This commit is contained in:
platoff aeeee 2024-06-21 18:19:35 +04:00
parent a54010df45
commit 4d18ba7e8b
74 changed files with 2591 additions and 1351 deletions

View File

@ -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<BackUpLogic> 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<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
// Три строчки ниже - сериализация файлов в json
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@ -14,161 +14,161 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
{ {
// Класс, реализующий логику для исполнителей // Класс, реализующий логику для исполнителей
public class ImplementerLogic : IImplementerLogic public class ImplementerLogic : IImplementerLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage; private readonly IImplementerStorage _implementerStorage;
// Конструктор // Конструктор
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage) public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{ {
_logger = logger; _logger = logger;
_implementerStorage = implementerStorage; _implementerStorage = implementerStorage;
} }
// Вывод всего отфильтрованного списка // Вывод всего отфильтрованного списка
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model) public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{ {
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода // list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; 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) public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); 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) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _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) public bool Create(ImplementerBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_implementerStorage.Insert(model) == null) if (_implementerStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
// Обновление данных о работнике // Обновление данных о работнике
public bool Update(ImplementerBindingModel model) public bool Update(ImplementerBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_implementerStorage.Update(model) == null) if (_implementerStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление работника // Удаление работника
public bool Delete(ImplementerBindingModel model) public bool Delete(ImplementerBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null) if (_implementerStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete // Проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ImplementerBindingModel model, bool withParams = true) private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false // Так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на наличие ФИО // Проверка на наличие ФИО
if (string.IsNullOrEmpty(model.ImplementerFIO)) if (string.IsNullOrEmpty(model.ImplementerFIO))
{ {
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO)); throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO));
} }
// Проверка на наличие пароля // Проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password)) if (string.IsNullOrEmpty(model.Password))
{ {
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
} }
// Проверка на наличие квалификации // Проверка на наличие квалификации
if (model.Qualification <= 0) if (model.Qualification <= 0)
{ {
throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification)); throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification));
} }
// Проверка на наличие квалификации // Проверка на наличие квалификации
if (model.WorkExperience < 0) if (model.WorkExperience < 0)
{ {
throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience)); throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience));
} }
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +
"Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}", "Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}",
model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id); model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id);
// Для проверка на наличие такого же аккаунта // Для проверка на наличие такого же аккаунта
var element = _implementerStorage.GetElement(new ImplementerSearchModel var element = _implementerStorage.GetElement(new ImplementerSearchModel
{ {
ImplementerFIO = model.ImplementerFIO, ImplementerFIO = model.ImplementerFIO,
}); });
// Если элемент найден и его Id не совпадает с Id переданного объекта // Если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Исполнитель с таким именем уже есть"); throw new InvalidOperationException("Исполнитель с таким именем уже есть");
} }
} }
} }
} }

View File

@ -58,35 +58,35 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
} }
// Вывод конкретного чека // Вывод конкретного чека
public OrderViewModel? ReadElement(OrderSearchModel model) public OrderViewModel? ReadElement(OrderSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); 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) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _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); CheckModel(model);
if(model.Status != OrderStatus.Неизвестен) if (model.Status != OrderStatus.Неизвестен)
{ {
_logger.LogWarning("Insert operation failed, incorrect order status"); _logger.LogWarning("Insert operation failed, incorrect order status");
return false; return false;
@ -95,7 +95,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
model.Status = OrderStatus.Принят; model.Status = OrderStatus.Принят;
var result = _orderStorage.Insert(model); var result = _orderStorage.Insert(model);
if (result == null) if (result == null)
{ {
model.Status = OrderStatus.Неизвестен; model.Status = OrderStatus.Неизвестен;
@ -179,13 +179,13 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
// Если не смогли найти указанный заказ по его Id // Если не смогли найти указанный заказ по его Id
if(viewModel == null) if (viewModel == null)
{ {
throw new ArgumentNullException(nameof(model)); 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"); _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + "incorrect");
return false; return false;
@ -193,14 +193,14 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
model.Status = newOrderStatus; model.Status = newOrderStatus;
// Помещаем id работника, не забываем про него... // Помещаем id работника, не забываем про него...
if (viewModel.ImplementerId.HasValue) if (viewModel.ImplementerId.HasValue)
{ {
model.ImplementerId = viewModel.ImplementerId; model.ImplementerId = viewModel.ImplementerId;
} }
// Проверка на выдачу // Проверка на выдачу
if (model.Status == OrderStatus.Выдан) if (model.Status == OrderStatus.Выдан)
{ {
model.DateImplement = DateTime.Now; model.DateImplement = DateTime.Now;
} }
@ -214,7 +214,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
// Финальная проверка на возможность обновления // Финальная проверка на возможность обновления
var result = _orderStorage.Update(model); var result = _orderStorage.Update(model);
if(result == null) if (result == null)
{ {
model.Status--; model.Status--;

View File

@ -12,155 +12,155 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.BussinessLogic namespace FurnitureAssemblyBusinessLogic.BussinessLogic
{ {
public class WorkModeling : IWorkProcess public class WorkModeling : IWorkProcess
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Random _rnd; private readonly Random _rnd;
private IOrderLogic? _orderLogic; private IOrderLogic? _orderLogic;
// Конструктор // Конструктор
public WorkModeling(ILogger<WorkModeling> logger) public WorkModeling(ILogger<WorkModeling> logger)
{ {
_logger = logger; _logger = logger;
_rnd = new Random(1000); _rnd = new Random(1000);
} }
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
{ {
_orderLogic = orderLogic; _orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null); var implementers = implementerLogic.ReadList(null);
if (implementers == null) if (implementers == null)
{ {
_logger.LogWarning("DoWork. Implementers is null"); _logger.LogWarning("DoWork. Implementers is null");
return; return;
} }
var orders = _orderLogic.ReadList(new OrderSearchModel var orders = _orderLogic.ReadList(new OrderSearchModel
{ {
Status = OrderStatus.Принят Status = OrderStatus.Принят
}); });
if (orders == null || orders.Count == 0) if (orders == null || orders.Count == 0)
{ {
_logger.LogWarning("Dowork. Orders is null or empty"); _logger.LogWarning("Dowork. Orders is null or empty");
return; return;
} }
_logger.LogDebug("DoWork for {count} orders", orders.Count); _logger.LogDebug("DoWork for {count} orders", orders.Count);
foreach (var implementer in implementers) foreach (var implementer in implementers)
{ {
Task.Run(() => WorkerWorkAsync(implementer, orders)); Task.Run(() => WorkerWorkAsync(implementer, orders));
} }
} }
// Имитация работы исполнителя // Имитация работы исполнителя
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders) private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{ {
if (_orderLogic == null || implementer == null) if (_orderLogic == null || implementer == null)
{ {
return; return;
} }
await RunOrderInWork(implementer); await RunOrderInWork(implementer);
await Task.Run(() => await Task.Run(() =>
{ {
foreach (var order in orders) foreach (var order in orders)
{ {
try try
{ {
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// Пытаемся назначить заказ на исполнителя // Пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel _orderLogic.TakeOrderInWork(new OrderBindingModel
{ {
Id = order.Id, Id = order.Id,
ImplementerId = implementer.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 _orderLogic.FinishOrder(new OrderBindingModel
{ {
Id = order.Id Id = order.Id
}); });
// Усёёё отдыхаем // Усёёё отдыхаем
Thread.Sleep(implementer.Qualification); Thread.Sleep(implementer.Qualification);
} }
// Игнорируем ошибку, если с заказом что-то случится // Игнорируем ошибку, если с заказом что-то случится
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogWarning(ex, "Error try get work"); _logger.LogWarning(ex, "Error try get work");
} }
// В случае ошибки прервём выполнение имитации работы // В случае ошибки прервём выполнение имитации работы
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error while do work"); _logger.LogError(ex, "Error while do work");
throw; throw;
} }
} }
}); });
} }
// Ищем заказ, который уже во всю в работе (вдруг прервали исполнителя) // Ищем заказ, который уже во всю в работе (вдруг прервали исполнителя)
private async Task RunOrderInWork(ImplementerViewModel implementer) private async Task RunOrderInWork(ImplementerViewModel implementer)
{ {
if (_orderLogic == null || implementer == null) if (_orderLogic == null || implementer == null)
{ {
return; return;
} }
try try
{ {
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{ {
ImplementerId = implementer.Id, ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется Status = OrderStatus.Выполняется
})); }));
if (runOrder == null) if (runOrder == null)
{ {
return; 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 _orderLogic.FinishOrder(new OrderBindingModel
{ {
Id = runOrder.Id Id = runOrder.Id
}); });
// Отдыхаем, хватит работы // Отдыхаем, хватит работы
Thread.Sleep(implementer.Qualification); Thread.Sleep(implementer.Qualification);
} }
// Заказа может не быть, просто игнорируем ошибку // Заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogWarning(ex, "Error try get work"); _logger.LogWarning(ex, "Error try get work");
} }
// Просто возникнет тупая ошибка, тогда заканчиваем выполнение имитации // Просто возникнет тупая ошибка, тогда заканчиваем выполнение имитации
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error while do work"); _logger.LogError(ex, "Error while do work");
throw; throw;
} }
} }
} }
} }

View File

@ -14,7 +14,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
//список заготовок для вывода и сохранения // Cписок заготовок для вывода и сохранения
public List<FurnitureViewModel> Furnitures { get; set; } = new(); public List<FurnitureViewModel> Furnitures { get; set; } = new();
} }
} }

View File

@ -12,7 +12,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
// Набор текстов в абзаце (для случая, если в абзаце текст разных стилей) // Набор текстов в абзаце (для случая, если в абзаце текст разных стилей)
public List<(string, WordTextProperties)> Texts { get; set; } = new(); public List<(string, WordTextProperties)> Texts { get; set; } = new();
//свойства параграфа, если они есть // Cвойства параграфа, если они есть
public WordTextProperties? TextProperties { get; set; } public WordTextProperties? TextProperties { get; set; }
} }
} }

View File

@ -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; }
}
}

View File

@ -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
}
}

View File

@ -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;
}
}

View File

