From 44b7483160405ef25690479101ab6f48a236ce86 Mon Sep 17 00:00:00 2001 From: Salikh Date: Sat, 25 May 2024 16:04:21 +0400 Subject: [PATCH] first commit --- .../BusinessLogic/BackUpLogic.cs | 97 ++++ .../Attributes/ColumnAttribute.cs | 32 ++ .../Attributes/GridViewAutoSize.cs | 21 + .../BindingModels/BackUpSaveBindingModel.cs | 7 + .../BindingModels/MessageInfoBindingModel.cs | 3 +- .../BusinessLogicsContracts/IBackUpLogic.cs | 9 + .../DI/DependencyManager.cs | 61 +++ .../DI/IDependencyContainer.cs | 35 ++ .../DI/IImplementationExtension.cs | 11 + .../DI/ServiceDependencyContainer.cs | 57 ++ .../DI/ServiceProviderLoader.cs | 50 ++ .../StoragesContracts/IBackUpInfo.cs | 9 + .../ViewModels/ClientViewModel.cs | 18 +- .../ViewModels/ComponentViewModel.cs | 16 +- .../ViewModels/EngineViewModel.cs | 17 +- .../ViewModels/ImplementerViewModel.cs | 22 +- .../ViewModels/MessageInfoViewModel.cs | 28 +- .../ViewModels/OrderViewModel.cs | 46 +- .../Models/IMessageInfoModel.cs | 4 +- .../ImplementationExtension.cs | 22 + .../Implements/BackUpInfo.cs | 32 ++ .../Models/Client.cs | 16 +- .../Models/Component.cs | 13 +- .../Models/Engine.cs | 16 +- .../Models/Implementer.cs | 19 +- .../Models/MessageInfo.cs | 10 + .../Models/Order.cs | 23 +- .../MotorPlantDatabaseImplement.csproj | 4 + .../ImplementationExtension.cs | 22 + .../Implements/BackUpInfo.cs | 39 ++ .../MotorPlantFileImplement/Models/Client.cs | 16 +- .../Models/Component.cs | 12 +- .../MotorPlantFileImplement/Models/Engine.cs | 16 +- .../Models/Implementer.cs | 19 +- .../Models/MessageInfo.cs | 25 +- .../MotorPlantFileImplement/Models/Order.cs | 25 +- .../MotorPlantFileImplement.csproj | 4 + .../ImplementationExtension.cs | 22 + .../Implements/BackUpInfo.cs | 17 + .../Models/MessageInfo.cs | 4 +- .../MotorPlantListImplement.csproj | 4 + .../MotorPlantView/DataGridViewExtension.cs | 46 ++ MotorPlant/MotorPlantView/FormClients.cs | 7 +- MotorPlant/MotorPlantView/FormComponents.cs | 30 +- MotorPlant/MotorPlantView/FormEngine.cs | 70 ++- MotorPlant/MotorPlantView/FormEngines.cs | 42 +- MotorPlant/MotorPlantView/FormImplementers.cs | 11 +- MotorPlant/MotorPlantView/FormMail.cs | 12 +- .../MotorPlantView/FormMain.Designer.cs | 511 +++++++++--------- MotorPlant/MotorPlantView/FormMain.cs | 392 +++++++------- MotorPlant/MotorPlantView/Program.cs | 157 +++--- 51 files changed, 1435 insertions(+), 766 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/BusinessLogic/BackUpLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/Attributes/ColumnAttribute.cs create mode 100644 MotorPlant/MotorPlantContracts/Attributes/GridViewAutoSize.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/BackUpSaveBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/DI/DependencyManager.cs create mode 100644 MotorPlant/MotorPlantContracts/DI/IDependencyContainer.cs create mode 100644 MotorPlant/MotorPlantContracts/DI/IImplementationExtension.cs create mode 100644 MotorPlant/MotorPlantContracts/DI/ServiceDependencyContainer.cs create mode 100644 MotorPlant/MotorPlantContracts/DI/ServiceProviderLoader.cs create mode 100644 MotorPlant/MotorPlantContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/ImplementationExtension.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Implements/BackUpInfo.cs create mode 100644 MotorPlant/MotorPlantFileImplement/ImplementationExtension.cs create mode 100644 MotorPlant/MotorPlantFileImplement/Implements/BackUpInfo.cs create mode 100644 MotorPlant/MotorPlantListImplement/ImplementationExtension.cs create mode 100644 MotorPlant/MotorPlantListImplement/Implements/BackUpInfo.cs create mode 100644 MotorPlant/MotorPlantView/DataGridViewExtension.cs diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/BackUpLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..6f7befa --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/BackUpLogic.cs @@ -0,0 +1,97 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.StoragesContracts; +using MotorPlantDataModels; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.Serialization.Json; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + + private readonly IBackUpInfo _backUpInfo; + + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + + public void CreateBackUp(BackUpSaveBindingModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + var dirInfo = new DirectoryInfo(model.FolderName); + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + _logger.LogDebug("Delete archive"); + string fileName = $"{model.FolderName}.zip"; + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + _logger.LogDebug("Find {count} types", types.Length); + foreach (var type in types) + { + if (type.IsInterface && type.GetInterface(typeIId.Name) != null) + { + var modelType = _backUpInfo.GetTypeByModelInterface(type.Name); + if (modelType == null) + { + throw new InvalidOperationException($"Не найден класс-модель для {type.Name}"); + } + _logger.LogDebug("Call SaveToFile method for {name} type", type.Name); + // вызываем метод на выполнение + method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName }); + } + } + _logger.LogDebug("Create zip and remove folder"); + // архивируем + ZipFile.CreateFromDirectory(model.FolderName, fileName); + // удаляем папку + dirInfo.Delete(true); + } + catch (Exception) + { + throw; + } + } + + private void SaveToFile(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + return; + } + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate); + jsonFormatter.WriteObject(fs, records); + } + } +} diff --git a/MotorPlant/MotorPlantContracts/Attributes/ColumnAttribute.cs b/MotorPlant/MotorPlantContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..ead1612 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + 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; } + + 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; + } + } +} diff --git a/MotorPlant/MotorPlantContracts/Attributes/GridViewAutoSize.cs b/MotorPlant/MotorPlantContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..43fe00b --- /dev/null +++ b/MotorPlant/MotorPlantContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,21 @@ +namespace MotorPlantContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/BackUpSaveBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/BackUpSaveBindingModel.cs new file mode 100644 index 0000000..37efa74 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/BackUpSaveBindingModel.cs @@ -0,0 +1,7 @@ +namespace MotorPlantContracts.BindingModels +{ + public class BackUpSaveBindingModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs index a940c2a..3689cc6 100644 --- a/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs +++ b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -15,5 +15,6 @@ namespace MotorPlantContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } - } + public int Id => throw new NotImplementedException(); + } } diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IBackUpLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..dcee80c --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,9 @@ +using MotorPlantContracts.BindingModels; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/DI/DependencyManager.cs b/MotorPlant/MotorPlantContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..bdd9c88 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/DI/DependencyManager.cs @@ -0,0 +1,61 @@ +using Microsoft.Extensions.Logging; + +namespace MotorPlantContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new ServiceDependencyContainer(); + } + + public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } } + + /// + /// Иницализация библиотек, в которых идут установки зависомстей + /// + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + // регистрируем зависимости + ext.RegisterServices(); + } + + /// + /// Регистрация логгера + /// + /// + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Получение класса со всеми зависмостями + /// + /// + /// + public T Resolve() => _dependencyManager.Resolve(); + } +} diff --git a/MotorPlant/MotorPlantContracts/DI/IDependencyContainer.cs b/MotorPlant/MotorPlantContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..0cb9413 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/DI/IDependencyContainer.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Logging; + +namespace MotorPlantContracts.DI +{ + public interface IDependencyContainer + { + /// + /// Регистрация логгера + /// + /// + void AddLogging(Action configure); + + /// + /// Добавление зависимости + /// + /// + /// + /// + void RegisterType(bool isSingle) where U : class, T where T : class; + + /// + /// Добавление зависимости + /// + /// + /// + void RegisterType(bool isSingle) where T : class; + + /// + /// Получение класса со всеми зависмостями + /// + /// + /// + T Resolve(); + } +} diff --git a/MotorPlant/MotorPlantContracts/DI/IImplementationExtension.cs b/MotorPlant/MotorPlantContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..d667c6d --- /dev/null +++ b/MotorPlant/MotorPlantContracts/DI/IImplementationExtension.cs @@ -0,0 +1,11 @@ +namespace MotorPlantContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/MotorPlant/MotorPlantContracts/DI/ServiceDependencyContainer.cs b/MotorPlant/MotorPlantContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..73d4b7a --- /dev/null +++ b/MotorPlant/MotorPlantContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,57 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace MotorPlantContracts.DI +{ + public class ServiceDependencyContainer : IDependencyContainer + { + private ServiceProvider? _serviceProvider; + + private readonly ServiceCollection _serviceCollection; + + public ServiceDependencyContainer() + { + _serviceCollection = new ServiceCollection(); + } + + public void AddLogging(Action configure) + { + _serviceCollection.AddLogging(configure); + } + + public void RegisterType(bool isSingle) where U : class, T where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + _serviceProvider = null; + } + + public void RegisterType(bool isSingle) where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + _serviceProvider = null; + } + + public T Resolve() + { + if (_serviceProvider == null) + { + _serviceProvider = _serviceCollection.BuildServiceProvider(); + } + return _serviceProvider.GetService()!; + } + } +} diff --git a/MotorPlant/MotorPlantContracts/DI/ServiceProviderLoader.cs b/MotorPlant/MotorPlantContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..71d2926 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,50 @@ +using System.Reflection; + +namespace MotorPlantContracts.DI +{ + public class ServiceProviderLoader + { + /// + /// Загрузка всех классов-реализаций IImplementationExtension + /// + /// + public static IImplementationExtension? GetImplementationExtensions() + { + IImplementationExtension? source = null; + var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories); + foreach (var file in files.Distinct()) + { + Assembly asm = Assembly.LoadFrom(file); + foreach (var t in asm.GetExportedTypes()) + { + if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t)) + { + if (source == null) + { + source = (IImplementationExtension)Activator.CreateInstance(t)!; + } + else + { + var newSource = (IImplementationExtension)Activator.CreateInstance(t)!; + if (newSource.Priority > source.Priority) + { + source = newSource; + } + } + } + } + } + return source; + } + + private static string TryGetImplementationExtensionsFolder() + { + var directory = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions")) + { + directory = directory.Parent; + } + return $"{directory?.FullName}\\ImplementationExtensions"; + } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IBackUpInfo.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..ae036d8 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,9 @@ +namespace MotorPlantContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ClientViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ClientViewModel.cs index 3413bd5..85163c2 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/ClientViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/ClientViewModel.cs @@ -1,17 +1,19 @@ -using MotorPlantDataModels.Models; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Models; using System.ComponentModel; namespace MotorPlantContracts.ViewModels { public class ClientViewModel : IClientModel { - public int Id { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] - public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(visible: false)] + public int Id { get; set; } + [Column(title: "ФИО клиента", width: 150)] + public string ClientFIO { get; set; } = string.Empty; + [Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Email { get; set; } = string.Empty; + [Column(title: "Пароль", width: 150)] + public string Password { get; set; } = string.Empty; } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ComponentViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ComponentViewModel.cs index ab561a6..d47271c 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/ComponentViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/ComponentViewModel.cs @@ -1,18 +1,20 @@ -using MotorPlantDataModels.Models; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Models; using System.ComponentModel; namespace MotorPlantContracts.ViewModels { public class ComponentViewModel : IComponentModel { - public int Id { get; set; } + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Название компонента")] - - public string ComponentName { get; set; } = string.Empty; + [Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] - [DisplayName("Цена")] + public string ComponentName { get; set; } = string.Empty; - public double Cost { get; set; } + [Column(title: "Цена", width: 150)] + + public double Cost { get; set; } } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/EngineViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/EngineViewModel.cs index db139d9..4ccfff8 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/EngineViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/EngineViewModel.cs @@ -1,4 +1,5 @@ -using MotorPlantDataModels.Models; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,17 +11,19 @@ namespace MotorPlantContracts.ViewModels { public class EngineViewModel : IEngineModel { - public int Id { get; set; } + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Название изделия")] + [Column(title: "Название двигателя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] - public string EngineName { get; set; } = string.Empty; + public string EngineName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 70)] - public double Price { get; set; } + public double Price { get; set; } - public Dictionary EngineComponents { get; set; } = new(); + [Column(visible: false)] + public Dictionary EngineComponents { get; set; } = new(); } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs index 4384e4b..fb95779 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/ImplementerViewModel.cs @@ -1,22 +1,24 @@ -using MotorPlantDataModels.Models; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Models; using System.ComponentModel; namespace MotorPlantContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { - public int Id { get; set; } + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 100)] + public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] - public int WorkExperience { get; set; } + [Column(title: "Стаж работы", width: 60)] + public int WorkExperience { get; set; } - [DisplayName("Квалификация")] - public int Qualification { get; set; } + [Column(title: "Квалификация", width: 60)] + public int Qualification { get; set; } } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs index c5db751..a8c9257 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using MotorPlantDataModels.Models; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace MotorPlantContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { - public string MessageId { get; set; } = string.Empty; + [Column(visible: false)] + public int Id { get; set; } - public int? ClientId { get; set; } + [Column(visible: false)] + public string MessageId { get; set; } = string.Empty; - [DisplayName("Отправитель")] - public string SenderName { get; set; } = string.Empty; + [Column(visible: false)] + public int? ClientId { get; set; } - [DisplayName("Дата письма")] - public DateTime DateDelivery { get; set; } + [Column(title: "Отправитель", width: 150)] + public string SenderName { get; set; } = string.Empty; - [DisplayName("Заголовок")] - public string Subject { get; set; } = string.Empty; + [Column(title: "Дата письма", width: 120)] + public DateTime DateDelivery { get; set; } - [DisplayName("Текст")] - public string Body { get; set; } = string.Empty; + [Column(title: "Заголовок", width: 120)] + public string Subject { get; set; } = string.Empty; + + [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Body { get; set; } = string.Empty; } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs index 7889603..e855153 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using MotorPlantDataModels.Enums; +using MotorPlantContracts.Attributes; +using MotorPlantDataModels.Enums; using MotorPlantDataModels.Models; using System; using System.Collections.Generic; @@ -11,46 +12,49 @@ namespace MotorPlantContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(title: "Номер", width: 90)] + public int Id { get; set; } - public int Id { get; set; } - - public int EngineId { get; set; } + [Column(visible: false)] + public int EngineId { get; set; } + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("Изделие")] + [Column(title: "Двигатель", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] - public string EngineName { get; set; } = string.Empty; + public string EngineName { get; set; } = string.Empty; - [DisplayName("ФИО клиента")] + [Column(title: "Имя клиента", width: 190)] public string ClientFIO { get; set; } = string.Empty; - public string ClientEmail { get; set; } = string.Empty; + [Column(visible: false)] + public string ClientEmail { get; set; } = string.Empty; - public int? ImplementerId { get; set; } + [Column(visible: false)] + public int? ImplementerId { get; set; } - [DisplayName("Исполнитель")] + [Column(title: "Исполнитель", width: 150)] public string? ImplementerFIO { get; set; } = null; - [DisplayName("Количество")] + [Column(title: "Количество", width: 100)] - public int Count { get; set; } + public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 120)] - public double Sum { get; set; } + public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 70)] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 120)] - public DateTime DateCreate { get; set; } = DateTime.Now; + public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 120)] - public DateTime? DateImplement { get; set; } + public DateTime? DateImplement { get; set; } } } diff --git a/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs b/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs index 6bda5d1..4a7bdf9 100644 --- a/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs +++ b/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs @@ -6,8 +6,8 @@ using System.Threading.Tasks; namespace MotorPlantDataModels.Models { - public interface IMessageInfoModel - { + public interface IMessageInfoModel : IId + { string MessageId { get; } int? ClientId { get; } diff --git a/MotorPlant/MotorPlantDatabaseImplement/ImplementationExtension.cs b/MotorPlant/MotorPlantDatabaseImplement/ImplementationExtension.cs new file mode 100644 index 0000000..ff661ef --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/ImplementationExtension.cs @@ -0,0 +1,22 @@ +using MotorPlantContracts.DI; +using MotorPlantContracts.StoragesContracts; +using MotorPlantDatabaseImplement.Implements; + +namespace MotorPlantDatabaseImplement +{ + public class ImplementationExtension : IImplementationExtension + { + public int Priority => 3; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/BackUpInfo.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..8b939e6 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,32 @@ +using MotorPlantContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new MotorPlantDatabase(); + return context.Set().ToList(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs index 6702cfd..c868058 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs @@ -3,17 +3,23 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { - public class Client : IClientModel + [DataContract] + public class Client : IClientModel { - public int Id { get; private set; } - [Required] + [DataMember] + public int Id { get; private set; } + [DataMember] + [Required] public string ClientFIO { get; private set; } = string.Empty; - [Required] + [DataMember] + [Required] public string Email { get; private set; } = string.Empty; - [Required] + [DataMember] + [Required] public string Password { get; private set; } = string.Empty; [ForeignKey("ClientId")] diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Component.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Component.cs index 223ccc7..2fe04f8 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Component.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Component.cs @@ -3,15 +3,20 @@ using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using MotorPlantContracts.BindingModels; using MotorPlantContracts.ViewModels; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { - public class Component : IComponentModel + [DataContract] + public class Component : IComponentModel { - public int Id { get; private set; } - [Required] + [DataMember] + public int Id { get; private set; } + [DataMember] + [Required] public string ComponentName { get; private set; } = string.Empty; - [Required] + [DataMember] + [Required] public double Cost { get; set; } [ForeignKey("ComponentId")] public virtual List EngineComponents { get; set; } = new(); diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Engine.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Engine.cs index 44db39e..98e7d2a 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Engine.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Engine.cs @@ -3,18 +3,24 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { - public class Engine : IEngineModel + [DataContract] + public class Engine : IEngineModel { - public int Id { get; set; } - [Required] + [DataMember] + public int Id { get; set; } + [DataMember] + [Required] public string EngineName { get; set; } = string.Empty; - [Required] + [DataMember] + [Required] public double Price { get; set; } private Dictionary? _engineComponents = null; - [NotMapped] + [DataMember] + [NotMapped] public Dictionary EngineComponents { get diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Implementer.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Implementer.cs index 8f7cc1e..e48775b 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Implementer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Implementer.cs @@ -3,23 +3,30 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { - public class Implementer : IImplementerModel + [DataContract] + public class Implementer : IImplementerModel { - public int Id { get; set; } + [DataMember] + public int Id { get; set; } - [Required] + [DataMember] + [Required] public string ImplementerFIO { get; set; } = string.Empty; - [Required] + [DataMember] + [Required] public string Password { get; set; } = string.Empty; - [Required] + [DataMember] + [Required] public int WorkExperience { get; set; } - [Required] + [DataMember] + [Required] public int Qualification { get; set; } [ForeignKey("ImplementerId")] diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs index 80fe801..9b3fff6 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs @@ -3,28 +3,38 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { public class MessageInfo : IMessageInfoModel { + [NotMapped] + public int Id { get; private set; } + + [DataMember] [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string MessageId { get; set; } = string.Empty; + [DataMember] public int? ClientId { get; set; } public virtual Client? Client { get; set; } + [DataMember] [Required] public string SenderName { get; set; } = string.Empty; + [DataMember] [Required] public DateTime DateDelivery { get; set; } + [DataMember] [Required] public string Subject { get; set; } = string.Empty; + [DataMember] [Required] public string Body { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 91c89ff..92701e9 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -3,40 +3,51 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Enums; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace MotorPlantDatabaseImplement.Models { - public class Order : IOrderModel + [DataContract] + public class Order : IOrderModel { - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } + [DataMember] [Required] public int EngineId { get; private set; } public virtual Engine Engine { get; set; } = new(); + [DataMember] [Required] public int ClientId { get; private set; } public virtual Client Client { get; private set; } = new(); + [DataMember] public int? ImplementerId { get; private set; } public virtual Implementer? Implementer { get; set; } = new(); + [DataMember] [Required] public int Count { get; private set; } - [Required] + [DataMember] + [Required] public double Sum { get; private set; } - [Required] + [DataMember] + [Required] public OrderStatus Status { get; private set; } - [Required] + [DataMember] + [Required] public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } + [DataMember] + public DateTime? DateImplement { get; private set; } public static Order Create(MotorPlantDatabase context, OrderBindingModel model) { diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj index fa3b43b..a7a79d9 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj @@ -21,4 +21,8 @@ + + + + diff --git a/MotorPlant/MotorPlantFileImplement/ImplementationExtension.cs b/MotorPlant/MotorPlantFileImplement/ImplementationExtension.cs new file mode 100644 index 0000000..f3db880 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/ImplementationExtension.cs @@ -0,0 +1,22 @@ +using MotorPlantContracts.DI; +using MotorPlantContracts.StoragesContracts; +using MotorPlantFileImplement.Implements; + +namespace MotorPlantFileImplement +{ + public class ImplementationExtension : IImplementationExtension + { + public int Priority => 1; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Implements/BackUpInfo.cs b/MotorPlant/MotorPlantFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..a38c352 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,39 @@ +using MotorPlantContracts.StoragesContracts; +using System.Reflection; + +namespace MotorPlantFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + private readonly DataFileSingleton source; + private readonly PropertyInfo[] sourceProperties; + + public BackUpInfo() + { + source = DataFileSingleton.GetInstance(); + sourceProperties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); + } + + public List? GetList() where T : class, new() + { + var requredType = typeof(T); + return (List?)sourceProperties.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == requredType) + ?.GetValue(source); + + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Models/Client.cs b/MotorPlant/MotorPlantFileImplement/Models/Client.cs index 5b9ca46..e329210 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Client.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Client.cs @@ -1,16 +1,22 @@ using MotorPlantContracts.BindingModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class Client : IClientModel + [DataContract] + public class Client : IClientModel { - public int Id { get; private set; } - public string ClientFIO { get; private set; } = string.Empty; - public string Email { get; private set; } = string.Empty; - public string Password { get; private set; } = string.Empty; + [DataMember] + public int Id { get; private set; } + [DataMember] + public string ClientFIO { get; private set; } = string.Empty; + [DataMember] + public string Email { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/MotorPlant/MotorPlantFileImplement/Models/Component.cs b/MotorPlant/MotorPlantFileImplement/Models/Component.cs index b6e440b..e0bdc13 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Component.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Component.cs @@ -1,15 +1,21 @@ using MotorPlantContracts.BindingModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class Component : IComponentModel + [DataContract] + public class Component : IComponentModel { - public int Id { get; private set; } - public string ComponentName { get; private set; } = string.Empty; + [DataMember] + public int Id { get; private set; } + [DataMember] + public string ComponentName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } + public static Component? Create(ComponentBindingModel model) { if (model == null) diff --git a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs index 47f3f3c..37ffcd3 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs @@ -1,18 +1,24 @@ using MotorPlantContracts.BindingModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class Engine : IEngineModel + [DataContract] + public class Engine : IEngineModel { - public int Id { get; private set; } - public string EngineName { get; private set; } = string.Empty; - public double Price { get; private set; } + [DataMember] + public int Id { get; private set; } + [DataMember] + public string EngineName { get; private set; } = string.Empty; + [DataMember] + public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _EngineComponents = null; - public Dictionary EngineComponents + [DataMember] + public Dictionary EngineComponents { get { diff --git a/MotorPlant/MotorPlantFileImplement/Models/Implementer.cs b/MotorPlant/MotorPlantFileImplement/Models/Implementer.cs index 719136d..57faea7 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Implementer.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Implementer.cs @@ -4,23 +4,30 @@ using MotorPlantDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class Implementer : IImplementerModel + [DataContract] + public class Implementer : IImplementerModel { - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } - public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] + public string ImplementerFIO { get; private set; } = string.Empty; - public string Password { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; - public int WorkExperience { get; private set; } + [DataMember] + public int WorkExperience { get; private set; } - public int Qualification { get; private set; } + [DataMember] + public int Qualification { get; private set; } public static Implementer? Create(XElement element) { diff --git a/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs index b8c9785..5b20ae6 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs @@ -1,23 +1,34 @@ using MotorPlantContracts.BindingModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { - public string MessageId { get; private set; } = string.Empty; + [DataMember] + public int Id { get; private set; } - public int? ClientId { get; private set; } + [DataMember] + public string MessageId { get; private set; } = string.Empty; - public string SenderName { get; private set; } = string.Empty; + [DataMember] + public int? ClientId { get; private set; } - public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] + public string SenderName { get; private set; } = string.Empty; - public string Subject { get; private set; } = string.Empty; + [DataMember] + public DateTime DateDelivery { get; private set; } = DateTime.Now; - public string Body { get; private set; } = string.Empty; + [DataMember] + public string Subject { get; private set; } = string.Empty; + + [DataMember] + public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) { diff --git a/MotorPlant/MotorPlantFileImplement/Models/Order.cs b/MotorPlant/MotorPlantFileImplement/Models/Order.cs index a0bd1e4..ba1b840 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Order.cs @@ -2,21 +2,32 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Enums; using MotorPlantDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace MotorPlantFileImplement.Models { - public class Order : IOrderModel + [DataContract] + public class Order : IOrderModel { - public int EngineId { get; private set; } + [DataMember] + public int EngineId { get; private set; } + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; set; } + [DataMember] public int Count { get; private set; } - public double Sum { get; private set; } - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } - public int Id { get; private set; } + [DataMember] + public double Sum { get; private set; } + [DataMember] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] + public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] + public DateTime? DateImplement { get; private set; } + [DataMember] + public int Id { get; private set; } public static Order? Create(OrderBindingModel? model) { diff --git a/MotorPlant/MotorPlantFileImplement/MotorPlantFileImplement.csproj b/MotorPlant/MotorPlantFileImplement/MotorPlantFileImplement.csproj index 706e69d..d205555 100644 --- a/MotorPlant/MotorPlantFileImplement/MotorPlantFileImplement.csproj +++ b/MotorPlant/MotorPlantFileImplement/MotorPlantFileImplement.csproj @@ -15,4 +15,8 @@ + + + + diff --git a/MotorPlant/MotorPlantListImplement/ImplementationExtension.cs b/MotorPlant/MotorPlantListImplement/ImplementationExtension.cs new file mode 100644 index 0000000..d71d491 --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/ImplementationExtension.cs @@ -0,0 +1,22 @@ +using MotorPlantContracts.DI; +using MotorPlantContracts.StoragesContracts; +using MotorPlantListImplement.Implements; + +namespace MotorPlantListImplement +{ + internal class ImplementationExtension + { + public int Priority => 0; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Implements/BackUpInfo.cs b/MotorPlant/MotorPlantListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..798604a --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,17 @@ +using MotorPlantContracts.StoragesContracts; + +namespace MotorPlantListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + throw new NotImplementedException(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + throw new NotImplementedException(); + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs index 7c90ac7..6196551 100644 --- a/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs +++ b/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs @@ -18,7 +18,9 @@ namespace MotorPlantListImplement.Models public string Body { get; private set; } = string.Empty; - public static MessageInfo? Create(MessageInfoBindingModel model) + public int Id => throw new NotImplementedException(); + + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) { diff --git a/MotorPlant/MotorPlantListImplement/MotorPlantListImplement.csproj b/MotorPlant/MotorPlantListImplement/MotorPlantListImplement.csproj index 706e69d..d205555 100644 --- a/MotorPlant/MotorPlantListImplement/MotorPlantListImplement.csproj +++ b/MotorPlant/MotorPlantListImplement/MotorPlantListImplement.csproj @@ -15,4 +15,8 @@ + + + + diff --git a/MotorPlant/MotorPlantView/DataGridViewExtension.cs b/MotorPlant/MotorPlantView/DataGridViewExtension.cs new file mode 100644 index 0000000..9ace8b0 --- /dev/null +++ b/MotorPlant/MotorPlantView/DataGridViewExtension.cs @@ -0,0 +1,46 @@ +using MotorPlantContracts.Attributes; + +namespace MotorPlantView +{ + internal static class DataGridViewExtension + { + public static void FillAndConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormClients.cs b/MotorPlant/MotorPlantView/FormClients.cs index ba49e89..0a3db10 100644 --- a/MotorPlant/MotorPlantView/FormClients.cs +++ b/MotorPlant/MotorPlantView/FormClients.cs @@ -24,12 +24,7 @@ namespace MotorPlantView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) diff --git a/MotorPlant/MotorPlantView/FormComponents.cs b/MotorPlant/MotorPlantView/FormComponents.cs index 6c22176..e6326ac 100644 --- a/MotorPlant/MotorPlantView/FormComponents.cs +++ b/MotorPlant/MotorPlantView/FormComponents.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.DI; namespace MotorPlantView.Forms { @@ -42,29 +43,24 @@ namespace MotorPlantView.Forms private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } } private void buttonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } } } diff --git a/MotorPlant/MotorPlantView/FormEngine.cs b/MotorPlant/MotorPlantView/FormEngine.cs index f292451..ad73b30 100644 --- a/MotorPlant/MotorPlantView/FormEngine.cs +++ b/MotorPlant/MotorPlantView/FormEngine.cs @@ -3,6 +3,7 @@ using MotorPlantDataModels.Models; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.BindingModels; +using MotorPlantContracts.DI; namespace MotorPlantView.Forms { @@ -75,50 +76,43 @@ namespace MotorPlantView.Forms private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormEngineComponent)); - if (service is FormEngineComponent form) - { - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count); - if (_productComponents.ContainsKey(form.Id)) - { - _productComponents[form.Id] = (form.ComponentModel, form.Count); - } - else - { - _productComponents.Add(form.Id, (form.ComponentModel, form.Count)); - } - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + return; } - } + _logger.LogInformation("Добавление нового компонента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + if (_productComponents.ContainsKey(form.Id)) + { + _productComponents[form.Id] = (form.ComponentModel, + form.Count); + } + else + { + _productComponents.Add(form.Id, (form.ComponentModel, + form.Count)); + } + LoadData(); + } private void buttonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormEngineComponent)); - if (service is FormEngineComponent form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _productComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _productComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _productComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Изменение компонента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + _productComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); + } } } diff --git a/MotorPlant/MotorPlantView/FormEngines.cs b/MotorPlant/MotorPlantView/FormEngines.cs index 7e129dc..2aad0ff 100644 --- a/MotorPlant/MotorPlantView/FormEngines.cs +++ b/MotorPlant/MotorPlantView/FormEngines.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.DI; namespace MotorPlantView.Forms { @@ -24,16 +25,9 @@ namespace MotorPlantView.Forms { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["EngineComponents"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка компонентов"); - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка движков"); + } catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки компонентов"); @@ -42,29 +36,23 @@ namespace MotorPlantView.Forms private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormEngine)); - if (service is FormEngine form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } } private void buttonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormEngine)); - if (service is FormEngine form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } } } diff --git a/MotorPlant/MotorPlantView/FormImplementers.cs b/MotorPlant/MotorPlantView/FormImplementers.cs index 39a97c1..467e41e 100644 --- a/MotorPlant/MotorPlantView/FormImplementers.cs +++ b/MotorPlant/MotorPlantView/FormImplementers.cs @@ -29,15 +29,8 @@ namespace MotorPlantView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка исполнителей"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) { diff --git a/MotorPlant/MotorPlantView/FormMail.cs b/MotorPlant/MotorPlantView/FormMail.cs index 542ce87..831dd41 100644 --- a/MotorPlant/MotorPlantView/FormMail.cs +++ b/MotorPlant/MotorPlantView/FormMail.cs @@ -19,16 +19,8 @@ namespace MotorPlantView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка писем"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка писем"); } catch (Exception ex) { diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index cce31d8..853d3d8 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,259 +1,268 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - toolStrip1 = new ToolStrip(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - ДвигателиToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - почтаToolStripMenuItem = new ToolStripMenuItem(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - dataGridView = new DataGridView(); - toolStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // toolStrip1 - // - toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); - toolStrip1.Location = new Point(0, 0); - toolStrip1.Name = "toolStrip1"; - toolStrip1.Size = new Size(1231, 25); - toolStrip1.TabIndex = 0; - toolStrip1.Text = "toolStrip1"; - // - // toolStripDropDownButton1 - // - toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(88, 22); - toolStripDropDownButton1.Text = "Справочник"; - // - // КомпонентыToolStripMenuItem - // - КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - КомпонентыToolStripMenuItem.Size = new Size(149, 22); - КомпонентыToolStripMenuItem.Text = "Компоненты"; - КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // ДвигателиToolStripMenuItem - // - ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; - ДвигателиToolStripMenuItem.Size = new Size(149, 22); - ДвигателиToolStripMenuItem.Text = "Двигатели"; - ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(149, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(149, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(60, 25); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокДвигателейToolStripMenuItem - // - списокДвигателейToolStripMenuItem.Name = "списокДвигателейToolStripMenuItem"; - списокДвигателейToolStripMenuItem.Size = new Size(228, 22); - списокДвигателейToolStripMenuItem.Text = "Список двигателей"; - списокДвигателейToolStripMenuItem.Click += списокДвигателейToolStripMenuItem_Click; - // - // компонентыПоДвигателямToolStripMenuItem - // - компонентыПоДвигателямToolStripMenuItem.Name = "компонентыПоДвигателямToolStripMenuItem"; - компонентыПоДвигателямToolStripMenuItem.Size = new Size(228, 22); - компонентыПоДвигателямToolStripMenuItem.Text = "Компоненты по двигателям"; - компонентыПоДвигателямToolStripMenuItem.Click += компонентыПоДвигателямToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(228, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 25); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // почтаToolStripMenuItem - // - почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; - почтаToolStripMenuItem.Size = new Size(53, 25); - почтаToolStripMenuItem.Text = "Почта"; - почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; - // - // buttonCreateOrder - // - buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonCreateOrder.BackColor = SystemColors.ControlLight; - buttonCreateOrder.Location = new Point(1043, 146); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(178, 30); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = false; - buttonCreateOrder.Click += buttonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; - buttonTakeOrderInWork.Location = new Point(1043, 194); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(178, 30); - buttonTakeOrderInWork.TabIndex = 2; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = false; - buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonOrderReady.BackColor = SystemColors.ControlLight; - buttonOrderReady.Location = new Point(1043, 242); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(178, 30); - buttonOrderReady.TabIndex = 3; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = false; - buttonOrderReady.Click += buttonOrderReady_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonIssuedOrder.BackColor = SystemColors.ControlLight; - buttonIssuedOrder.Location = new Point(1043, 287); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(178, 30); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = false; - buttonIssuedOrder.Click += buttonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonRef.BackColor = SystemColors.ControlLight; - buttonRef.Location = new Point(1043, 100); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(178, 30); - buttonRef.TabIndex = 5; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = false; - buttonRef.Click += buttonRef_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 26); - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(1026, 441); - dataGridView.TabIndex = 6; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1231, 467); - Controls.Add(dataGridView); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(toolStrip1); - Name = "FormMain"; - Text = "Моторный завод"; - Load += FormMain_Load; - toolStrip1.ResumeLayout(false); - toolStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + toolStrip1 = new ToolStrip(); + toolStripDropDownButton1 = new ToolStripDropDownButton(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + ДвигателиToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + dataGridView = new DataGridView(); + создатьБекапToolStripMenuItem = new ToolStripMenuItem(); + toolStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // toolStrip1 + // + toolStrip1.ImageScalingSize = new Size(20, 20); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem, создатьБекапToolStripMenuItem }); + toolStrip1.Location = new Point(0, 0); + toolStrip1.Name = "toolStrip1"; + toolStrip1.Size = new Size(1231, 25); + toolStrip1.TabIndex = 0; + toolStrip1.Text = "toolStrip1"; + // + // toolStripDropDownButton1 + // + toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; + toolStripDropDownButton1.Name = "toolStripDropDownButton1"; + toolStripDropDownButton1.Size = new Size(88, 22); + toolStripDropDownButton1.Text = "Справочник"; + // + // КомпонентыToolStripMenuItem + // + КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; + КомпонентыToolStripMenuItem.Size = new Size(149, 22); + КомпонентыToolStripMenuItem.Text = "Компоненты"; + КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // ДвигателиToolStripMenuItem + // + ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; + ДвигателиToolStripMenuItem.Size = new Size(149, 22); + ДвигателиToolStripMenuItem.Text = "Двигатели"; + ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(149, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(149, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 25); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокДвигателейToolStripMenuItem + // + списокДвигателейToolStripMenuItem.Name = "списокДвигателейToolStripMenuItem"; + списокДвигателейToolStripMenuItem.Size = new Size(228, 22); + списокДвигателейToolStripMenuItem.Text = "Список двигателей"; + списокДвигателейToolStripMenuItem.Click += списокДвигателейToolStripMenuItem_Click; + // + // компонентыПоДвигателямToolStripMenuItem + // + компонентыПоДвигателямToolStripMenuItem.Name = "компонентыПоДвигателямToolStripMenuItem"; + компонентыПоДвигателямToolStripMenuItem.Size = new Size(228, 22); + компонентыПоДвигателямToolStripMenuItem.Text = "Компоненты по двигателям"; + компонентыПоДвигателямToolStripMenuItem.Click += компонентыПоДвигателямToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(228, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 25); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 25); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.BackColor = SystemColors.ControlLight; + buttonCreateOrder.Location = new Point(1043, 146); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(178, 30); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = false; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; + buttonTakeOrderInWork.Location = new Point(1043, 194); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(178, 30); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = false; + buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonOrderReady.BackColor = SystemColors.ControlLight; + buttonOrderReady.Location = new Point(1043, 242); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(178, 30); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = false; + buttonOrderReady.Click += buttonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonIssuedOrder.BackColor = SystemColors.ControlLight; + buttonIssuedOrder.Location = new Point(1043, 287); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(178, 30); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = false; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.BackColor = SystemColors.ControlLight; + buttonRef.Location = new Point(1043, 100); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(178, 30); + buttonRef.TabIndex = 5; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = false; + buttonRef.Click += buttonRef_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 26); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 24; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(1026, 441); + dataGridView.TabIndex = 6; + // + // создатьБекапToolStripMenuItem + // + создатьБекапToolStripMenuItem.Name = "создатьБекапToolStripMenuItem"; + создатьБекапToolStripMenuItem.Size = new Size(97, 25); + создатьБекапToolStripMenuItem.Text = "Создать Бекап"; + создатьБекапToolStripMenuItem.Click += создатьБекапToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1231, 467); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(toolStrip1); + Name = "FormMain"; + Text = "Моторный завод"; + Load += FormMain_Load; + toolStrip1.ResumeLayout(false); + toolStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private ToolStrip toolStrip1; - private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; - private Button buttonIssuedOrder; - private Button buttonRef; - private DataGridView dataGridView; - private ToolStripDropDownButton toolStripDropDownButton1; - private ToolStripMenuItem КомпонентыToolStripMenuItem; - private ToolStripMenuItem ДвигателиToolStripMenuItem; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem списокДвигателейToolStripMenuItem; - private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem исполнителиToolStripMenuItem; - private ToolStripMenuItem запускРаботToolStripMenuItem; - private ToolStripMenuItem почтаToolStripMenuItem; - } + private ToolStrip toolStrip1; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRef; + private DataGridView dataGridView; + private ToolStripDropDownButton toolStripDropDownButton1; + private ToolStripMenuItem КомпонентыToolStripMenuItem; + private ToolStripMenuItem ДвигателиToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem списокДвигателейToolStripMenuItem; + private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem почтаToolStripMenuItem; + private ToolStripMenuItem создатьБекапToolStripMenuItem; + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index 0e880b1..f963de6 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -1,216 +1,208 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.DI; namespace MotorPlantView.Forms { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + private readonly IBackUpLogic _backUpLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + _backUpLogic = backUpLogic; + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); + } + private void buttonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id, + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientEmail"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + private void списокДвигателейToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveEngineToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + private void компонентыПоДвигателямToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } - if (service is FormEngines form) - { - form.ShowDialog(); - } - } - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } - private void buttonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id, - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } - private void списокДвигателейToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveEngineToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } - private void компонентыПоДвигателямToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportEngineComponents)); - if (service is FormReportEngineComponents form) - { - form.ShowDialog(); - } - } + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(DependencyManager.Instance.Resolve(), _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } - private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + private void почтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } - private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } - - private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - - private void почтаToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormMail)); - if (service is FormMail form) - { - form.ShowDialog(); - } - } - } + private void создатьБекапToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBindingModel + { + FolderName = fbd.SelectedPath + }); + MessageBox.Show("Бекап создан", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка создания бэкапа", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } } diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 76f012a..c892d36 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -12,93 +12,88 @@ using MotorPlantBusinessLogic.OfficePackage; using System.Text; using MotorPlantBusinessLogic.MailWorker; using MotorPlantContracts.BindingModels; +using MotorPlantContracts.DI; namespace MotorPlantView { - internal static class Program - { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); - try - { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); + internal static class Program + { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + InitDependency(); + try + { + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); - } - catch (Exception ex) - { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, "Mails Problem"); - } - Application.Run(_serviceProvider.GetRequiredService()); - } - private static void ConfigureServices(ServiceCollection services) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = DependencyManager.Instance.Resolve(); + logger?.LogError(ex, "Mails Problem"); + } + Application.Run(DependencyManager.Instance.Resolve()); + } + private static void InitDependency() + { + DependencyManager.InitDependency(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); - } + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); + } } \ No newline at end of file -- 2.25.1