diff --git a/.gitignore b/.gitignore index ca1c7a3..1b17ff9 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.user *.userosscache *.sln.docstates +*.dll # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/BackUpLogic.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..0d44934 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/BackUpLogic.cs @@ -0,0 +1,134 @@ +using FurnitureAssemblyContracts.BindingModels; +using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.StoragesContracts; +using FurnitureAssemblyDataModels; +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 FurnitureAssemblyBusinessLogic.BussinessLogic +{ + // Класс, реализующий логику для BackUp + 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(BackUpSaveBindingModel model) + { + // Проверка наличия данных для бэкапа + if (_backUpInfo == null) + { + return; + } + + try + { + _logger.LogDebug("Clear folder"); + + // Зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + + if (dirInfo.Exists) + { + // ЛУЧШЕ ВЫБИРАТЬ ОТДЕЛЬНО СОЗДАННУЮ ПАПКУ (Рабочий стол не использовать, поскольку с него всё удалится) + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + + _logger.LogDebug("Delete archive"); + + string fileName = $"{model.FolderName}.zip"; + + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + + // Берём метод для сохранения + _logger.LogDebug("Get assembly"); + + // Получение сборки и типов + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + + _logger.LogDebug("Find {count} types", types.Length); + + // Перебор типов и вызов метода для сохранения данных + foreach (var type in types) + { + // Проверка на то, является ли тип интерфейсом и унаследован ли он от 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); + + // Вызываем метод на выполнение (Вызываем метод типа MethodInfo) + 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); + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/ImplementerLogic.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/ImplementerLogic.cs index c1e236b..80a3fc5 100644 --- a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/ImplementerLogic.cs +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/ImplementerLogic.cs @@ -14,161 +14,161 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic { // Класс, реализующий логику для исполнителей public class ImplementerLogic : IImplementerLogic - { - private readonly ILogger _logger; + { + private readonly ILogger _logger; - private readonly IImplementerStorage _implementerStorage; + private readonly IImplementerStorage _implementerStorage; - // Конструктор - public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) - { - _logger = logger; - _implementerStorage = implementerStorage; - } + // Конструктор + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } - // Вывод всего отфильтрованного списка - public List? ReadList(ImplementerSearchModel? model) - { - _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); + // Вывод всего отфильтрованного списка + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); - // list хранит весь список в случае, если model пришло со значением null на вход метода - var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); + // list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.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 ImplementerViewModel? ReadElement(ImplementerSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + // Вывод конкретного элемента + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model?.Id); + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model?.Id); - var element = _implementerStorage.GetElement(model); + var element = _implementerStorage.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(ImplementerBindingModel model) - { - CheckModel(model); + // Создание работника + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); - if (_implementerStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - // Обновление данных о работнике - public bool Update(ImplementerBindingModel model) - { - CheckModel(model); + // Обновление данных о работнике + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); - if (_implementerStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - // Удаление работника - public bool Delete(ImplementerBindingModel model) - { - CheckModel(model, false); + // Удаление работника + public bool Delete(ImplementerBindingModel model) + { + CheckModel(model, false); - _logger.LogInformation("Delete. Id:{Id}", model.Id); + _logger.LogInformation("Delete. Id:{Id}", model.Id); - if (_implementerStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); - return false; - } + return false; + } - return true; - } + return true; + } - // Проверка входного аргумента для методов Insert, Update и Delete - private void CheckModel(ImplementerBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + // Проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - // Так как при удалении передаём как параметр false - if (!withParams) - { - return; - } + // Так как при удалении передаём как параметр false + if (!withParams) + { + return; + } - // Проверка на наличие ФИО - if (string.IsNullOrEmpty(model.ImplementerFIO)) - { - throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO)); - } + // Проверка на наличие ФИО + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO)); + } - // Проверка на наличие пароля - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); - } + // Проверка на наличие пароля + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); + } - // Проверка на наличие квалификации - if (model.Qualification <= 0) - { - throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification)); - } + // Проверка на наличие квалификации + if (model.Qualification <= 0) + { + throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification)); + } - // Проверка на наличие квалификации - if (model.WorkExperience < 0) - { - throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience)); - } + // Проверка на наличие квалификации + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience)); + } - _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " + - "Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}", - model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id); + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " + + "Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}", + model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id); - // Для проверка на наличие такого же аккаунта - var element = _implementerStorage.GetElement(new ImplementerSearchModel - { - ImplementerFIO = model.ImplementerFIO, - }); + // Для проверка на наличие такого же аккаунта + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); - // Если элемент найден и его Id не совпадает с Id переданного объекта - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Исполнитель с таким именем уже есть"); - } - } - } + // Если элемент найден и его Id не совпадает с Id переданного объекта + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким именем уже есть"); + } + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/OrderLogic.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/OrderLogic.cs index a5f8363..5e06ba5 100644 --- a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/OrderLogic.cs +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/OrderLogic.cs @@ -58,35 +58,35 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic } // Вывод конкретного чека - public OrderViewModel? ReadElement(OrderSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - _logger.LogInformation("ReadElement. Id:{Id}", model?.Id); + _logger.LogInformation("ReadElement. Id:{Id}", model?.Id); - var element = _orderStorage.GetElement(model); + var element = _orderStorage.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 CreateOrder(OrderBindingModel model) + // Создание чека + public bool CreateOrder(OrderBindingModel model) { CheckModel(model); - if(model.Status != OrderStatus.Неизвестен) + if (model.Status != OrderStatus.Неизвестен) { _logger.LogWarning("Insert operation failed, incorrect order status"); return false; @@ -95,7 +95,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic model.Status = OrderStatus.Принят; var result = _orderStorage.Insert(model); - + if (result == null) { model.Status = OrderStatus.Неизвестен; @@ -179,13 +179,13 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); // Если не смогли найти указанный заказ по его Id - if(viewModel == null) + if (viewModel == null) { throw new ArgumentNullException(nameof(model)); } // Проверка на возможность обновления статуса на следующий - if(viewModel.Status + 1 != newOrderStatus) + if (viewModel.Status + 1 != newOrderStatus) { _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + "incorrect"); return false; @@ -193,14 +193,14 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic model.Status = newOrderStatus; - // Помещаем id работника, не забываем про него... - if (viewModel.ImplementerId.HasValue) - { - model.ImplementerId = viewModel.ImplementerId; - } + // Помещаем id работника, не забываем про него... + if (viewModel.ImplementerId.HasValue) + { + model.ImplementerId = viewModel.ImplementerId; + } - // Проверка на выдачу - if (model.Status == OrderStatus.Выдан) + // Проверка на выдачу + if (model.Status == OrderStatus.Выдан) { model.DateImplement = DateTime.Now; } @@ -214,7 +214,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic // Финальная проверка на возможность обновления var result = _orderStorage.Update(model); - if(result == null) + if (result == null) { model.Status--; diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/WorkModeling.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/WorkModeling.cs index 6d7f567..1784d17 100644 --- a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/WorkModeling.cs +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/BussinessLogic/WorkModeling.cs @@ -12,155 +12,155 @@ using System.Threading.Tasks; namespace FurnitureAssemblyBusinessLogic.BussinessLogic { - public class WorkModeling : IWorkProcess - { - private readonly ILogger _logger; + public class WorkModeling : IWorkProcess + { + private readonly ILogger _logger; - private readonly Random _rnd; + private readonly Random _rnd; - private IOrderLogic? _orderLogic; + private IOrderLogic? _orderLogic; - // Конструктор - public WorkModeling(ILogger logger) - { - _logger = logger; - _rnd = new Random(1000); - } + // Конструктор + public WorkModeling(ILogger logger) + { + _logger = logger; + _rnd = new Random(1000); + } - public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) - { - _orderLogic = orderLogic; - var implementers = implementerLogic.ReadList(null); + public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + { + _orderLogic = orderLogic; + var implementers = implementerLogic.ReadList(null); - if (implementers == null) - { - _logger.LogWarning("DoWork. Implementers is null"); - return; - } + if (implementers == null) + { + _logger.LogWarning("DoWork. Implementers is null"); + return; + } - var orders = _orderLogic.ReadList(new OrderSearchModel - { - Status = OrderStatus.Принят - }); + var orders = _orderLogic.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); - if (orders == null || orders.Count == 0) - { - _logger.LogWarning("Dowork. Orders is null or empty"); - return; - } + if (orders == null || orders.Count == 0) + { + _logger.LogWarning("Dowork. Orders is null or empty"); + return; + } - _logger.LogDebug("DoWork for {count} orders", orders.Count); + _logger.LogDebug("DoWork for {count} orders", orders.Count); - foreach (var implementer in implementers) - { - Task.Run(() => WorkerWorkAsync(implementer, orders)); - } - } + foreach (var implementer in implementers) + { + Task.Run(() => WorkerWorkAsync(implementer, orders)); + } + } - // Имитация работы исполнителя - private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) - { - if (_orderLogic == null || implementer == null) - { - return; - } + // Имитация работы исполнителя + private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + { + if (_orderLogic == null || implementer == null) + { + return; + } - await RunOrderInWork(implementer); + await RunOrderInWork(implementer); - await Task.Run(() => - { - foreach (var order in orders) - { - try - { - _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); + await Task.Run(() => + { + foreach (var order in orders) + { + try + { + _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); - // Пытаемся назначить заказ на исполнителя - _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = order.Id, - ImplementerId = implementer.Id - }); + // Пытаемся назначить заказ на исполнителя + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); - // Работу работаем, делаем-делаем - Thread.Sleep(implementer.WorkExperience * order.Count); + // Работу работаем, делаем-делаем + Thread.Sleep(implementer.WorkExperience * order.Count); - _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); - _orderLogic.FinishOrder(new OrderBindingModel - { - Id = order.Id - }); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = order.Id + }); - // Усёёё отдыхаем - Thread.Sleep(implementer.Qualification); - } + // Усёёё отдыхаем + Thread.Sleep(implementer.Qualification); + } - // Игнорируем ошибку, если с заказом что-то случится - catch (InvalidOperationException ex) - { - _logger.LogWarning(ex, "Error try get work"); - } + // Игнорируем ошибку, если с заказом что-то случится + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } - // В случае ошибки прервём выполнение имитации работы - catch (Exception ex) - { - _logger.LogError(ex, "Error while do work"); - throw; - } - } - }); - } + // В случае ошибки прервём выполнение имитации работы + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + }); + } - // Ищем заказ, который уже во всю в работе (вдруг прервали исполнителя) - private async Task RunOrderInWork(ImplementerViewModel implementer) - { - if (_orderLogic == null || implementer == null) - { - return; - } + // Ищем заказ, который уже во всю в работе (вдруг прервали исполнителя) + private async Task RunOrderInWork(ImplementerViewModel implementer) + { + if (_orderLogic == null || implementer == null) + { + return; + } - try - { - var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel - { - ImplementerId = implementer.Id, - Status = OrderStatus.Выполняется - })); + try + { + var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel + { + ImplementerId = implementer.Id, + Status = OrderStatus.Выполняется + })); - if (runOrder == null) - { - return; - } + if (runOrder == null) + { + return; + } - _logger.LogDebug("DoWork {Id} back to order {Order}", implementer.Id, runOrder.Id); + _logger.LogDebug("DoWork {Id} back to order {Order}", implementer.Id, runOrder.Id); - // Доделываем работу - Thread.Sleep(implementer.WorkExperience * runOrder.Count); + // Доделываем работу + Thread.Sleep(implementer.WorkExperience * runOrder.Count); - _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); - _orderLogic.FinishOrder(new OrderBindingModel - { - Id = runOrder.Id - }); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = runOrder.Id + }); - // Отдыхаем, хватит работы - Thread.Sleep(implementer.Qualification); - } + // Отдыхаем, хватит работы + Thread.Sleep(implementer.Qualification); + } - // Заказа может не быть, просто игнорируем ошибку - catch (InvalidOperationException ex) - { - _logger.LogWarning(ex, "Error try get work"); - } + // Заказа может не быть, просто игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } - // Просто возникнет тупая ошибка, тогда заканчиваем выполнение имитации - catch (Exception ex) - { - _logger.LogError(ex, "Error while do work"); - throw; - } - } - } + // Просто возникнет тупая ошибка, тогда заканчиваем выполнение имитации + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index 987a54a..863ebaa 100644 --- a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -14,7 +14,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; - //список заготовок для вывода и сохранения + // Cписок заготовок для вывода и сохранения public List Furnitures { get; set; } = new(); } } diff --git a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs index 12c062a..ada3aa6 100644 --- a/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs +++ b/FurnitureAssembly/FurnitureAssemblyBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -12,7 +12,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels // Набор текстов в абзаце (для случая, если в абзаце текст разных стилей) public List<(string, WordTextProperties)> Texts { get; set; } = new(); - //свойства параграфа, если они есть + // Cвойства параграфа, если они есть public WordTextProperties? TextProperties { get; set; } } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/ColumnAttribute.cs b/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..ef344a9 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.Attributes +{ + // Укажем, что данный атрибут можно прописать только в Property + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public ColumnAttribute(string title = "", bool visible = true, int width = 0, + GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + + public string Title { get; private set; } + + public bool Visible { get; private set; } + + public int Width { get; private set; } + + public GridViewAutoSize GridViewAutoSize { get; private set; } + + public bool IsUseAutoSize { get; private set; } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/GridViewAutoSize.cs b/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..bf31304 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/BackUpSaveBindingModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/BackUpSaveBindingModel.cs new file mode 100644 index 0000000..c37c1d2 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/BackUpSaveBindingModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.BindingModels +{ + public class BackUpSaveBindingModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/MessageInfoBindingModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/MessageInfoBindingModel.cs index 6c4ef95..f7f3f21 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/MessageInfoBindingModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/BindingModels/MessageInfoBindingModel.cs @@ -7,9 +7,11 @@ using System.Threading.Tasks; namespace FurnitureAssemblyContracts.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/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IBackUpLogic.cs b/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..ff03de5 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,16 @@ +using FurnitureAssemblyContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.BusinessLogicsContracts +{ + // Интерфейс создания бекапа + public interface IBackUpLogic + { + // Путь и имя файла для архивации + void CreateBackUp(BackUpSaveBindingModel model); + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IWorkProcess.cs b/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IWorkProcess.cs index 6c654db..e0a5ad5 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IWorkProcess.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -6,10 +6,10 @@ using System.Threading.Tasks; namespace FurnitureAssemblyContracts.BusinessLogicsContracts { - // Интерфейс для класса, имитирующего работу - public interface IWorkProcess - { - // Запуск работы - void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); - } + // Интерфейс для класса, имитирующего работу + public interface IWorkProcess + { + // Запуск работы + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/DI/DependencyManager.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..6b25f65 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/DI/DependencyManager.cs @@ -0,0 +1,60 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.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(); + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/DI/IDependencyContainer.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..fec4ae8 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/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 FurnitureAssemblyContracts.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(); + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/DI/IImplementationExtension.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..6b4d9ff --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/DI/IImplementationExtension.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.DI +{ + // Интерфейс для регистрации зависимостей в модулях + public interface IImplementationExtension + { + // Для установления приоритета + public int Priority { get; } + + // Регистрация сервисов + public void RegisterServices(); + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/DI/ServiceDependencyContainer.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..63ee44a --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,65 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.DI +{ + public class ServiceDependencyContainer : IDependencyContainer + { + private ServiceProvider? _serviceProvider; + + private readonly ServiceCollection _serviceCollection; + + public ServiceDependencyContainer() + { + _serviceCollection = new ServiceCollection(); + } + + public void AddLogging(Action configure) + { + _serviceCollection.AddLogging(configure); + } + + public void RegisterType(bool isSingle) where U : class, T where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + + _serviceProvider = null; + } + + public void RegisterType(bool isSingle) where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + + _serviceProvider = null; + } + + public T Resolve() + { + if (_serviceProvider == null) + { + _serviceProvider = _serviceCollection.BuildServiceProvider(); + } + + return _serviceProvider.GetService()!; + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/DI/ServiceProviderLoader.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..10d820f --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/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 FurnitureAssemblyContracts.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/FurnitureAssembly/FurnitureAssemblyContracts/DI/UnityDependencyContainer.cs b/FurnitureAssembly/FurnitureAssemblyContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..dbb5127 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,42 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Unity.Microsoft.Logging; +using Unity; + +namespace FurnitureAssemblyContracts.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); + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/FurnitureAssemblyContracts.csproj b/FurnitureAssembly/FurnitureAssemblyContracts/FurnitureAssemblyContracts.csproj index 04f9955..02bfc6a 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/FurnitureAssemblyContracts.csproj +++ b/FurnitureAssembly/FurnitureAssemblyContracts/FurnitureAssemblyContracts.csproj @@ -6,6 +6,12 @@ enable + + + + + + diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/SearchModels/ImplementerSearchModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/SearchModels/ImplementerSearchModel.cs index 4821d93..4989565 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/SearchModels/ImplementerSearchModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/SearchModels/ImplementerSearchModel.cs @@ -8,15 +8,15 @@ namespace FurnitureAssemblyContracts.SearchModels { // Модель для поиска исполнителя public class ImplementerSearchModel - { - public int? Id { get; set; } + { + public int? Id { get; set; } - public string? ImplementerFIO { get; set; } + public string? ImplementerFIO { get; set; } - public string? Password { get; set; } + public string? Password { get; set; } - public int? WorkExperience { get; set; } + public int? WorkExperience { get; set; } - public int? Qualification { get; set; } - } + public int? Qualification { get; set; } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IBackUpInfo.cs b/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..9940335 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyContracts.StoragesContracts +{ + // Интерфейс получения данных по всем сущностям + public interface IBackUpInfo + { + // Метод получения данных по всем сущностям + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IImplementerStorage.cs b/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IImplementerStorage.cs index f37fd81..0015138 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IImplementerStorage.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/StoragesContracts/IImplementerStorage.cs @@ -11,17 +11,17 @@ namespace FurnitureAssemblyContracts.StoragesContracts { // Класс для хранилища исполнителей public interface IImplementerStorage - { - List GetFullList(); + { + List GetFullList(); - List GetFilteredList(ImplementerSearchModel model); + List GetFilteredList(ImplementerSearchModel model); - ImplementerViewModel? GetElement(ImplementerSearchModel model); + ImplementerViewModel? GetElement(ImplementerSearchModel model); - ImplementerViewModel? Insert(ImplementerBindingModel model); + ImplementerViewModel? Insert(ImplementerBindingModel model); - ImplementerViewModel? Update(ImplementerBindingModel model); + ImplementerViewModel? Update(ImplementerBindingModel model); - ImplementerViewModel? Delete(ImplementerBindingModel model); - } + ImplementerViewModel? Delete(ImplementerBindingModel model); + } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ClientViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ClientViewModel.cs index 68687de..60ecd6b 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ClientViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Models; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,15 +12,16 @@ namespace FurnitureAssemblyContracts.ViewModels // Класс для отображения информации о клиентах public class ClientViewModel : IClientModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] + [Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 150)] public string Password { get; set; } = string.Empty; } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/FurnitureViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/FurnitureViewModel.cs index f24f746..ba4f64e 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/FurnitureViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/FurnitureViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Models; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,14 +12,16 @@ namespace FurnitureAssemblyContracts.ViewModels // Класс для отображения пользователю информации о продуктах (изделиях) public class FurnitureViewModel : IFurnitureModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название изделия")] + [Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string FurnitureName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Price { get; set; } + [Column(visible: false)] public Dictionary FurnitureWorkPieces { get; set; } = new(); } } \ No newline at end of file diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ImplementerViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ImplementerViewModel.cs index eb81af6..c317b39 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ImplementerViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Models; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,19 +11,20 @@ namespace FurnitureAssemblyContracts.ViewModels { // Класс для отображения информации об исполнителях public class ImplementerViewModel : IImplementerModel - { - public int Id { get; set; } + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "ФИО исполнителя", width: 150)] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 150)] + public string Password { get; set; } = string.Empty; - [DisplayName("Стаж")] - public int WorkExperience { get; set; } + [Column(title: "Стаж", width: 150)] + public int WorkExperience { get; set; } - [DisplayName("Квалификация")] - public int Qualification { get; set; } - } + [Column(title: "Квалификация", width: 150)] + public int Qualification { get; set; } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/MessageInfoViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/MessageInfoViewModel.cs index 16c929b..2f95c09 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/MessageInfoViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Models; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,20 +12,25 @@ namespace FurnitureAssemblyContracts.ViewModels // Класс для отображения пользователю информации о сообщениях public class MessageInfoViewModel : IMessageInfoModel { + [Column(visible: false)] + public int Id { get; set; } + + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; - public int? ClientId { get; set; } + [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; } } diff --git a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/OrderViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/OrderViewModel.cs index 637df08..b094861 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/OrderViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Enums; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Enums; using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; @@ -12,37 +13,40 @@ namespace FurnitureAssemblyContracts.ViewModels // Класс для отображения пользователю информации о заказах public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(visible: false)] public int Id { get; set; } + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] public int? ImplementerId { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", width: 150)] public string ImplementerFIO { get; set; } = string.Empty; + [Column(visible: false)] public int FurnitureId { get; set; } - [DisplayName("Изделие")] + [Column(title: "Изделие", width: 150)] public string FurnitureName { 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/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/WorkPieceViewModel.cs b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/WorkPieceViewModel.cs index 8eb29ab..4bd7592 100644 --- a/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/WorkPieceViewModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyContracts/ViewModels/WorkPieceViewModel.cs @@ -1,4 +1,5 @@ -using FurnitureAssemblyDataModels.Models; +using FurnitureAssemblyContracts.Attributes; +using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,12 +12,13 @@ namespace FurnitureAssemblyContracts.ViewModels // Класс для отображения пользователю данных о заготовке (заготовках) public class WorkPieceViewModel : IWorkPieceModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название заготовки")] + [Column(title: "Название заготовки", width: 150)] public string WorkPieceName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Cost { get; set; } } } \ No newline at end of file diff --git a/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IImplementerModel.cs b/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IImplementerModel.cs index 75d8518..b20edc0 100644 --- a/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IImplementerModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IImplementerModel.cs @@ -8,13 +8,13 @@ namespace FurnitureAssemblyDataModels.Models { // Интерфейс, отвечающий за исполнителя public interface IImplementerModel : IId - { - string ImplementerFIO { get; } + { + string ImplementerFIO { get; } - string Password { get; } + string Password { get; } - int WorkExperience { get; } + int WorkExperience { get; } - int Qualification { get; } - } + int Qualification { get; } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IMessageInfoModel.cs b/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IMessageInfoModel.cs index 4292b62..d1e064c 100644 --- a/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IMessageInfoModel.cs +++ b/FurnitureAssembly/FurnitureAssemblyDataModels/Models/IMessageInfoModel.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace FurnitureAssemblyDataModels.Models { // Интерфейс, отвечающий за сообщения - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/DataBaseImplementationExtension.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/DataBaseImplementationExtension.cs new file mode 100644 index 0000000..a41af44 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/DataBaseImplementationExtension.cs @@ -0,0 +1,33 @@ +using FurnitureAssemblyContracts.DI; +using FurnitureAssemblyContracts.StoragesContracts; +using FurnitureAssemblyDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyDatabaseImplement +{ + 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(); + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/FurnitureAssemblyDatabaseImplement.csproj b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/FurnitureAssemblyDatabaseImplement.csproj index 481038d..096af5a 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/FurnitureAssemblyDatabaseImplement.csproj +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/FurnitureAssemblyDatabaseImplement.csproj @@ -1,23 +1,31 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - - - + + + + + + + + + + + + diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/BackUpInfo.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..5840415 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,35 @@ +using FurnitureAssemblyContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new FurnitureAssemblyDatabase(); + + 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; + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/ImplementerStorage.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/ImplementerStorage.cs index 5ba5b06..742acb8 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/ImplementerStorage.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/ImplementerStorage.cs @@ -12,96 +12,96 @@ using System.Threading.Tasks; namespace FurnitureAssemblyDatabaseImplement.Implements { - public class ImplementerStorage : IImplementerStorage - { - public ImplementerViewModel? GetElement(ImplementerSearchModel model) - { - using var context = new FurnitureAssemblyDatabase(); + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new FurnitureAssemblyDatabase(); - if (model.Id.HasValue) - return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.Id.HasValue) + return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.ImplementerFIO != null && model.Password != null) - return context.Implementers.FirstOrDefault(x => x.ImplementerFIO - .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return context.Implementers.FirstOrDefault(x => x.ImplementerFIO + .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; - if (model.ImplementerFIO != null) - return context.Implementers.FirstOrDefault(x => x.ImplementerFIO - .Equals(model.ImplementerFIO))?.GetViewModel; + if (model.ImplementerFIO != null) + return context.Implementers.FirstOrDefault(x => x.ImplementerFIO + .Equals(model.ImplementerFIO))?.GetViewModel; - return null; - } + return null; + } - public List GetFilteredList(ImplementerSearchModel model) - { - if (model == null) - { - return new(); - } + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } - if (model.ImplementerFIO != null) - { - using var context = new FurnitureAssemblyDatabase(); + if (model.ImplementerFIO != null) + { + using var context = new FurnitureAssemblyDatabase(); - return context.Implementers - .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) - .Select(x => x.GetViewModel) - .ToList(); - } + return context.Implementers + .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } - return new(); - } + return new(); + } - public List GetFullList() - { - using var context = new FurnitureAssemblyDatabase(); + public List GetFullList() + { + using var context = new FurnitureAssemblyDatabase(); - return context.Implementers.Select(x => x.GetViewModel).ToList(); - } + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } - public ImplementerViewModel? Insert(ImplementerBindingModel model) - { - using var context = new FurnitureAssemblyDatabase(); + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new FurnitureAssemblyDatabase(); - var res = Implementer.Create(model); + var res = Implementer.Create(model); - if (res != null) - { - context.Implementers.Add(res); - context.SaveChanges(); - } + if (res != null) + { + context.Implementers.Add(res); + context.SaveChanges(); + } - return res?.GetViewModel; - } + return res?.GetViewModel; + } - public ImplementerViewModel? Update(ImplementerBindingModel model) - { - using var context = new FurnitureAssemblyDatabase(); + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new FurnitureAssemblyDatabase(); - var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (res != null) - { - res.Update(model); - context.SaveChanges(); - } + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } - return res?.GetViewModel; - } + return res?.GetViewModel; + } - public ImplementerViewModel? Delete(ImplementerBindingModel model) - { - using var context = new FurnitureAssemblyDatabase(); + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new FurnitureAssemblyDatabase(); - var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (res != null) - { - context.Implementers.Remove(res); - context.SaveChanges(); - } + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } - return res?.GetViewModel; - } - } + return res?.GetViewModel; + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240511234747_InitialCreate.Designer.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240518234238_InitialCreate.Designer.cs similarity index 99% rename from FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240511234747_InitialCreate.Designer.cs rename to FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240518234238_InitialCreate.Designer.cs index d2b2599..954ebb6 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240511234747_InitialCreate.Designer.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240518234238_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace FurnitureAssemblyDatabaseImplement.Migrations { [DbContext(typeof(FurnitureAssemblyDatabase))] - [Migration("20240511234747_InitialCreate")] + [Migration("20240518234238_InitialCreate")] partial class InitialCreate { /// diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240511234747_InitialCreate.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240518234238_InitialCreate.cs similarity index 100% rename from FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240511234747_InitialCreate.cs rename to FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Migrations/20240518234238_InitialCreate.cs diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Client.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Client.cs index af77220..18af9d6 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Client.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Client.cs @@ -8,20 +8,26 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string ClientFIO { get; private set; } = string.Empty; [Required] + [DataMember] public string Email { get; private set; } = string.Empty; [Required] + [DataMember] public string Password { get; private set; } = string.Empty; // Для реализации связи многие-ко-многим с заказами (клиенты могу сделать одинаковый заказ) diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Furniture.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Furniture.cs index b2f1f02..ec7b5d9 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Furniture.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Furniture.cs @@ -7,25 +7,31 @@ 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 FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class Furniture : IFurnitureModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string FurnitureName { get; set; } = string.Empty; [Required] + [DataMember] public double Price { get; set; } public Dictionary? _furnitureWorkPieces = null; // Это поле не будет "мапиться" в бд [NotMapped] + [DataMember] public Dictionary FurnitureWorkPieces { get diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/FurnitureWorkPiece.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/FurnitureWorkPiece.cs index 688440d..65644dd 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/FurnitureWorkPiece.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/FurnitureWorkPiece.cs @@ -2,11 +2,13 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class FurnitureWorkPiece { public int Id { get; set; } diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Implementer.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Implementer.cs index fc93d8b..03e5610 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Implementer.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Implementer.cs @@ -8,24 +8,31 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { - public int Id { get; set; } + [DataMember] + public int Id { get; set; } [Required] - public string ImplementerFIO { get; set; } = string.Empty; + [DataMember] + public string ImplementerFIO { get; set; } = string.Empty; [Required] - public string Password { get; set; } = string.Empty; + [DataMember] + public string Password { get; set; } = string.Empty; [Required] - public int WorkExperience { get; set; } + [DataMember] + public int WorkExperience { get; set; } [Required] - public int Qualification { get; set; } + [DataMember] + public int Qualification { get; set; } // Для реализации связи один ко многим с заказами [ForeignKey("ImplementerId")] diff --git a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/MessageInfo.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/MessageInfo.cs index 7a59a32..fe1647e 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/MessageInfo.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/MessageInfo.cs @@ -5,29 +5,30 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FurnitureAssemblyDatabaseImplement.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/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Order.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Order.cs index b47e03f..8b2569b 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Order.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/Order.cs @@ -6,35 +6,46 @@ 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 FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public int FurnitureId { 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/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/WorkPiece.cs b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/WorkPiece.cs index 7bf4529..0620c1c 100644 --- a/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/WorkPiece.cs +++ b/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Models/WorkPiece.cs @@ -6,19 +6,24 @@ 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 FurnitureAssemblyDatabaseImplement.Models { + [DataContract] public class WorkPiece : IWorkPieceModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string WorkPieceName { get; private set; } = string.Empty; [Required] + [DataMember] public double Cost { get; set; } // для реализации связи многие ко многим с изделиями diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/FileImplementationExtension.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..2606f41 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/FileImplementationExtension.cs @@ -0,0 +1,34 @@ +using FurnitureAssemblyContracts.DI; +using FurnitureAssemblyContracts.StoragesContracts; +using FurnitureAssemblyFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyFileImplement +{ + // Для реализации нужных нам зависимостей в данном варианте хранения информации + 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(); + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/FurnitureAssemblyFileImplement.csproj b/FurnitureAssembly/FurnitureAssemblyFileImplement/FurnitureAssemblyFileImplement.csproj index c0fa55b..9a3ae31 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/FurnitureAssemblyFileImplement.csproj +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/FurnitureAssemblyFileImplement.csproj @@ -1,14 +1,18 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - + + + + + + + + diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/BackUpInfo.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..8833636 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,37 @@ +using FurnitureAssemblyContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + var source = DataFileSingleton.GetInstance(); + + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + + 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; + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/ImplementerStorage.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/ImplementerStorage.cs index 6fe21ff..ac14b08 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/ImplementerStorage.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Implements/ImplementerStorage.cs @@ -11,102 +11,102 @@ using System.Threading.Tasks; namespace FurnitureAssemblyFileImplement.Implements { - public class ImplementerStorage : IImplementerStorage - { - private readonly DataFileSingleton source; + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton source; - public ImplementerStorage() - { - source = DataFileSingleton.GetInstance(); - } + public ImplementerStorage() + { + source = DataFileSingleton.GetInstance(); + } - public ImplementerViewModel? GetElement(ImplementerSearchModel model) - { - if (model.Id.HasValue) - return source.Implementers - .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - - if (model.ImplementerFIO != null && model.Password != null) - return source.Implementers.FirstOrDefault(x => x.ImplementerFIO - .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; - - if (model.ImplementerFIO != null) - return source.Implementers - .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; - - return null; - } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + return source.Implementers + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + + if (model.ImplementerFIO != null && model.Password != null) + return source.Implementers.FirstOrDefault(x => x.ImplementerFIO + .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; + + if (model.ImplementerFIO != null) + return source.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + + return null; + } - public List GetFullList() - { - return source.Implementers.Select(x => x.GetViewModel).ToList(); - } + public List GetFullList() + { + return source.Implementers.Select(x => x.GetViewModel).ToList(); + } - public List GetFilteredList(ImplementerSearchModel model) - { - if (model == null) - { - return new(); - } + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } - if (model.ImplementerFIO != null) - { - return source.Implementers - .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); - } + if (model.ImplementerFIO != null) + { + return source.Implementers + .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } - return new(); - } + return new(); + } - public ImplementerViewModel? Insert(ImplementerBindingModel model) - { - model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1; + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1; - var newImplementer = Implementer.Create(model); + var newImplementer = Implementer.Create(model); - if (newImplementer == null) - { - return null; - } + if (newImplementer == null) + { + return null; + } - source.Implementers.Add(newImplementer); - source.SaveImplementers(); + source.Implementers.Add(newImplementer); + source.SaveImplementers(); - return newImplementer.GetViewModel; - } + return newImplementer.GetViewModel; + } - public ImplementerViewModel? Update(ImplementerBindingModel model) - { - var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (implementer == null) - { - return null; - } + if (implementer == null) + { + return null; + } - implementer.Update(model); - source.SaveImplementers(); + implementer.Update(model); + source.SaveImplementers(); - return implementer.GetViewModel; - } + return implementer.GetViewModel; + } - public ImplementerViewModel? Delete(ImplementerBindingModel model) - { - var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (element != null) - { - source.Implementers.Remove(element); - source.SaveImplementers(); + if (element != null) + { + source.Implementers.Remove(element); + source.SaveImplementers(); - return element.GetViewModel; - } + return element.GetViewModel; + } - return null; - } - } + return null; + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Client.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Client.cs index b5dae44..8e00ade 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Client.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Client.cs @@ -4,20 +4,26 @@ using FurnitureAssemblyDataModels.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 FurnitureAssemblyFileImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ClientFIO { get; private set; } = string.Empty; + [DataMember] public string Email { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Furniture.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Furniture.cs index d428d39..e5b719e 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Furniture.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Furniture.cs @@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.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; @@ -11,18 +12,23 @@ using System.Xml.Linq; namespace FurnitureAssemblyFileImplement.Models { // Класс, реализующий интерфейс модели изделия + [DataContract] public class Furniture : IFurnitureModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string FurnitureName { get; private set; } = string.Empty; + [DataMember] public double Price { get; private set; } public Dictionary WorkPieces { get; private set; } = new(); private Dictionary? _furnitureWorkPieces = null; + [DataMember] public Dictionary FurnitureWorkPieces { get diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Implementer.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Implementer.cs index 2d1f696..c812573 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Implementer.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Implementer.cs @@ -4,22 +4,29 @@ using FurnitureAssemblyDataModels.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 FurnitureAssemblyFileImplement.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/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/MessageInfo.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/MessageInfo.cs index 91aeaf2..acf0db0 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/MessageInfo.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/MessageInfo.cs @@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -11,18 +12,27 @@ using System.Xml.Linq; namespace FurnitureAssemblyFileImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + public int Id { get; 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; + public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Order.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Order.cs index 4384655..59c79a4 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Order.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Order.cs @@ -5,6 +5,7 @@ using FurnitureAssemblyDataModels.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; @@ -12,24 +13,34 @@ using System.Xml.Linq; namespace FurnitureAssemblyFileImplement.Models { // Класс, реализующий интерфейс модели заказа + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int FurnitureId { get; private set; } + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } + [DataMember] public int Count { get; private set; } + [DataMember] public double Sum { get; private set; } + [DataMember] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; private set; } public static Order? Create(OrderBindingModel model) diff --git a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/WorkPiece.cs b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/WorkPiece.cs index 125494d..f8330c8 100644 --- a/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/WorkPiece.cs +++ b/FurnitureAssembly/FurnitureAssemblyFileImplement/Models/WorkPiece.cs @@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.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; @@ -11,12 +12,16 @@ using System.Xml.Linq; namespace FurnitureAssemblyFileImplement.Models { // Класс, реализующий интерфейс модели заготовки + [DataContract] public class WorkPiece : IWorkPieceModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string WorkPieceName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } public static WorkPiece? Create(WorkPieceBindingModel model) diff --git a/FurnitureAssembly/FurnitureAssemblyListImplement/FurnitureAssemblyListImplement.csproj b/FurnitureAssembly/FurnitureAssemblyListImplement/FurnitureAssemblyListImplement.csproj index c0fa55b..c5df54f 100644 --- a/FurnitureAssembly/FurnitureAssemblyListImplement/FurnitureAssemblyListImplement.csproj +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/FurnitureAssemblyListImplement.csproj @@ -1,14 +1,14 @@ - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - + + + + diff --git a/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/BackUpInfo.cs b/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..17649c2 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,22 @@ +using FurnitureAssemblyContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + throw new NotImplementedException(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + throw new NotImplementedException(); + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/ImplementerStorage.cs b/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/ImplementerStorage.cs index a6e3d64..dc9d479 100644 --- a/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/ImplementerStorage.cs +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/Implements/ImplementerStorage.cs @@ -11,120 +11,120 @@ using System.Threading.Tasks; namespace FurnitureAssemblyListImplement.Implements { - public class ImplementerStorage : IImplementerStorage - { - // Поле для работы со списком исполнителей - private readonly DataListSingleton _source; + public class ImplementerStorage : IImplementerStorage + { + // Поле для работы со списком исполнителей + private readonly DataListSingleton _source; - public ImplementerStorage() - { - _source = DataListSingleton.GetInstance(); - } + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } - public List GetFullList() - { - var result = new List(); + public List GetFullList() + { + var result = new List(); - foreach (var implementer in _source.Implementers) - { - result.Add(implementer.GetViewModel); - } + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } - return result; - } + return result; + } - public List GetFilteredList(ImplementerSearchModel model) - { - var result = new List(); + public List GetFilteredList(ImplementerSearchModel model) + { + var result = new List(); - if (string.IsNullOrEmpty(model.ImplementerFIO)) - { - return result; - } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return result; + } - foreach (var implementer in _source.Implementers) - { - if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) - { - result.Add(implementer.GetViewModel); - } - } + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } - return result; - } + return result; + } - public ImplementerViewModel? GetElement(ImplementerSearchModel model) - { - if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) - { - return null; - } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) + { + return null; + } - foreach (var implementer in _source.Implementers) - { - if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) || - (model.Id.HasValue && implementer.Id == model.Id)) - { - return implementer.GetViewModel; - } - } + foreach (var implementer in _source.Implementers) + { + if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) || + (model.Id.HasValue && implementer.Id == model.Id)) + { + return implementer.GetViewModel; + } + } - return null; - } + return null; + } - public ImplementerViewModel? Insert(ImplementerBindingModel model) - { - model.Id = 1; + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = 1; - foreach (var implementer in _source.Implementers) - { - if (model.Id <= implementer.Id) - { - model.Id = implementer.Id + 1; - } - } + foreach (var implementer in _source.Implementers) + { + if (model.Id <= implementer.Id) + { + model.Id = implementer.Id + 1; + } + } - var newImplementer = Implementer.Create(model); + var newImplementer = Implementer.Create(model); - if (newImplementer == null) - { - return null; - } + if (newImplementer == null) + { + return null; + } - _source.Implementers.Add(newImplementer); + _source.Implementers.Add(newImplementer); - return newImplementer.GetViewModel; - } + return newImplementer.GetViewModel; + } - public ImplementerViewModel? Update(ImplementerBindingModel model) - { - foreach (var implementer in _source.Implementers) - { - if (implementer.Id == model.Id) - { - implementer.Update(model); + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == model.Id) + { + implementer.Update(model); - return implementer.GetViewModel; - } - } + return implementer.GetViewModel; + } + } - return null; - } + return null; + } - public ImplementerViewModel? Delete(ImplementerBindingModel model) - { - for (int i = 0; i < _source.Implementers.Count; ++i) - { - if (_source.Implementers[i].Id == model.Id) - { - var element = _source.Implementers[i]; - _source.Implementers.RemoveAt(i); + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + for (int i = 0; i < _source.Implementers.Count; ++i) + { + if (_source.Implementers[i].Id == model.Id) + { + var element = _source.Implementers[i]; + _source.Implementers.RemoveAt(i); - return element.GetViewModel; - } - } + return element.GetViewModel; + } + } - return null; - } - } + return null; + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyListImplement/ListImplementationExtension.cs b/FurnitureAssembly/FurnitureAssemblyListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..c913969 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/ListImplementationExtension.cs @@ -0,0 +1,33 @@ +using FurnitureAssemblyContracts.DI; +using FurnitureAssemblyContracts.StoragesContracts; +using FurnitureAssemblyListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyListImplement +{ + 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/FurnitureAssembly/FurnitureAssemblyListImplement/Models/Implementer.cs b/FurnitureAssembly/FurnitureAssemblyListImplement/Models/Implementer.cs index 7afd835..902a2a0 100644 --- a/FurnitureAssembly/FurnitureAssemblyListImplement/Models/Implementer.cs +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/Models/Implementer.cs @@ -9,58 +9,58 @@ using System.Threading.Tasks; namespace FurnitureAssemblyListImplement.Models { - public class Implementer : IImplementerModel - { - public int Id { get; private set; } + public class Implementer : IImplementerModel + { + public int Id { get; private set; } - public string ImplementerFIO { get; private set; } = string.Empty; + public string ImplementerFIO { get; private set; } = string.Empty; - public string Password { get; private set; } = string.Empty; + public string Password { get; private set; } = string.Empty; - public int WorkExperience { get; private set; } + public int WorkExperience { get; private set; } - public int Qualification { get; private set; } + public int Qualification { get; private set; } - // Метод для создания объекта от класса-компонента на основе класса-BindingModel - public static Implementer? Create(ImplementerBindingModel? model) - { - if (model == null) - { - return null; - } + // Метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } - return new Implementer() - { - Id = model.Id, - Password = model.Password, - ImplementerFIO = model.ImplementerFIO, - Qualification = model.Qualification, - WorkExperience = model.WorkExperience - }; - } + return new Implementer() + { + Id = model.Id, + Password = model.Password, + ImplementerFIO = model.ImplementerFIO, + Qualification = model.Qualification, + WorkExperience = model.WorkExperience + }; + } - // Метод изменения существующего объекта - public void Update(ImplementerBindingModel? model) - { - if (model == null) - { - return; - } + // Метод изменения существующего объекта + public void Update(ImplementerBindingModel? model) + { + if (model == null) + { + return; + } - Password = model.Password; - ImplementerFIO = model.ImplementerFIO; - Qualification = model.Qualification; - WorkExperience = model.WorkExperience; - } + Password = model.Password; + ImplementerFIO = model.ImplementerFIO; + Qualification = model.Qualification; + WorkExperience = model.WorkExperience; + } - // Метод для создания объекта класса ViewModel на основе данных объекта класса-компонента - public ImplementerViewModel GetViewModel => new() - { - Id = Id, - Password = Password, - ImplementerFIO = ImplementerFIO, - Qualification = Qualification, - WorkExperience = WorkExperience - }; - } + // Метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + ImplementerFIO = ImplementerFIO, + Qualification = Qualification, + WorkExperience = WorkExperience + }; + } } diff --git a/FurnitureAssembly/FurnitureAssemblyListImplement/Models/MessageInfo.cs b/FurnitureAssembly/FurnitureAssemblyListImplement/Models/MessageInfo.cs index af5b220..b86e808 100644 --- a/FurnitureAssembly/FurnitureAssemblyListImplement/Models/MessageInfo.cs +++ b/FurnitureAssembly/FurnitureAssemblyListImplement/Models/MessageInfo.cs @@ -12,6 +12,8 @@ namespace FurnitureAssemblyListImplement.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/FurnitureAssembly/FurnitureAssemblyRestApi/Controllers/ImplementerController.cs b/FurnitureAssembly/FurnitureAssemblyRestApi/Controllers/ImplementerController.cs index 4e2db8a..183fd38 100644 --- a/FurnitureAssembly/FurnitureAssemblyRestApi/Controllers/ImplementerController.cs +++ b/FurnitureAssembly/FurnitureAssemblyRestApi/Controllers/ImplementerController.cs @@ -7,106 +7,106 @@ using Microsoft.AspNetCore.Mvc; namespace FurnitureAssemblyRestApi.Controllers { - [Route("api/[controller]/[action]")] - [ApiController] - public class ImplementerController : Controller - { - private readonly ILogger _logger; + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : Controller + { + private readonly ILogger _logger; - private readonly IOrderLogic _order; + private readonly IOrderLogic _order; - private readonly IImplementerLogic _logic; + private readonly IImplementerLogic _logic; - public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) - { - _logger = logger; - _order = order; - _logic = logic; - } + public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) + { + _logger = logger; + _order = order; + _logic = logic; + } - [HttpGet] - public ImplementerViewModel? Login(string login, string password) - { - try - { - return _logic.ReadElement(new ImplementerSearchModel - { - ImplementerFIO = login, - Password = password - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка авторизации сотрудника"); + [HttpGet] + public ImplementerViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ImplementerSearchModel + { + ImplementerFIO = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка авторизации сотрудника"); - throw; - } - } + throw; + } + } - [HttpGet] - public List? GetNewOrders() - { - try - { - return _order.ReadList(new OrderSearchModel - { - Status = OrderStatus.Принят - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка получения новых заказов"); + [HttpGet] + public List? GetNewOrders() + { + try + { + return _order.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения новых заказов"); - throw; - } - } + throw; + } + } - [HttpGet] - public OrderViewModel? GetImplementerOrder(int implementerId) - { - try - { - return _order.ReadElement(new OrderSearchModel - { - ImplementerId = implementerId - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); + [HttpGet] + public OrderViewModel? GetImplementerOrder(int implementerId) + { + try + { + return _order.ReadElement(new OrderSearchModel + { + ImplementerId = implementerId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); - throw; - } - } + throw; + } + } - [HttpPost] - public void TakeOrderInWork(OrderBindingModel model) - { - try - { - _order.TakeOrderInWork(model); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); + [HttpPost] + public void TakeOrderInWork(OrderBindingModel model) + { + try + { + _order.TakeOrderInWork(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); - throw; - } - } + throw; + } + } - [HttpPost] - public void FinishOrder(OrderBindingModel model) - { - try - { - _order.FinishOrder(model); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id); + [HttpPost] + public void FinishOrder(OrderBindingModel model) + { + try + { + _order.FinishOrder(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id); - throw; - } - } - } + throw; + } + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyRestApi/FurnitureAssemblyRestApi.csproj b/FurnitureAssembly/FurnitureAssemblyRestApi/FurnitureAssemblyRestApi.csproj index d987301..e347951 100644 --- a/FurnitureAssembly/FurnitureAssemblyRestApi/FurnitureAssemblyRestApi.csproj +++ b/FurnitureAssembly/FurnitureAssemblyRestApi/FurnitureAssemblyRestApi.csproj @@ -1,20 +1,20 @@  - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - + + + + - - - - - + + + + + diff --git a/FurnitureAssembly/FurnitureAssemblyView/DataGridViewExtension.cs b/FurnitureAssembly/FurnitureAssemblyView/DataGridViewExtension.cs new file mode 100644 index 0000000..1ba84a8 --- /dev/null +++ b/FurnitureAssembly/FurnitureAssemblyView/DataGridViewExtension.cs @@ -0,0 +1,62 @@ +using FurnitureAssemblyContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FurnitureAssemblyView +{ + 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; + } + } + } + } + } +} diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormClients.cs b/FurnitureAssembly/FurnitureAssemblyView/FormClients.cs index 0e0fa8d..9f52ee4 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormClients.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormClients.cs @@ -35,18 +35,11 @@ namespace FurnitureAssemblyView private void LoadData() { - _logger.LogInformation("Загрузка клиентов"); + _logger.LogInformation("Загрузка клиентов"); - try + try { - var list = _clientLogic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - + dataGridView.FillandConfigGrid(_clientLogic.ReadList(null)); _logger.LogInformation("Успешная загрузка клиентов"); } catch (Exception ex) diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormFurniture.cs b/FurnitureAssembly/FurnitureAssemblyView/FormFurniture.cs index d52ab40..befd832 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormFurniture.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormFurniture.cs @@ -1,5 +1,6 @@ using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.DI; using FurnitureAssemblyContracts.SearchModels; using FurnitureAssemblyDataModels.Models; using Microsoft.Extensions.Logging; @@ -35,7 +36,7 @@ namespace FurnitureAssemblyView _logic = logic; _furnitureWorkPieces = new Dictionary(); } - + private void FormFurniture_Load(object sender, EventArgs e) { if (_id.HasValue) @@ -46,7 +47,7 @@ namespace FurnitureAssemblyView { var view = _logic.ReadElement(new FurnitureSearchModel { Id = _id.Value }); - if(view != null) + if (view != null) { textBoxName.Text = view.FurnitureName; textBoxPrice.Text = view.Price.ToString(); @@ -54,7 +55,7 @@ namespace FurnitureAssemblyView LoadData(); } } - catch(Exception ex) + catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -68,11 +69,11 @@ namespace FurnitureAssemblyView try { - if(_furnitureWorkPieces != null) + if (_furnitureWorkPieces != null) { dataGridView.Rows.Clear(); - foreach(var awp in _furnitureWorkPieces) + foreach (var awp in _furnitureWorkPieces) { dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 }); } @@ -80,7 +81,7 @@ namespace FurnitureAssemblyView textBoxPrice.Text = CalcPrice().ToString(); } } - catch(Exception ex) + catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки заготовки для изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -89,30 +90,27 @@ namespace FurnitureAssemblyView private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormFurnitureWorkPiece)); - - if (service is FormFurnitureWorkPiece form) + var form = DependencyManager.Instance.Resolve(); + + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) + if (form.WorkPieceModel == null) { - if (form.WorkPieceModel == null) - { - return; - } - - _logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); - - if (_furnitureWorkPieces.ContainsKey(form.Id)) - { - _furnitureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); - } - else - { - _furnitureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count)); - } - - LoadData(); + return; } + + _logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + + if (_furnitureWorkPieces.ContainsKey(form.Id)) + { + _furnitureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + } + else + { + _furnitureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count)); + } + + LoadData(); } } @@ -120,26 +118,23 @@ namespace FurnitureAssemblyView { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormFurnitureWorkPiece)); - - if (service is FormFurnitureWorkPiece form) + var form = DependencyManager.Instance.Resolve(); + + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _furnitureWorkPieces[id].Item2; + + if (form.ShowDialog() == DialogResult.OK) { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _furnitureWorkPieces[id].Item2; - - if (form.ShowDialog() == DialogResult.OK) + if (form.WorkPieceModel == null) { - if (form.WorkPieceModel == null) - { - return; - } - - _logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); - _furnitureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); - - LoadData(); + return; } + + _logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count); + _furnitureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count); + + LoadData(); } } } @@ -189,7 +184,7 @@ namespace FurnitureAssemblyView if (_furnitureWorkPieces == null || _furnitureWorkPieces.Count == 0) { MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - + return; } diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormFurnitures.cs b/FurnitureAssembly/FurnitureAssemblyView/FormFurnitures.cs index 1e8b461..98201e8 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormFurnitures.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormFurnitures.cs @@ -1,5 +1,6 @@ using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -37,15 +38,7 @@ namespace FurnitureAssemblyView { try { - var list = _logic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["FurnitureWorkPieces"].Visible = false; - dataGridView.Columns["FurnitureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка изделий"); } @@ -58,14 +51,11 @@ namespace FurnitureAssemblyView private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormFurniture)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormFurniture form) + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } @@ -73,16 +63,13 @@ namespace FurnitureAssemblyView { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormFurniture)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormFurniture 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/FurnitureAssembly/FurnitureAssemblyView/FormImplementers.cs b/FurnitureAssembly/FurnitureAssemblyView/FormImplementers.cs index b05211a..9f5de17 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormImplementers.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormImplementers.cs @@ -1,5 +1,6 @@ using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,115 +14,113 @@ using System.Windows.Forms; namespace FurnitureAssemblyView { - public partial class FormImplementers : Form - { - private readonly ILogger _logger; + public partial class FormImplementers : Form + { + private readonly ILogger _logger; - private readonly IImplementerLogic _logic; + private readonly IImplementerLogic _logic; - public FormImplementers(ILogger logger, IImplementerLogic logic) - { - InitializeComponent(); + public FormImplementers(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); - _logger = logger; - _logic = logic; - } + _logger = logger; + _logic = logic; + } - private void FormImplementers_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormImplementers_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["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + _logger.LogInformation("Загрузка исполнителей"); + var list = _logic.ReadList(null); - _logger.LogInformation("Загрузка исполнителей"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки исполнителей"); + // Растягиваем колонку Название на всю ширину, колонку Id скрываем + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); - private void ButtonCreate_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - if (service is FormImplementer form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + private void ButtonCreate_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonChange_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + private void ButtonChange_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } + form.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); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } - _logger.LogInformation("Удаление исполнителя"); + } + } - try - { - if (!_logic.Delete(new ImplementerBindingModel - { - 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("Удаление исполнителя"); - private void ButtonUpdate_Click(object sender, EventArgs e) - { - LoadData(); - } - } + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonUpdate_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormMails.cs b/FurnitureAssembly/FurnitureAssemblyView/FormMails.cs index 62d0f94..3471704 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormMails.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormMails.cs @@ -12,48 +12,40 @@ using System.Windows.Forms; namespace FurnitureAssemblyView { - public partial class FormMails : Form - { - private readonly ILogger _logger; + public partial class FormMails : Form + { + private readonly ILogger _logger; - private readonly IMessageInfoLogic _messageLogic; + private readonly IMessageInfoLogic _messageLogic; - public FormMails(ILogger logger, IMessageInfoLogic messageLogic) - { - InitializeComponent(); + public FormMails(ILogger logger, IMessageInfoLogic messageLogic) + { + InitializeComponent(); - _logger = logger; - _messageLogic = messageLogic; - } + _logger = logger; + _messageLogic = messageLogic; + } - private void FormMails_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - _logger.LogInformation("Загрузка писем"); + private void LoadData() + { + _logger.LogInformation("Загрузка писем"); - try - { - var list = _messageLogic.ReadList(null); + try + { + dataGridView.FillandConfigGrid(_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; - } - - _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); + } + } + } } diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormMain.Designer.cs b/FurnitureAssembly/FurnitureAssemblyView/FormMain.Designer.cs index 346ffc5..6220268 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormMain.Designer.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormMain.Designer.cs @@ -46,6 +46,7 @@ workWithImplementerToolStripMenuItem = new ToolStripMenuItem(); implementerToolStripMenuItem = new ToolStripMenuItem(); startingWorkToolStripMenuItem = new ToolStripMenuItem(); + createBackUpToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -92,12 +93,12 @@ buttonRefresh.TabIndex = 5; buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true; - buttonRefresh.Click += ButtonRef_Click; + buttonRefresh.Click += ButtonRefresh_Click; // // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem, createBackUpToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Padding = new Padding(5, 2, 0, 2); @@ -115,21 +116,21 @@ // workPieceToolStripMenuItem // workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem"; - workPieceToolStripMenuItem.Size = new Size(180, 22); + workPieceToolStripMenuItem.Size = new Size(130, 22); workPieceToolStripMenuItem.Text = "Заготовки"; workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click; // // furnitureToolStripMenuItem // furnitureToolStripMenuItem.Name = "furnitureToolStripMenuItem"; - furnitureToolStripMenuItem.Size = new Size(180, 22); + furnitureToolStripMenuItem.Size = new Size(130, 22); furnitureToolStripMenuItem.Text = "Изделия"; furnitureToolStripMenuItem.Click += FurnitureToolStripMenuItem_Click; // // mailsToolStripMenuItem // mailsToolStripMenuItem.Name = "mailsToolStripMenuItem"; - mailsToolStripMenuItem.Size = new Size(180, 22); + mailsToolStripMenuItem.Size = new Size(130, 22); mailsToolStripMenuItem.Text = "Письма"; mailsToolStripMenuItem.Click += MailsToolStripMenuItem_Click; // @@ -196,6 +197,13 @@ startingWorkToolStripMenuItem.Text = "Запуск работ"; startingWorkToolStripMenuItem.Click += StartingWorkToolStripMenuItem_Click; // + // createBackUpToolStripMenuItem + // + createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem"; + createBackUpToolStripMenuItem.Size = new Size(97, 20); + createBackUpToolStripMenuItem.Text = "Создать бекап"; + createBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -238,5 +246,6 @@ private ToolStripMenuItem implementerToolStripMenuItem; private ToolStripMenuItem startingWorkToolStripMenuItem; private ToolStripMenuItem mailsToolStripMenuItem; + private ToolStripMenuItem createBackUpToolStripMenuItem; } } \ No newline at end of file diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormMain.cs b/FurnitureAssembly/FurnitureAssemblyView/FormMain.cs index 1d2b862..c0385f1 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormMain.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormMain.cs @@ -1,5 +1,6 @@ using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.DI; using FurnitureAssemblyDataModels.Enums; using Microsoft.Extensions.Logging; using System; @@ -24,7 +25,9 @@ namespace FurnitureAssemblyView private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + private readonly IBackUpLogic _backUpLogic; + + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); @@ -32,6 +35,7 @@ namespace FurnitureAssemblyView _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) @@ -45,20 +49,9 @@ namespace FurnitureAssemblyView try { - var list = _orderLogic.ReadList(null); + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["FurnitureId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["FurnitureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - - _logger.LogInformation("Загрузка заказов"); + _logger.LogInformation("Успешная загрузка заказов"); } catch (Exception ex) { @@ -69,34 +62,24 @@ namespace FurnitureAssemblyView 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 FurnitureToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormFurnitures)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormFurnitures form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private void ButtonIssuedOrder_Click(object sender, EventArgs e) @@ -147,63 +130,73 @@ namespace FurnitureAssemblyView private void WorkPieceFurnituresToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportFurnitureWorkPieces)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormReportFurnitureWorkPieces form) - { - form.ShowDialog(); - } + 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 ButtonRef_Click(object sender, EventArgs e) + private void ButtonRefresh_Click(object sender, EventArgs e) { LoadData(); } 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(); - } + form.ShowDialog(); } private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e) { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + _workProcess.DoWork(DependencyManager.Instance.Resolve()!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormImplementers form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void MailsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormMails form) + 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 BackUpSaveBindingModel + { + FolderName = fbd.SelectedPath + }); + + MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/FurnitureAssembly/FurnitureAssemblyView/FormWorkPieces.cs b/FurnitureAssembly/FurnitureAssemblyView/FormWorkPieces.cs index 303f88b..4133208 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/FormWorkPieces.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/FormWorkPieces.cs @@ -1,5 +1,6 @@ using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BusinessLogicsContracts; +using FurnitureAssemblyContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -37,15 +38,7 @@ namespace FurnitureAssemblyView { try { - var list = _logic.ReadList(null); - - // Растягиваем колонку Название на всю ширину, колонку Id скрываем - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка заготовок"); } @@ -59,14 +52,11 @@ namespace FurnitureAssemblyView private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormWorkPiece form) + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } @@ -75,15 +65,12 @@ namespace FurnitureAssemblyView { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormWorkPiece 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/FurnitureAssembly/FurnitureAssemblyView/Program.cs b/FurnitureAssembly/FurnitureAssemblyView/Program.cs index 09bede2..4e7a2c8 100644 --- a/FurnitureAssembly/FurnitureAssemblyView/Program.cs +++ b/FurnitureAssembly/FurnitureAssemblyView/Program.cs @@ -4,6 +4,7 @@ using FurnitureAssemblyBusinessLogic.OfficePackage; using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.StoragesContracts; using FurnitureAssemblyDatabaseImplement.Implements; +using FurnitureAssemblyContracts.DI; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -15,10 +16,6 @@ namespace FurnitureAssemblyView { internal static class Program { - private static ServiceProvider? _serviceProvider; - - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// /// The main entry point for the application. /// @@ -29,80 +26,75 @@ namespace FurnitureAssemblyView // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); + InitDependency(); try { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); // var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); 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(); - - services.AddTransient(); - services.AddSingleton(); + 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.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