@ -7,9 +7,11 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BindingModels namespace FurnitureAssemblyContracts.BindingModels
{ {
// Реализации сущности "Сообщение" // Реализация сущности "Сообщение"
public class MessageInfoBindingModel : IMessageInfoModel public class MessageInfoBindingModel : IMessageInfoModel
{ {
public int Id { get; set; }
public string MessageId { get; set; } = string.Empty; public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; } public int? ClientId { get; set; }

View File

@ -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);
}
}

View File

@ -6,10 +6,10 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts namespace FurnitureAssemblyContracts.BusinessLogicsContracts
{ {
// Интерфейс для класса, имитирующего работу // Интерфейс для класса, имитирующего работу
public interface IWorkProcess public interface IWorkProcess
{ {
// Запуск работы // Запуск работы
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
} }
} }

View File

@ -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<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
// Добавление зависимости
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
// Добавление зависимости
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
// Получение класса со всеми зависимостями
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -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<ILoggingBuilder> configure);
// Добавление зависимости
void RegisterType<T, U>(bool isSingle) where U : class, T where T :
class;
// Добавление зависимости
void RegisterType<T>(bool isSingle) where T : class;
// Получение класса со всеми зависимостями
T Resolve<T>();
}
}

View File

@ -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();
}
}

View File

@ -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<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@ -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";
}
}
}

View File

@ -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<ILoggingBuilder> configure)
{
var factory = LoggerFactory.Create(configure);
_container.AddExtension(new LoggingExtension(factory));
}
public void RegisterType<T>(bool isSingle) where T : class
{
_container.RegisterType<T>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
void IDependencyContainer.RegisterType<T, U>(bool isSingle)
{
_container.RegisterType<T, U>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
}
}

View File

@ -6,6 +6,12 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Unity" Version="5.10.0" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.10.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" /> <ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -8,15 +8,15 @@ namespace FurnitureAssemblyContracts.SearchModels
{ {
// Модель для поиска исполнителя // Модель для поиска исполнителя
public class ImplementerSearchModel 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; }
} }
} }

View File

@ -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<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@ -11,17 +11,17 @@ namespace FurnitureAssemblyContracts.StoragesContracts
{ {
// Класс для хранилища исполнителей // Класс для хранилища исполнителей
public interface IImplementerStorage public interface IImplementerStorage
{ {
List<ImplementerViewModel> GetFullList(); List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model); List<ImplementerViewModel> 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);
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -11,15 +12,16 @@ namespace FurnitureAssemblyContracts.ViewModels
// Класс для отображения информации о клиентах // Класс для отображения информации о клиентах
public class ClientViewModel : IClientModel public class ClientViewModel : IClientModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("ФИО клиента")] [Column(title: "ФИО клиента", width: 150)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")] [Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Email { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -11,14 +12,16 @@ namespace FurnitureAssemblyContracts.ViewModels
// Класс для отображения пользователю информации о продуктах (изделиях) // Класс для отображения пользователю информации о продуктах (изделиях)
public class FurnitureViewModel : IFurnitureModel public class FurnitureViewModel : IFurnitureModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Название изделия")] [Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string FurnitureName { get; set; } = string.Empty; public string FurnitureName { get; set; } = string.Empty;
[DisplayName("Цена")] [Column(title: "Цена", width: 150)]
public double Price { get; set; } public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces { get; set; } = new(); public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces { get; set; } = new();
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,19 +11,20 @@ namespace FurnitureAssemblyContracts.ViewModels
{ {
// Класс для отображения информации об исполнителях // Класс для отображения информации об исполнителях
public class ImplementerViewModel : IImplementerModel public class ImplementerViewModel : IImplementerModel
{ {
public int Id { get; set; } [Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО исполнителя")] [Column(title: "ФИО исполнителя", width: 150)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[DisplayName("Стаж")] [Column(title: "Стаж", width: 150)]
public int WorkExperience { get; set; } public int WorkExperience { get; set; }
[DisplayName("Квалификация")] [Column(title: "Квалификация", width: 150)]
public int Qualification { get; set; } public int Qualification { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -11,20 +12,25 @@ namespace FurnitureAssemblyContracts.ViewModels
// Класс для отображения пользователю информации о сообщениях // Класс для отображения пользователю информации о сообщениях
public class MessageInfoViewModel : IMessageInfoModel public class MessageInfoViewModel : IMessageInfoModel
{ {
[Column(visible: false)]
public int Id { get; set; }
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty; 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; public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата отправки")] [Column(title: "Дата отправки", width: 150)]
public DateTime DateDelivery { get; set; } = DateTime.Now; public DateTime DateDelivery { get; set; } = DateTime.Now;
[DisplayName("Заголовок")] [Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")] [Column(title: "Текст", width: 150)]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Enums; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Enums;
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -12,37 +13,40 @@ namespace FurnitureAssemblyContracts.ViewModels
// Класс для отображения пользователю информации о заказах // Класс для отображения пользователю информации о заказах
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[Column(visible: false)]
public int ClientId { get; set; } public int ClientId { get; set; }
[DisplayName("ФИО клиента")] [Column(title: "ФИО клиента", width: 150)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[Column(visible: false)]
public int? ImplementerId { get; set; } public int? ImplementerId { get; set; }
[DisplayName("ФИО исполнителя")] [Column(title: "ФИО исполнителя", width: 150)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[Column(visible: false)]
public int FurnitureId { get; set; } public int FurnitureId { get; set; }
[DisplayName("Изделие")] [Column(title: "Изделие", width: 150)]
public string FurnitureName { get; set; } = string.Empty; public string FurnitureName { get; set; } = string.Empty;
[DisplayName("Количество")] [Column(title: "Количество", width: 150)]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [Column(title: "Сумма", width: 150)]
public double Sum { get; set; } public double Sum { get; set; }
[DisplayName("Статус")] [Column(title: "Статус", width: 150)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")] [Column(title: "Дата создания", width: 150)]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")] [Column(title: "Дата выполнения", width: 150)]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyContracts.Attributes;
using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -11,12 +12,13 @@ namespace FurnitureAssemblyContracts.ViewModels
// Класс для отображения пользователю данных о заготовке (заготовках) // Класс для отображения пользователю данных о заготовке (заготовках)
public class WorkPieceViewModel : IWorkPieceModel public class WorkPieceViewModel : IWorkPieceModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Название заготовки")] [Column(title: "Название заготовки", width: 150)]
public string WorkPieceName { get; set; } = string.Empty; public string WorkPieceName { get; set; } = string.Empty;
[DisplayName("Цена")] [Column(title: "Цена", width: 150)]
public double Cost { get; set; } public double Cost { get; set; }
} }
} }

View File

@ -8,13 +8,13 @@ namespace FurnitureAssemblyDataModels.Models
{ {
// Интерфейс, отвечающий за исполнителя // Интерфейс, отвечающий за исполнителя
public interface IImplementerModel : IId 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; }
} }
} }

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyDataModels.Models namespace FurnitureAssemblyDataModels.Models
{ {
// Интерфейс, отвечающий за сообщения // Интерфейс, отвечающий за сообщения
public interface IMessageInfoModel public interface IMessageInfoModel : IId
{ {
string MessageId { get; } string MessageId { get; }

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IFurnitureStorage, FurnitureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -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<T>? GetList<T>() where T : class, new()
{
using var context = new FurnitureAssemblyDatabase();
return context.Set<T>().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;
}
}
}

View File

@ -12,96 +12,96 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Implements namespace FurnitureAssemblyDatabaseImplement.Implements
{ {
public class ImplementerStorage : IImplementerStorage public class ImplementerStorage : IImplementerStorage
{ {
public ImplementerViewModel? GetElement(ImplementerSearchModel model) public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{ {
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
if (model.Id.HasValue) if (model.Id.HasValue)
return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null) if (model.ImplementerFIO != null && model.Password != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO return context.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
if (model.ImplementerFIO != null) if (model.ImplementerFIO != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO return context.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO))?.GetViewModel; .Equals(model.ImplementerFIO))?.GetViewModel;
return null; return null;
} }
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model) public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{ {
if (model == null) if (model == null)
{ {
return new(); return new();
} }
if (model.ImplementerFIO != null) if (model.ImplementerFIO != null)
{ {
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
return context.Implementers return context.Implementers
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
return new(); return new();
} }
public List<ImplementerViewModel> GetFullList() public List<ImplementerViewModel> GetFullList()
{ {
using var context = new FurnitureAssemblyDatabase(); 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) public ImplementerViewModel? Insert(ImplementerBindingModel model)
{ {
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
var res = Implementer.Create(model); var res = Implementer.Create(model);
if (res != null) if (res != null)
{ {
context.Implementers.Add(res); context.Implementers.Add(res);
context.SaveChanges(); context.SaveChanges();
} }
return res?.GetViewModel; return res?.GetViewModel;
} }
public ImplementerViewModel? Update(ImplementerBindingModel model) public ImplementerViewModel? Update(ImplementerBindingModel model)
{ {
using var context = new FurnitureAssemblyDatabase(); 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) if (res != null)
{ {
res.Update(model); res.Update(model);
context.SaveChanges(); context.SaveChanges();
} }
return res?.GetViewModel; return res?.GetViewModel;
} }
public ImplementerViewModel? Delete(ImplementerBindingModel model) public ImplementerViewModel? Delete(ImplementerBindingModel model)
{ {
using var context = new FurnitureAssemblyDatabase(); 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) if (res != null)
{ {
context.Implementers.Remove(res); context.Implementers.Remove(res);
context.SaveChanges(); context.SaveChanges();
} }
return res?.GetViewModel; return res?.GetViewModel;
} }
} }
} }

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
[DbContext(typeof(FurnitureAssemblyDatabase))]
[Migration("20240621135519_lab8")]
partial class lab8
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FurnitureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkPieceId");
b.ToTable("FurnitureWorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FurnitureId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureWorkPiece", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("WorkPieces")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("FurnitureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Orders")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Furniture");
b.Navigation("Implementer");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("FurnitureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class lab8 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -8,20 +8,26 @@ using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class Client : IClientModel public class Client : IClientModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
[DataMember]
public string ClientFIO { get; private set; } = string.Empty; public string ClientFIO { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public string Email { get; private set; } = string.Empty; public string Email { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
// Для реализации связи многие-ко-многим с заказами (клиенты могу сделать одинаковый заказ) // Для реализации связи многие-ко-многим с заказами (клиенты могу сделать одинаковый заказ)

View File

@ -7,25 +7,31 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class Furniture : IFurnitureModel public class Furniture : IFurnitureModel
{ {
[DataMember]
public int Id { get; set; } public int Id { get; set; }
[Required] [Required]
[DataMember]
public string FurnitureName { get; set; } = string.Empty; public string FurnitureName { get; set; } = string.Empty;
[Required] [Required]
[DataMember]
public double Price { get; set; } public double Price { get; set; }
public Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null; public Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null;
// Это поле не будет "мапиться" в бд // Это поле не будет "мапиться" в бд
[NotMapped] [NotMapped]
[DataMember]
public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces
{ {
get get

View File

@ -2,11 +2,13 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class FurnitureWorkPiece public class FurnitureWorkPiece
{ {
public int Id { get; set; } public int Id { get; set; }

View File

@ -8,24 +8,31 @@ using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
public int Id { get; set; } [DataMember]
public int Id { get; set; }
[Required] [Required]
public string ImplementerFIO { get; set; } = string.Empty; [DataMember]
public string ImplementerFIO { get; set; } = string.Empty;
[Required] [Required]
public string Password { get; set; } = string.Empty; [DataMember]
public string Password { get; set; } = string.Empty;
[Required] [Required]
public int WorkExperience { get; set; } [DataMember]
public int WorkExperience { get; set; }
[Required] [Required]
public int Qualification { get; set; } [DataMember]
public int Qualification { get; set; }
// Для реализации связи один ко многим с заказами // Для реализации связи один ко многим с заказами
[ForeignKey("ImplementerId")] [ForeignKey("ImplementerId")]

View File

@ -5,29 +5,30 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
public int Id => throw new NotImplementedException();
[Key] [Key]
[DataMember]
public string MessageId { get; set; } = string.Empty; public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; } public int? ClientId { get; set; }
[Required]
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
[Required]
public DateTime DateDelivery { get; set; } = DateTime.Now; public DateTime DateDelivery { get; set; } = DateTime.Now;
[Required]
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
[Required]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
public virtual Client? Client { get; set; } public virtual Client? Client { get; set; }

View File

@ -6,35 +6,46 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class Order : IOrderModel public class Order : IOrderModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
[DataMember]
public int FurnitureId { get; private set; } public int FurnitureId { get; private set; }
[Required] [Required]
[DataMember]
public int ClientId { get; private set; } public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; } public int? ImplementerId { get; private set; }
[Required] [Required]
[DataMember]
public int Count { get; private set; } public int Count { get; private set; }
[Required] [Required]
[DataMember]
public double Sum { get; private set; } public double Sum { get; private set; }
[Required] [Required]
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required] [Required]
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
// Для передачи названия изделия // Для передачи названия изделия

View File

@ -6,19 +6,24 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Models namespace FurnitureAssemblyDatabaseImplement.Models
{ {
[DataContract]
public class WorkPiece : IWorkPieceModel public class WorkPiece : IWorkPieceModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
[DataMember]
public string WorkPieceName { get; private set; } = string.Empty; public string WorkPieceName { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public double Cost { get; set; } public double Cost { get; set; }
// для реализации связи многие ко многим с изделиями // для реализации связи многие ко многим с изделиями

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IFurnitureStorage, FurnitureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -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<T>? GetList<T>() where T : class, new()
{
var source = DataFileSingleton.GetInstance();
return (List<T>?)source.GetType().GetProperties()
.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T))
?.GetValue(source);
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -11,102 +11,102 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyFileImplement.Implements namespace FurnitureAssemblyFileImplement.Implements
{ {
public class ImplementerStorage : IImplementerStorage public class ImplementerStorage : IImplementerStorage
{ {
private readonly DataFileSingleton source; private readonly DataFileSingleton source;
public ImplementerStorage() public ImplementerStorage()
{ {
source = DataFileSingleton.GetInstance(); source = DataFileSingleton.GetInstance();
} }
public ImplementerViewModel? GetElement(ImplementerSearchModel model) public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{ {
if (model.Id.HasValue) if (model.Id.HasValue)
return source.Implementers return source.Implementers
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null) if (model.ImplementerFIO != null && model.Password != null)
return source.Implementers.FirstOrDefault(x => x.ImplementerFIO return source.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; .Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
if (model.ImplementerFIO != null) if (model.ImplementerFIO != null)
return source.Implementers return source.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null; return null;
} }
public List<ImplementerViewModel> GetFullList() public List<ImplementerViewModel> GetFullList()
{ {
return source.Implementers.Select(x => x.GetViewModel).ToList(); return source.Implementers.Select(x => x.GetViewModel).ToList();
} }
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model) public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{ {
if (model == null) if (model == null)
{ {
return new(); return new();
} }
if (model.ImplementerFIO != null) if (model.ImplementerFIO != null)
{ {
return source.Implementers return source.Implementers
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Where(x => x.Id == model.Id) .Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
return new(); return new();
} }
public ImplementerViewModel? Insert(ImplementerBindingModel model) public ImplementerViewModel? Insert(ImplementerBindingModel model)
{ {
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1; 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) if (newImplementer == null)
{ {
return null; return null;
} }
source.Implementers.Add(newImplementer); source.Implementers.Add(newImplementer);
source.SaveImplementers(); source.SaveImplementers();
return newImplementer.GetViewModel; return newImplementer.GetViewModel;
} }
public ImplementerViewModel? Update(ImplementerBindingModel model) public ImplementerViewModel? Update(ImplementerBindingModel model)
{ {
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null) if (implementer == null)
{ {
return null; return null;
} }
implementer.Update(model); implementer.Update(model);
source.SaveImplementers(); source.SaveImplementers();
return implementer.GetViewModel; return implementer.GetViewModel;
} }
public ImplementerViewModel? Delete(ImplementerBindingModel model) public ImplementerViewModel? Delete(ImplementerBindingModel model)
{ {
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id); var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null) if (element != null)
{ {
source.Implementers.Remove(element); source.Implementers.Remove(element);
source.SaveImplementers(); source.SaveImplementers();
return element.GetViewModel; return element.GetViewModel;
} }
return null; return null;
} }
} }
} }

View File

@ -4,20 +4,26 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
[DataContract]
public class Client : IClientModel public class Client : IClientModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ClientFIO { get; private set; } = string.Empty; public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty; public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model) public static Client? Create(ClientBindingModel model)

View File

@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -11,18 +12,23 @@ using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
// Класс, реализующий интерфейс модели изделия // Класс, реализующий интерфейс модели изделия
[DataContract]
public class Furniture : IFurnitureModel public class Furniture : IFurnitureModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string FurnitureName { get; private set; } = string.Empty; public string FurnitureName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; } public double Price { get; private set; }
public Dictionary<int, int> WorkPieces { get; private set; } = new(); public Dictionary<int, int> WorkPieces { get; private set; } = new();
private Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null; private Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null;
[DataMember]
public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces
{ {
get get

View File

@ -4,22 +4,29 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; } public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; } public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel model) public static Implementer? Create(ImplementerBindingModel model)

View File

@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -11,18 +12,27 @@ using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
public int Id { get; set; }
[DataMember]
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty; public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now; public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty; public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)

View File

@ -5,6 +5,7 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -12,24 +13,34 @@ using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
// Класс, реализующий интерфейс модели заказа // Класс, реализующий интерфейс модели заказа
[DataContract]
public class Order : IOrderModel public class Order : IOrderModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public int FurnitureId { get; private set; } public int FurnitureId { get; private set; }
[DataMember]
public int ClientId { get; private set; } public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; } public int? ImplementerId { get; private set; }
[DataMember]
public int Count { get; private set; } public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; } public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel model) public static Order? Create(OrderBindingModel model)

View File

@ -4,6 +4,7 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -11,12 +12,16 @@ using System.Xml.Linq;
namespace FurnitureAssemblyFileImplement.Models namespace FurnitureAssemblyFileImplement.Models
{ {
// Класс, реализующий интерфейс модели заготовки // Класс, реализующий интерфейс модели заготовки
[DataContract]
public class WorkPiece : IWorkPieceModel public class WorkPiece : IWorkPieceModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string WorkPieceName { get; private set; } = string.Empty; public string WorkPieceName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; } public double Cost { get; set; }
public static WorkPiece? Create(WorkPieceBindingModel model) public static WorkPiece? Create(WorkPieceBindingModel model)

View File

@ -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<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@ -11,120 +11,120 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Implements namespace FurnitureAssemblyListImplement.Implements
{ {
public class ImplementerStorage : IImplementerStorage public class ImplementerStorage : IImplementerStorage
{ {
// Поле для работы со списком исполнителей // Поле для работы со списком исполнителей
private readonly DataListSingleton _source; private readonly DataListSingleton _source;
public ImplementerStorage() public ImplementerStorage()
{ {
_source = DataListSingleton.GetInstance(); _source = DataListSingleton.GetInstance();
} }
public List<ImplementerViewModel> GetFullList() public List<ImplementerViewModel> GetFullList()
{ {
var result = new List<ImplementerViewModel>(); var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers) foreach (var implementer in _source.Implementers)
{ {
result.Add(implementer.GetViewModel); result.Add(implementer.GetViewModel);
} }
return result; return result;
} }
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model) public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{ {
var result = new List<ImplementerViewModel>(); var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO)) if (string.IsNullOrEmpty(model.ImplementerFIO))
{ {
return result; return result;
} }
foreach (var implementer in _source.Implementers) foreach (var implementer in _source.Implementers)
{ {
if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) if (implementer.ImplementerFIO.Contains(model.ImplementerFIO))
{ {
result.Add(implementer.GetViewModel); result.Add(implementer.GetViewModel);
} }
} }
return result; return result;
} }
public ImplementerViewModel? GetElement(ImplementerSearchModel model) public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{ {
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{ {
return null; return null;
} }
foreach (var implementer in _source.Implementers) foreach (var implementer in _source.Implementers)
{ {
if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) || if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) ||
(model.Id.HasValue && implementer.Id == model.Id)) (model.Id.HasValue && implementer.Id == model.Id))
{ {
return implementer.GetViewModel; return implementer.GetViewModel;
} }
} }
return null; return null;
} }
public ImplementerViewModel? Insert(ImplementerBindingModel model) public ImplementerViewModel? Insert(ImplementerBindingModel model)
{ {
model.Id = 1; model.Id = 1;
foreach (var implementer in _source.Implementers) foreach (var implementer in _source.Implementers)
{ {
if (model.Id <= implementer.Id) if (model.Id <= implementer.Id)
{ {
model.Id = implementer.Id + 1; model.Id = implementer.Id + 1;
} }
} }
var newImplementer = Implementer.Create(model); var newImplementer = Implementer.Create(model);
if (newImplementer == null) if (newImplementer == null)
{ {
return null; return null;
} }
_source.Implementers.Add(newImplementer); _source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel; return newImplementer.GetViewModel;
} }
public ImplementerViewModel? Update(ImplementerBindingModel model) public ImplementerViewModel? Update(ImplementerBindingModel model)
{ {
foreach (var implementer in _source.Implementers) foreach (var implementer in _source.Implementers)
{ {
if (implementer.Id == model.Id) if (implementer.Id == model.Id)
{ {
implementer.Update(model); implementer.Update(model);
return implementer.GetViewModel; return implementer.GetViewModel;
} }
} }
return null; return null;
} }
public ImplementerViewModel? Delete(ImplementerBindingModel model) public ImplementerViewModel? Delete(ImplementerBindingModel model)
{ {
for (int i = 0; i < _source.Implementers.Count; ++i) for (int i = 0; i < _source.Implementers.Count; ++i)
{ {
if (_source.Implementers[i].Id == model.Id) if (_source.Implementers[i].Id == model.Id)
{ {
var element = _source.Implementers[i]; var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i); _source.Implementers.RemoveAt(i);
return element.GetViewModel; return element.GetViewModel;
} }
} }
return null; return null;
} }
} }
} }

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IFurnitureStorage, FurnitureStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -9,58 +9,58 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Models namespace FurnitureAssemblyListImplement.Models
{ {
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
public int Id { get; private set; } 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 // Метод для создания объекта от класса-компонента на основе класса-BindingModel
public static Implementer? Create(ImplementerBindingModel? model) public static Implementer? Create(ImplementerBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return null; return null;
} }
return new Implementer() return new Implementer()
{ {
Id = model.Id, Id = model.Id,
Password = model.Password, Password = model.Password,
ImplementerFIO = model.ImplementerFIO, ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification, Qualification = model.Qualification,
WorkExperience = model.WorkExperience WorkExperience = model.WorkExperience
}; };
} }
// Метод изменения существующего объекта // Метод изменения существующего объекта
public void Update(ImplementerBindingModel? model) public void Update(ImplementerBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Password = model.Password; Password = model.Password;
ImplementerFIO = model.ImplementerFIO; ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification; Qualification = model.Qualification;
WorkExperience = model.WorkExperience; WorkExperience = model.WorkExperience;
} }
// Метод для создания объекта класса ViewModel на основе данных объекта класса-компонента // Метод для создания объекта класса ViewModel на основе данных объекта класса-компонента
public ImplementerViewModel GetViewModel => new() public ImplementerViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
Password = Password, Password = Password,
ImplementerFIO = ImplementerFIO, ImplementerFIO = ImplementerFIO,
Qualification = Qualification, Qualification = Qualification,
WorkExperience = WorkExperience WorkExperience = WorkExperience
}; };
} }
} }

View File

@ -12,6 +12,8 @@ namespace FurnitureAssemblyListImplement.Models
{ {
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
public int Id { get; private set; }
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } public int? ClientId { get; private set; }

View File

@ -7,106 +7,106 @@ using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.Controllers namespace FurnitureAssemblyRestApi.Controllers
{ {
[Route("api/[controller]/[action]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class ImplementerController : Controller public class ImplementerController : Controller
{ {
private readonly ILogger _logger; 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<ImplementerController> logger) public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{ {
_logger = logger; _logger = logger;
_order = order; _order = order;
_logic = logic; _logic = logic;
} }
[HttpGet] [HttpGet]
public ImplementerViewModel? Login(string login, string password) public ImplementerViewModel? Login(string login, string password)
{ {
try try
{ {
return _logic.ReadElement(new ImplementerSearchModel return _logic.ReadElement(new ImplementerSearchModel
{ {
ImplementerFIO = login, ImplementerFIO = login,
Password = password Password = password
}); });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка авторизации сотрудника"); _logger.LogError(ex, "Ошибка авторизации сотрудника");
throw; throw;
} }
} }
[HttpGet] [HttpGet]
public List<OrderViewModel>? GetNewOrders() public List<OrderViewModel>? GetNewOrders()
{ {
try try
{ {
return _order.ReadList(new OrderSearchModel return _order.ReadList(new OrderSearchModel
{ {
Status = OrderStatus.Принят Status = OrderStatus.Принят
}); });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка получения новых заказов"); _logger.LogError(ex, "Ошибка получения новых заказов");
throw; throw;
} }
} }
[HttpGet] [HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId) public OrderViewModel? GetImplementerOrder(int implementerId)
{ {
try try
{ {
return _order.ReadElement(new OrderSearchModel return _order.ReadElement(new OrderSearchModel
{ {
ImplementerId = implementerId ImplementerId = implementerId
}); });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw; throw;
} }
} }
[HttpPost] [HttpPost]
public void TakeOrderInWork(OrderBindingModel model) public void TakeOrderInWork(OrderBindingModel model)
{ {
try try
{ {
_order.TakeOrderInWork(model); _order.TakeOrderInWork(model);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id);
throw; throw;
} }
} }
[HttpPost] [HttpPost]
public void FinishOrder(OrderBindingModel model) public void FinishOrder(OrderBindingModel model)
{ {
try try
{ {
_order.FinishOrder(model); _order.FinishOrder(model);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id); _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id);
throw; throw;
} }
} }
} }
} }

View File

@ -13,6 +13,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" /> <ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDatabaseImplement\FurnitureAssemblyDatabaseImplement.csproj" /> <ProjectReference Include="..\FurnitureAssemblyDatabaseImplement\FurnitureAssemblyDatabaseImplement.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -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<T>(this DataGridView grid, List<T>? 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;
}
}
}
}
}
}

View File

@ -35,18 +35,11 @@ namespace FurnitureAssemblyView
private void LoadData() private void LoadData()
{ {
_logger.LogInformation("Загрузка клиентов"); _logger.LogInformation("Загрузка клиентов");
try try
{ {
var list = _clientLogic.ReadList(null); dataGridView.FillandConfigGrid(_clientLogic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Успешная загрузка клиентов"); _logger.LogInformation("Успешная загрузка клиентов");
} }
catch (Exception ex) catch (Exception ex)

View File

@ -38,11 +38,11 @@
this.buttonUpdate = new System.Windows.Forms.Button(); this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button(); this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView(); this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPrice = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxWorkPiece.SuspendLayout(); this.groupBoxWorkPiece.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
@ -50,35 +50,33 @@
// labelName // labelName
// //
this.labelName.AutoSize = true; this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(48, 23); this.labelName.Location = new System.Drawing.Point(23, 30);
this.labelName.Name = "labelName"; this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(62, 15); this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 0; this.labelName.TabIndex = 0;
this.labelName.Text = "Название:"; this.labelName.Text = "Название:";
// //
// labelCost // labelCost
// //
this.labelCost.AutoSize = true; this.labelCost.AutoSize = true;
this.labelCost.Location = new System.Drawing.Point(38, 63); this.labelCost.Location = new System.Drawing.Point(23, 84);
this.labelCost.Name = "labelCost"; this.labelCost.Name = "labelCost";
this.labelCost.Size = new System.Drawing.Size(70, 15); this.labelCost.Size = new System.Drawing.Size(86, 20);
this.labelCost.TabIndex = 1; this.labelCost.TabIndex = 1;
this.labelCost.Text = "Стоимость:"; this.labelCost.Text = "Стоимость:";
// //
// textBoxName // textBoxName
// //
this.textBoxName.Location = new System.Drawing.Point(116, 20); this.textBoxName.Location = new System.Drawing.Point(133, 27);
this.textBoxName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxName.Name = "textBoxName"; this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(291, 23); this.textBoxName.Size = new System.Drawing.Size(332, 27);
this.textBoxName.TabIndex = 2; this.textBoxName.TabIndex = 2;
// //
// textBoxPrice // textBoxPrice
// //
this.textBoxPrice.Location = new System.Drawing.Point(116, 60); this.textBoxPrice.Location = new System.Drawing.Point(133, 81);
this.textBoxPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxPrice.Name = "textBoxPrice"; this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.Size = new System.Drawing.Size(291, 23); this.textBoxPrice.Size = new System.Drawing.Size(196, 27);
this.textBoxPrice.TabIndex = 3; this.textBoxPrice.TabIndex = 3;
// //
// groupBoxWorkPiece // groupBoxWorkPiece
@ -88,21 +86,18 @@
this.groupBoxWorkPiece.Controls.Add(this.buttonUpdate); this.groupBoxWorkPiece.Controls.Add(this.buttonUpdate);
this.groupBoxWorkPiece.Controls.Add(this.buttonAdd); this.groupBoxWorkPiece.Controls.Add(this.buttonAdd);
this.groupBoxWorkPiece.Controls.Add(this.dataGridView); this.groupBoxWorkPiece.Controls.Add(this.dataGridView);
this.groupBoxWorkPiece.Location = new System.Drawing.Point(12, 87); this.groupBoxWorkPiece.Location = new System.Drawing.Point(23, 126);
this.groupBoxWorkPiece.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxWorkPiece.Name = "groupBoxWorkPiece"; this.groupBoxWorkPiece.Name = "groupBoxWorkPiece";
this.groupBoxWorkPiece.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2); this.groupBoxWorkPiece.Size = new System.Drawing.Size(567, 300);
this.groupBoxWorkPiece.Size = new System.Drawing.Size(491, 225);
this.groupBoxWorkPiece.TabIndex = 4; this.groupBoxWorkPiece.TabIndex = 4;
this.groupBoxWorkPiece.TabStop = false; this.groupBoxWorkPiece.TabStop = false;
this.groupBoxWorkPiece.Text = "Заготовки"; this.groupBoxWorkPiece.Text = "Заготовки";
// //
// buttonRefresh // buttonRefresh
// //
this.buttonRefresh.Location = new System.Drawing.Point(397, 120); this.buttonRefresh.Location = new System.Drawing.Point(454, 196);
this.buttonRefresh.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonRefresh.Name = "buttonRefresh"; this.buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.Size = new System.Drawing.Size(82, 27); this.buttonRefresh.Size = new System.Drawing.Size(94, 29);
this.buttonRefresh.TabIndex = 4; this.buttonRefresh.TabIndex = 4;
this.buttonRefresh.Text = "Обновить"; this.buttonRefresh.Text = "Обновить";
this.buttonRefresh.UseVisualStyleBackColor = true; this.buttonRefresh.UseVisualStyleBackColor = true;
@ -110,10 +105,9 @@
// //
// buttonDelete // buttonDelete
// //
this.buttonDelete.Location = new System.Drawing.Point(397, 91); this.buttonDelete.Location = new System.Drawing.Point(454, 145);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete"; this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(82, 25); this.buttonDelete.Size = new System.Drawing.Size(94, 29);
this.buttonDelete.TabIndex = 3; this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить"; this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true; this.buttonDelete.UseVisualStyleBackColor = true;
@ -121,10 +115,9 @@
// //
// buttonUpdate // buttonUpdate
// //
this.buttonUpdate.Location = new System.Drawing.Point(397, 62); this.buttonUpdate.Location = new System.Drawing.Point(454, 95);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(82, 25); this.buttonUpdate.Size = new System.Drawing.Size(94, 29);
this.buttonUpdate.TabIndex = 2; this.buttonUpdate.TabIndex = 2;
this.buttonUpdate.Text = "Изменить"; this.buttonUpdate.Text = "Изменить";
this.buttonUpdate.UseVisualStyleBackColor = true; this.buttonUpdate.UseVisualStyleBackColor = true;
@ -132,10 +125,9 @@
// //
// buttonAdd // buttonAdd
// //
this.buttonAdd.Location = new System.Drawing.Point(397, 32); this.buttonAdd.Location = new System.Drawing.Point(454, 43);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(82, 26); this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 1; this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить"; this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true; this.buttonAdd.UseVisualStyleBackColor = true;
@ -148,14 +140,33 @@
this.ColumnID, this.ColumnID,
this.ColumnName, this.ColumnName,
this.ColumnPrice}); this.ColumnPrice});
this.dataGridView.Location = new System.Drawing.Point(5, 20); this.dataGridView.Location = new System.Drawing.Point(6, 26);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView"; this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51; this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29; this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(382, 201); this.dataGridView.Size = new System.Drawing.Size(436, 268);
this.dataGridView.TabIndex = 0; this.dataGridView.TabIndex = 0;
// //
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(340, 448);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(95, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(458, 448);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ColumnID // ColumnID
// //
this.ColumnID.HeaderText = "Id"; this.ColumnID.HeaderText = "Id";
@ -178,33 +189,11 @@
this.ColumnPrice.MinimumWidth = 6; this.ColumnPrice.MinimumWidth = 6;
this.ColumnPrice.Name = "ColumnPrice"; this.ColumnPrice.Name = "ColumnPrice";
// //
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(271, 316);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(83, 22);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(360, 316);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(82, 22);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormFurniture // FormFurniture
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(517, 357); this.ClientSize = new System.Drawing.Size(619, 500);
this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave); this.Controls.Add(this.buttonSave);
this.Controls.Add(this.groupBoxWorkPiece); this.Controls.Add(this.groupBoxWorkPiece);
@ -212,7 +201,6 @@
this.Controls.Add(this.textBoxName); this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelCost); this.Controls.Add(this.labelCost);
this.Controls.Add(this.labelName); this.Controls.Add(this.labelName);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormFurniture"; this.Name = "FormFurniture";
this.Text = "Изделие"; this.Text = "Изделие";
this.Load += new System.EventHandler(this.FormFurniture_Load); this.Load += new System.EventHandler(this.FormFurniture_Load);

View File

@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DI;
using FurnitureAssemblyContracts.SearchModels; using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyDataModels.Models; using FurnitureAssemblyDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -35,7 +36,7 @@ namespace FurnitureAssemblyView
_logic = logic; _logic = logic;
_furnitureWorkPieces = new Dictionary<int, (IWorkPieceModel, int)>(); _furnitureWorkPieces = new Dictionary<int, (IWorkPieceModel, int)>();
} }
private void FormFurniture_Load(object sender, EventArgs e) private void FormFurniture_Load(object sender, EventArgs e)
{ {
if (_id.HasValue) if (_id.HasValue)
@ -46,7 +47,7 @@ namespace FurnitureAssemblyView
{ {
var view = _logic.ReadElement(new FurnitureSearchModel { Id = _id.Value }); var view = _logic.ReadElement(new FurnitureSearchModel { Id = _id.Value });
if(view != null) if (view != null)
{ {
textBoxName.Text = view.FurnitureName; textBoxName.Text = view.FurnitureName;
textBoxPrice.Text = view.Price.ToString(); textBoxPrice.Text = view.Price.ToString();
@ -54,7 +55,7 @@ namespace FurnitureAssemblyView
LoadData(); LoadData();
} }
} }
catch(Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки изделия"); _logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -68,11 +69,11 @@ namespace FurnitureAssemblyView
try try
{ {
if(_furnitureWorkPieces != null) if (_furnitureWorkPieces != null)
{ {
dataGridView.Rows.Clear(); 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 }); dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 });
} }
@ -80,7 +81,7 @@ namespace FurnitureAssemblyView
textBoxPrice.Text = CalcPrice().ToString(); textBoxPrice.Text = CalcPrice().ToString();
} }
} }
catch(Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки заготовки для изделия"); _logger.LogError(ex, "Ошибка загрузки заготовки для изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -89,30 +90,27 @@ namespace FurnitureAssemblyView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormFurnitureWorkPiece)); var form = DependencyManager.Instance.Resolve<FormFurnitureWorkPiece>();
if (service is FormFurnitureWorkPiece form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) if (form.WorkPieceModel == null)
{ {
if (form.WorkPieceModel == null) return;
{
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();
} }
_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) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormFurnitureWorkPiece)); var form = DependencyManager.Instance.Resolve<FormFurnitureWorkPiece>();
if (service is FormFurnitureWorkPiece form) 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); if (form.WorkPieceModel == null)
form.Id = id;
form.Count = _furnitureWorkPieces[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.WorkPieceModel == null) return;
{
return;
}
_logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
_furnitureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
LoadData();
} }
_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) if (_furnitureWorkPieces == null || _furnitureWorkPieces.Count == 0)
{ {
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }

View File

@ -28,87 +28,79 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.buttonAdd = new System.Windows.Forms.Button(); buttonAdd = new Button();
this.buttonUpdate = new System.Windows.Forms.Button(); buttonUpdate = new Button();
this.buttonDelete = new System.Windows.Forms.Button(); buttonDelete = new Button();
this.buttonRef = new System.Windows.Forms.Button(); buttonRefresh = new Button();
this.dataGridView = new System.Windows.Forms.DataGridView(); dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
this.SuspendLayout(); SuspendLayout();
// //
// buttonAdd // buttonAdd
// //
this.buttonAdd.Location = new System.Drawing.Point(560, 26); buttonAdd.Location = new Point(640, 35);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd";
this.buttonAdd.Name = "buttonAdd"; buttonAdd.Size = new Size(116, 50);
this.buttonAdd.Size = new System.Drawing.Size(102, 38); buttonAdd.TabIndex = 0;
this.buttonAdd.TabIndex = 0; buttonAdd.Text = "Добавить";
this.buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
// //
// buttonUpdate // buttonUpdate
// //
this.buttonUpdate.Location = new System.Drawing.Point(560, 79); buttonUpdate.Location = new Point(640, 105);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Name = "buttonUpdate"; buttonUpdate.Size = new Size(116, 50);
this.buttonUpdate.Size = new System.Drawing.Size(102, 38); buttonUpdate.TabIndex = 1;
this.buttonUpdate.TabIndex = 1; buttonUpdate.Text = "Изменить";
this.buttonUpdate.Text = "Изменить"; buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.UseVisualStyleBackColor = true; buttonUpdate.Click += ButtonUpdate_Click;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonUpdate_Click);
// //
// buttonDelete // buttonDelete
// //
this.buttonDelete.Location = new System.Drawing.Point(560, 131); buttonDelete.Location = new Point(640, 175);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonDelete.Name = "buttonDelete";
this.buttonDelete.Name = "buttonDelete"; buttonDelete.Size = new Size(116, 50);
this.buttonDelete.Size = new System.Drawing.Size(102, 38); buttonDelete.TabIndex = 2;
this.buttonDelete.TabIndex = 2; buttonDelete.Text = "Удалить";
this.buttonDelete.Text = "Удалить"; buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.UseVisualStyleBackColor = true; buttonDelete.Click += ButtonDelete_Click;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
// //
// buttonRef // buttonRef
// //
this.buttonRef.Location = new System.Drawing.Point(560, 184); buttonRefresh.Location = new Point(640, 245);
this.buttonRef.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonRefresh.Name = "buttonRef";
this.buttonRef.Name = "buttonRef"; buttonRefresh.Size = new Size(116, 50);
this.buttonRef.Size = new System.Drawing.Size(102, 38); buttonRefresh.TabIndex = 3;
this.buttonRef.TabIndex = 3; buttonRefresh.Text = "Обновить";
this.buttonRef.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true;
this.buttonRef.UseVisualStyleBackColor = true; buttonRefresh.Click += ButtonRefresh_Click;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
// //
// dataGridView // dataGridView
// //
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(10, 9); dataGridView.Location = new Point(12, 12);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); dataGridView.Name = "dataGridView";
this.dataGridView.Name = "dataGridView"; dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29;
this.dataGridView.RowTemplate.Height = 29; dataGridView.Size = new Size(604, 426);
this.dataGridView.Size = new System.Drawing.Size(528, 320); dataGridView.TabIndex = 4;
this.dataGridView.TabIndex = 4;
// //
// FormFurnitures // FormFurnitures
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(683, 338); ClientSize = new Size(781, 450);
this.Controls.Add(this.dataGridView); Controls.Add(dataGridView);
this.Controls.Add(this.buttonRef); Controls.Add(buttonRefresh);
this.Controls.Add(this.buttonDelete); Controls.Add(buttonDelete);
this.Controls.Add(this.buttonUpdate); Controls.Add(buttonUpdate);
this.Controls.Add(this.buttonAdd); Controls.Add(buttonAdd);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); Name = "FormFurnitures";
this.Name = "FormFurnitures"; Text = "Изделия";
this.Text = "Изделия"; Load += FormFurnitures_Load;
this.Load += new System.EventHandler(this.FormFurnitures_Load); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
this.Click += new System.EventHandler(this.FormFurnitures_Load); ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
} }
#endregion #endregion
@ -116,7 +108,7 @@
private Button buttonAdd; private Button buttonAdd;
private Button buttonUpdate; private Button buttonUpdate;
private Button buttonDelete; private Button buttonDelete;
private Button buttonRef; private Button buttonRefresh;
private DataGridView dataGridView; private DataGridView dataGridView;
} }
} }

View File

@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -37,15 +38,7 @@ namespace FurnitureAssemblyView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillandConfigGrid(_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;
}
_logger.LogInformation("Загрузка изделий"); _logger.LogInformation("Загрузка изделий");
} }
@ -58,14 +51,11 @@ namespace FurnitureAssemblyView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormFurniture)); var form = DependencyManager.Instance.Resolve<FormFurniture>();
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) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormFurniture)); var form = DependencyManager.Instance.Resolve<FormFurniture>();
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); LoadData();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
} }
} }
} }
@ -118,7 +105,7 @@ namespace FurnitureAssemblyView
} }
} }
private void ButtonRef_Click(object sender, EventArgs e) private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }

View File

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

View File

@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -13,115 +14,113 @@ using System.Windows.Forms;
namespace FurnitureAssemblyView namespace FurnitureAssemblyView
{ {
public partial class FormImplementers : Form public partial class FormImplementers : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IImplementerLogic _logic; private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormWorkPieces> logger, IImplementerLogic logic) public FormImplementers(ILogger<FormWorkPieces> logger, IImplementerLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
} }
private void FormImplementers_Load(object sender, EventArgs e) private void FormImplementers_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
private void LoadData() private void LoadData()
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillandConfigGrid(_logic.ReadList(null));
// Растягиваем колонку Название на всю ширину, колонку Id скрываем _logger.LogInformation("Загрузка исполнителей");
if (list != null) var list = _logic.ReadList(null);
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей"); // Растягиваем колонку Название на всю ширину, колонку Id скрываем
} if (list != null)
catch (Exception ex) {
{ dataGridView.DataSource = list;
_logger.LogError(ex, "Ошибка загрузки исполнителей"); 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) MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); }
if (service is FormImplementer form) private void ButtonCreate_Click(object sender, EventArgs e)
{ {
if (form.ShowDialog() == DialogResult.OK) var form = DependencyManager.Instance.Resolve<FormImplementer>();
{
LoadData();
}
}
}
private void ButtonChange_Click(object sender, EventArgs e) if (form.ShowDialog() == DialogResult.OK)
{ {
if (dataGridView.SelectedRows.Count == 1) LoadData();
{ }
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); }
if (service is FormImplementer form) private void ButtonChange_Click(object sender, EventArgs e)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); if (dataGridView.SelectedRows.Count == 1)
{
var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (form.ShowDialog() == DialogResult.OK) form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
{
LoadData();
}
}
}
}
private void ButtonDelete_Click(object sender, EventArgs e) if (form.ShowDialog() == DialogResult.OK)
{ {
// Проверяем наличие выделенной строки LoadData();
if (dataGridView.SelectedRows.Count == 1) }
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя"); }
}
try private void ButtonDelete_Click(object sender, EventArgs e)
{ {
if (!_logic.Delete(new ImplementerBindingModel // Проверяем наличие выделенной строки
{ if (dataGridView.SelectedRows.Count == 1)
Id = id {
})) if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
}
LoadData(); _logger.LogInformation("Удаление исполнителя");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonUpdate_Click(object sender, EventArgs e) try
{ {
LoadData(); 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();
}
}
} }

View File

@ -12,48 +12,40 @@ using System.Windows.Forms;
namespace FurnitureAssemblyView namespace FurnitureAssemblyView
{ {
public partial class FormMails : Form public partial class FormMails : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoLogic _messageLogic; private readonly IMessageInfoLogic _messageLogic;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic messageLogic) public FormMails(ILogger<FormMails> logger, IMessageInfoLogic messageLogic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_messageLogic = messageLogic; _messageLogic = messageLogic;
} }
private void FormMails_Load(object sender, EventArgs e) private void FormMails_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
private void LoadData() private void LoadData()
{ {
_logger.LogInformation("Загрузка писем"); _logger.LogInformation("Загрузка писем");
try try
{ {
var list = _messageLogic.ReadList(null); dataGridView.FillandConfigGrid(_messageLogic.ReadList(null));
if (list != null) _logger.LogInformation("Успешная загрузка писем");
{ }
dataGridView.DataSource = list; catch (Exception ex)
dataGridView.Columns["MessageId"].Visible = false; {
dataGridView.Columns["ClientId"].Visible = false; _logger.LogError(ex, "Ошибка загрузки писем");
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
}
_logger.LogInformation("Успешная загрузка писем"); }
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }

View File

@ -28,196 +28,202 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.dataGridView = new System.Windows.Forms.DataGridView(); dataGridView = new DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button(); buttonCreateOrder = new Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button(); buttonIssuedOrder = new Button();
this.buttonRefresh = new System.Windows.Forms.Button(); buttonRefresh = new Button();
this.menuStrip = new System.Windows.Forms.MenuStrip(); menuStrip = new MenuStrip();
this.toolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); toolStripMenuItem = new ToolStripMenuItem();
this.workPieceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workPieceToolStripMenuItem = new ToolStripMenuItem();
this.furnitureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); furnitureToolStripMenuItem = new ToolStripMenuItem();
this.mailsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); mailsToolStripMenuItem = new ToolStripMenuItem();
this.reportsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem();
this.workPiecesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workPiecesToolStripMenuItem = new ToolStripMenuItem();
this.workPieceFurnituresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workPieceFurnituresToolStripMenuItem = new ToolStripMenuItem();
this.ordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem();
this.workWithClientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workWithClientsToolStripMenuItem = new ToolStripMenuItem();
this.clientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem();
this.workWithImplementerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
this.implementerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); implementerToolStripMenuItem = new ToolStripMenuItem();
this.startingWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); startingWorkToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); createBackUpToolStripMenuItem = new ToolStripMenuItem();
this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
this.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout();
// //
// dataGridView // dataGridView
// //
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(10, 27); dataGridView.Location = new Point(10, 27);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); dataGridView.Margin = new Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView"; dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51; dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29; dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(820, 302); dataGridView.Size = new Size(820, 302);
this.dataGridView.TabIndex = 0; dataGridView.TabIndex = 0;
// //
// buttonCreateOrder // buttonCreateOrder
// //
this.buttonCreateOrder.Location = new System.Drawing.Point(887, 50); buttonCreateOrder.Location = new Point(887, 50);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonCreateOrder.Margin = new Padding(3, 2, 3, 2);
this.buttonCreateOrder.Name = "buttonCreateOrder"; buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(206, 34); buttonCreateOrder.Size = new Size(206, 34);
this.buttonCreateOrder.TabIndex = 1; buttonCreateOrder.TabIndex = 1;
this.buttonCreateOrder.Text = "Создать заказ"; buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
// //
// buttonIssuedOrder // buttonIssuedOrder
// //
this.buttonIssuedOrder.Location = new System.Drawing.Point(887, 100); buttonIssuedOrder.Location = new Point(887, 100);
this.buttonIssuedOrder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonIssuedOrder.Margin = new Padding(3, 2, 3, 2);
this.buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Name = "buttonIssuedOrder";
this.buttonIssuedOrder.Size = new System.Drawing.Size(206, 33); buttonIssuedOrder.Size = new Size(206, 33);
this.buttonIssuedOrder.TabIndex = 4; buttonIssuedOrder.TabIndex = 4;
this.buttonIssuedOrder.Text = "Заказ выдан"; buttonIssuedOrder.Text = "Заказ выдан";
this.buttonIssuedOrder.UseVisualStyleBackColor = true; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
// //
// buttonRefresh // buttonRefresh
// //
this.buttonRefresh.Location = new System.Drawing.Point(887, 152); buttonRefresh.Location = new Point(887, 152);
this.buttonRefresh.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonRefresh.Margin = new Padding(3, 2, 3, 2);
this.buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.Size = new System.Drawing.Size(206, 29); buttonRefresh.Size = new Size(206, 29);
this.buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
this.buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
this.buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
// //
// menuStrip // menuStrip
// //
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem, createBackUpToolStripMenuItem });
this.toolStripMenuItem, menuStrip.Location = new Point(0, 0);
this.reportsToolStripMenuItem, menuStrip.Name = "menuStrip";
this.workWithClientsToolStripMenuItem, menuStrip.Padding = new Padding(5, 2, 0, 2);
this.workWithImplementerToolStripMenuItem, menuStrip.Size = new Size(1135, 24);
this.startingWorkToolStripMenuItem}); menuStrip.TabIndex = 6;
this.menuStrip.Location = new System.Drawing.Point(0, 0); menuStrip.Text = "menuStrip";
this.menuStrip.Name = "menuStrip";
this.menuStrip.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2);
this.menuStrip.Size = new System.Drawing.Size(1135, 24);
this.menuStrip.TabIndex = 6;
this.menuStrip.Text = "menuStrip";
// //
// toolStripMenuItem // toolStripMenuItem
// //
this.toolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, furnitureToolStripMenuItem, mailsToolStripMenuItem });
this.workPieceToolStripMenuItem, toolStripMenuItem.Name = "toolStripMenuItem";
this.furnitureToolStripMenuItem, toolStripMenuItem.Size = new Size(94, 20);
this.mailsToolStripMenuItem}); toolStripMenuItem.Text = "Справочники";
this.toolStripMenuItem.Name = "toolStripMenuItem";
this.toolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.toolStripMenuItem.Text = "Справочники";
// //
// workPieceToolStripMenuItem // workPieceToolStripMenuItem
// //
this.workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem"; workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem";
this.workPieceToolStripMenuItem.Size = new System.Drawing.Size(180, 22); workPieceToolStripMenuItem.Size = new Size(130, 22);
this.workPieceToolStripMenuItem.Text = "Заготовки"; workPieceToolStripMenuItem.Text = "Заготовки";
workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click;
// //
// furnitureToolStripMenuItem // furnitureToolStripMenuItem
// //
this.furnitureToolStripMenuItem.Name = "furnitureToolStripMenuItem"; furnitureToolStripMenuItem.Name = "furnitureToolStripMenuItem";
this.furnitureToolStripMenuItem.Size = new System.Drawing.Size(180, 22); furnitureToolStripMenuItem.Size = new Size(130, 22);
this.furnitureToolStripMenuItem.Text = "Изделия"; furnitureToolStripMenuItem.Text = "Изделия";
furnitureToolStripMenuItem.Click += FurnitureToolStripMenuItem_Click;
// //
// mailsToolStripMenuItem // mailsToolStripMenuItem
// //
this.mailsToolStripMenuItem.Name = "mailsToolStripMenuItem"; mailsToolStripMenuItem.Name = "mailsToolStripMenuItem";
this.mailsToolStripMenuItem.Size = new System.Drawing.Size(180, 22); mailsToolStripMenuItem.Size = new Size(130, 22);
this.mailsToolStripMenuItem.Text = "Письма"; mailsToolStripMenuItem.Text = "Письма";
this.mailsToolStripMenuItem.Click += new System.EventHandler(this.MailsToolStripMenuItem_Click); mailsToolStripMenuItem.Click += MailsToolStripMenuItem_Click;
// //
// reportsToolStripMenuItem // reportsToolStripMenuItem
// //
this.reportsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPiecesToolStripMenuItem, workPieceFurnituresToolStripMenuItem, ordersToolStripMenuItem });
this.workPiecesToolStripMenuItem, reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.workPieceFurnituresToolStripMenuItem, reportsToolStripMenuItem.Size = new Size(60, 20);
this.ordersToolStripMenuItem}); reportsToolStripMenuItem.Text = "Отчёты";
this.reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.reportsToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
this.reportsToolStripMenuItem.Text = "Отчёты";
// //
// workPiecesToolStripMenuItem // workPiecesToolStripMenuItem
// //
this.workPiecesToolStripMenuItem.Name = "workPiecesToolStripMenuItem"; workPiecesToolStripMenuItem.Name = "workPiecesToolStripMenuItem";
this.workPiecesToolStripMenuItem.Size = new System.Drawing.Size(203, 22); workPiecesToolStripMenuItem.Size = new Size(203, 22);
this.workPiecesToolStripMenuItem.Text = "Список заготовок"; workPiecesToolStripMenuItem.Text = "Список заготовок";
workPiecesToolStripMenuItem.Click += WorkPiecesToolStripMenuItem_Click;
// //
// workPieceFurnituresToolStripMenuItem // workPieceFurnituresToolStripMenuItem
// //
this.workPieceFurnituresToolStripMenuItem.Name = "workPieceFurnituresToolStripMenuItem"; workPieceFurnituresToolStripMenuItem.Name = "workPieceFurnituresToolStripMenuItem";
this.workPieceFurnituresToolStripMenuItem.Size = new System.Drawing.Size(203, 22); workPieceFurnituresToolStripMenuItem.Size = new Size(203, 22);
this.workPieceFurnituresToolStripMenuItem.Text = "Заготовки по изделиям"; workPieceFurnituresToolStripMenuItem.Text = "Заготовки по изделиям";
workPieceFurnituresToolStripMenuItem.Click += WorkPieceFurnituresToolStripMenuItem_Click;
// //
// ordersToolStripMenuItem // ordersToolStripMenuItem
// //
this.ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
this.ordersToolStripMenuItem.Size = new System.Drawing.Size(203, 22); ordersToolStripMenuItem.Size = new Size(203, 22);
this.ordersToolStripMenuItem.Text = "Список заказов"; ordersToolStripMenuItem.Text = "Список заказов";
ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
// //
// workWithClientsToolStripMenuItem // workWithClientsToolStripMenuItem
// //
this.workWithClientsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { workWithClientsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem });
this.clientsToolStripMenuItem}); workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem";
this.workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem"; workWithClientsToolStripMenuItem.Size = new Size(129, 20);
this.workWithClientsToolStripMenuItem.Size = new System.Drawing.Size(129, 20); workWithClientsToolStripMenuItem.Text = "Работа с клиентами";
this.workWithClientsToolStripMenuItem.Text = "Работа с клиентами";
// //
// clientsToolStripMenuItem // clientsToolStripMenuItem
// //
this.clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
this.clientsToolStripMenuItem.Size = new System.Drawing.Size(180, 22); clientsToolStripMenuItem.Size = new Size(122, 22);
this.clientsToolStripMenuItem.Text = "Клиенты"; clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// //
// workWithImplementerToolStripMenuItem // workWithImplementerToolStripMenuItem
// //
this.workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
this.implementerToolStripMenuItem}); workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
this.workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem"; workWithImplementerToolStripMenuItem.Size = new Size(157, 20);
this.workWithImplementerToolStripMenuItem.Size = new System.Drawing.Size(157, 20); workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
this.workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
// //
// implementerToolStripMenuItem // implementerToolStripMenuItem
// //
this.implementerToolStripMenuItem.Name = "implementerToolStripMenuItem"; implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
this.implementerToolStripMenuItem.Size = new System.Drawing.Size(180, 22); implementerToolStripMenuItem.Size = new Size(149, 22);
this.implementerToolStripMenuItem.Text = "Исполнители"; implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click;
// //
// startingWorkToolStripMenuItem // startingWorkToolStripMenuItem
// //
this.startingWorkToolStripMenuItem.Name = "startingWorkToolStripMenuItem"; startingWorkToolStripMenuItem.Name = "startingWorkToolStripMenuItem";
this.startingWorkToolStripMenuItem.Size = new System.Drawing.Size(92, 20); startingWorkToolStripMenuItem.Size = new Size(92, 20);
this.startingWorkToolStripMenuItem.Text = "Запуск работ"; startingWorkToolStripMenuItem.Text = "Запуск работ";
startingWorkToolStripMenuItem.Click += StartingWorkToolStripMenuItem_Click;
//
// createBackUpToolStripMenuItem
//
createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem";
createBackUpToolStripMenuItem.Size = new Size(97, 20);
createBackUpToolStripMenuItem.Text = "Создать бекап";
createBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click;
// //
// FormMain // FormMain
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1135, 338); ClientSize = new Size(1135, 338);
this.Controls.Add(this.buttonRefresh); Controls.Add(buttonRefresh);
this.Controls.Add(this.buttonIssuedOrder); Controls.Add(buttonIssuedOrder);
this.Controls.Add(this.buttonCreateOrder); Controls.Add(buttonCreateOrder);
this.Controls.Add(this.dataGridView); Controls.Add(dataGridView);
this.Controls.Add(this.menuStrip); Controls.Add(menuStrip);
this.MainMenuStrip = this.menuStrip; MainMenuStrip = menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
this.Name = "FormMain"; Name = "FormMain";
this.Text = "Сборка мебели"; Text = "Сборка мебели";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); Load += FormMain_Load;
this.menuStrip.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
this.menuStrip.PerformLayout(); menuStrip.ResumeLayout(false);
this.ResumeLayout(false); menuStrip.PerformLayout();
this.PerformLayout(); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -240,5 +246,6 @@
private ToolStripMenuItem implementerToolStripMenuItem; private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem startingWorkToolStripMenuItem; private ToolStripMenuItem startingWorkToolStripMenuItem;
private ToolStripMenuItem mailsToolStripMenuItem; private ToolStripMenuItem mailsToolStripMenuItem;
private ToolStripMenuItem createBackUpToolStripMenuItem;
} }
} }

View File

@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DI;
using FurnitureAssemblyDataModels.Enums; using FurnitureAssemblyDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@ -24,7 +25,9 @@ namespace FurnitureAssemblyView
private readonly IWorkProcess _workProcess; private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{ {
InitializeComponent(); InitializeComponent();
@ -32,6 +35,7 @@ namespace FurnitureAssemblyView
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_workProcess = workProcess; _workProcess = workProcess;
_backUpLogic = backUpLogic;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
@ -45,20 +49,9 @@ namespace FurnitureAssemblyView
try try
{ {
var list = _orderLogic.ReadList(null); dataGridView.FillandConfigGrid(_orderLogic.ReadList(null));
if (list != null) _logger.LogInformation("Успешная загрузка заказов");
{
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("Загрузка заказов");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -69,34 +62,24 @@ namespace FurnitureAssemblyView
private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e) private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPieces)); var form = DependencyManager.Instance.Resolve<FormWorkPieces>();
if (service is FormWorkPieces form) form.ShowDialog();
{
form.ShowDialog();
}
} }
private void FurnitureToolStripMenuItem_Click(object sender, EventArgs e) private void FurnitureToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormFurnitures)); var form = DependencyManager.Instance.Resolve<FormFurnitures>();
if (service is FormFurnitures form) form.ShowDialog();
{
form.ShowDialog();
}
} }
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
form.ShowDialog();
LoadData();
} }
private void ButtonIssuedOrder_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
@ -147,63 +130,73 @@ namespace FurnitureAssemblyView
private void WorkPieceFurnituresToolStripMenuItem_Click(object sender, EventArgs e) private void WorkPieceFurnituresToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportFurnitureWorkPieces)); var form = DependencyManager.Instance.Resolve<FormReportFurnitureWorkPieces>();
if (service is FormReportFurnitureWorkPieces form) form.ShowDialog();
{
form.ShowDialog();
}
} }
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var form = DependencyManager.Instance.Resolve<FormReportOrders>();
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(); LoadData();
} }
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormClients)); var form = DependencyManager.Instance.Resolve<FormClients>();
if (service is FormClients form) form.ShowDialog();
{
form.ShowDialog();
}
} }
private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e) private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e)
{ {
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); _workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>()!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e) private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); var form = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormImplementers form) form.ShowDialog();
{
form.ShowDialog();
}
} }
private void MailsToolStripMenuItem_Click(object sender, EventArgs e) private void MailsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormMails)); var form = DependencyManager.Instance.Resolve<FormMails>();
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);
} }
} }
} }

View File

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

View File

@ -48,17 +48,15 @@
this.panel.Controls.Add(this.dateTimePickerFrom); this.panel.Controls.Add(this.dateTimePickerFrom);
this.panel.Dock = System.Windows.Forms.DockStyle.Top; this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0); this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.panel.Name = "panel"; this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(973, 38); this.panel.Size = new System.Drawing.Size(1112, 51);
this.panel.TabIndex = 0; this.panel.TabIndex = 0;
// //
// buttonToPdf // buttonToPdf
// //
this.buttonToPdf.Location = new System.Drawing.Point(782, 8); this.buttonToPdf.Location = new System.Drawing.Point(894, 10);
this.buttonToPdf.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonToPdf.Name = "buttonToPdf"; this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(137, 22); this.buttonToPdf.Size = new System.Drawing.Size(157, 29);
this.buttonToPdf.TabIndex = 5; this.buttonToPdf.TabIndex = 5;
this.buttonToPdf.Text = "В Pdf"; this.buttonToPdf.Text = "В Pdf";
this.buttonToPdf.UseVisualStyleBackColor = true; this.buttonToPdf.UseVisualStyleBackColor = true;
@ -66,10 +64,9 @@
// //
// buttonMake // buttonMake
// //
this.buttonMake.Location = new System.Drawing.Point(630, 8); this.buttonMake.Location = new System.Drawing.Point(612, 10);
this.buttonMake.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonMake.Name = "buttonMake"; this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(137, 22); this.buttonMake.Size = new System.Drawing.Size(157, 29);
this.buttonMake.TabIndex = 4; this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать"; this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true; this.buttonMake.UseVisualStyleBackColor = true;
@ -78,44 +75,41 @@
// label2 // label2
// //
this.label2.AutoSize = true; this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(230, 13); this.label2.Location = new System.Drawing.Point(263, 17);
this.label2.Name = "label2"; this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(21, 15); this.label2.Size = new System.Drawing.Size(27, 20);
this.label2.TabIndex = 3; this.label2.TabIndex = 3;
this.label2.Text = "по"; this.label2.Text = "по";
// //
// label1 // label1
// //
this.label1.AutoSize = true; this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(22, 13); this.label1.Location = new System.Drawing.Point(25, 17);
this.label1.Name = "label1"; this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(15, 15); this.label1.Size = new System.Drawing.Size(18, 20);
this.label1.TabIndex = 2; this.label1.TabIndex = 2;
this.label1.Text = "С"; this.label1.Text = "С";
// //
// dateTimePickerTo // dateTimePickerTo
// //
this.dateTimePickerTo.Location = new System.Drawing.Point(274, 9); this.dateTimePickerTo.Location = new System.Drawing.Point(313, 12);
this.dateTimePickerTo.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dateTimePickerTo.Name = "dateTimePickerTo"; this.dateTimePickerTo.Name = "dateTimePickerTo";
this.dateTimePickerTo.Size = new System.Drawing.Size(148, 23); this.dateTimePickerTo.Size = new System.Drawing.Size(169, 27);
this.dateTimePickerTo.TabIndex = 5; this.dateTimePickerTo.TabIndex = 1;
// //
// dateTimePickerFrom // dateTimePickerFrom
// //
this.dateTimePickerFrom.Location = new System.Drawing.Point(57, 9); this.dateTimePickerFrom.Location = new System.Drawing.Point(65, 12);
this.dateTimePickerFrom.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dateTimePickerFrom.Name = "dateTimePickerFrom"; this.dateTimePickerFrom.Name = "dateTimePickerFrom";
this.dateTimePickerFrom.Size = new System.Drawing.Size(154, 23); this.dateTimePickerFrom.Size = new System.Drawing.Size(176, 27);
this.dateTimePickerFrom.TabIndex = 0; this.dateTimePickerFrom.TabIndex = 0;
// //
// FormReportOrders // FormReportOrders
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(973, 338); this.ClientSize = new System.Drawing.Size(1112, 450);
this.Controls.Add(this.panel); this.Controls.Add(this.panel);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormReportOrders"; this.Name = "FormReportOrders";
this.Text = "Заказы"; this.Text = "Заказы";
this.panel.ResumeLayout(false); this.panel.ResumeLayout(false);

View File

@ -46,9 +46,9 @@ namespace FurnitureAssemblyView
{ {
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{ {
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try try
@ -64,13 +64,13 @@ namespace FurnitureAssemblyView
reportViewer.LocalReport.DataSources.Clear(); reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source); reportViewer.LocalReport.DataSources.Add(source);
var parameters = new[] { new ReportParameter("ReportParameterPeriod", var parameters = new[] { new ReportParameter("ReportParameterPeriod",
$"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") }; $"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters); reportViewer.LocalReport.SetParameters(parameters);
reportViewer.RefreshReport(); reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), _logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(),
dateTimePickerTo.Value.ToShortDateString()); dateTimePickerTo.Value.ToShortDateString());
} }
catch (Exception ex) catch (Exception ex)
@ -85,7 +85,7 @@ namespace FurnitureAssemblyView
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{ {
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
@ -105,7 +105,7 @@ namespace FurnitureAssemblyView
DateTo = dateTimePickerTo.Value DateTo = dateTimePickerTo.Value
}); });
_logger.LogInformation("Сохранение списка заказов на период {From}-{To}", _logger.LogInformation("Сохранение списка заказов на период {From}-{To}",
dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
@ -113,7 +113,7 @@ namespace FurnitureAssemblyView
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка сохранения списка заказов на период"); _logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -37,15 +38,7 @@ namespace FurnitureAssemblyView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillandConfigGrid(_logic.ReadList(null));
// Растягиваем колонку Название на всю ширину, колонку Id скрываем
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заготовок"); _logger.LogInformation("Загрузка заготовок");
} }
@ -59,14 +52,11 @@ namespace FurnitureAssemblyView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); var form = DependencyManager.Instance.Resolve<FormWorkPiece>();
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) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece)); var form = DependencyManager.Instance.Resolve<FormWorkPiece>();
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); LoadData();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
} }
} }
} }

View File

@ -4,6 +4,7 @@ using FurnitureAssemblyBusinessLogic.OfficePackage;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.StoragesContracts; using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatabaseImplement.Implements; using FurnitureAssemblyDatabaseImplement.Implements;
using FurnitureAssemblyContracts.DI;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -15,10 +16,6 @@ namespace FurnitureAssemblyView
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
@ -29,80 +26,75 @@ namespace FurnitureAssemblyView
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
var services = new ServiceCollection(); var services = new ServiceCollection();
ConfigureServices(services); InitDependency();
_serviceProvider = services.BuildServiceProvider();
try try
{ {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>(); var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel mailSender?.MailConfig(new MailConfigBindingModel
{ {
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
}); });
// Ñîçäà¸ì òàéìåð // Ñîçäà¸ì òàéìåð
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
} }
catch (Exception ex) catch (Exception ex)
{ {
var logger = _serviceProvider.GetService<ILogger>(); var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
} }
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); Application.Run(DependencyManager.Instance.Resolve<FormMain>());
} }
private static void ConfigureServices(ServiceCollection services) private static void InitDependency()
{ {
services.AddLogging(option => DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(option =>
{ {
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
services.AddTransient<IWorkPieceStorage, WorkPieceStorage>(); DependencyManager.Instance.RegisterType<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderStorage, OrderStorage>(); DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
services.AddTransient<IFurnitureStorage, FurnitureStorage>(); DependencyManager.Instance.RegisterType<IFurnitureLogic, FurnitureLogic>();
services.AddTransient<IClientStorage, ClientStorage>(); DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>(); DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<IOrderLogic, OrderLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
services.AddTransient<IFurnitureLogic, FurnitureLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>(); DependencyManager.Instance.RegisterType<FormMain>();
services.AddTransient<FormWorkPiece>(); DependencyManager.Instance.RegisterType<FormWorkPiece>();
services.AddTransient<FormWorkPieces>(); DependencyManager.Instance.RegisterType<FormWorkPieces>();
services.AddTransient<FormCreateOrder>(); DependencyManager.Instance.RegisterType<FormCreateOrder>();
services.AddTransient<FormFurniture>(); DependencyManager.Instance.RegisterType<FormFurniture>();
services.AddTransient<FormFurnitures>(); DependencyManager.Instance.RegisterType<FormFurnitureWorkPiece>();
services.AddTransient<FormFurnitureWorkPiece>(); DependencyManager.Instance.RegisterType<FormFurnitures>();
services.AddTransient<FormReportFurnitureWorkPieces>(); DependencyManager.Instance.RegisterType<FormReportFurnitureWorkPieces>();
services.AddTransient<FormReportOrders>(); DependencyManager.Instance.RegisterType<FormReportOrders>();
services.AddTransient<FormClients>(); DependencyManager.Instance.RegisterType<FormClients>();
services.AddTransient<FormImplementers>(); DependencyManager.Instance.RegisterType<FormImplementer>();
services.AddTransient<FormImplementer>(); DependencyManager.Instance.RegisterType<FormImplementers>();
services.AddTransient<FormMails>(); DependencyManager.Instance.RegisterType<FormMails>();
} }
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck(); private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
} }
} }