From f42c402c7a6c7224cd7472100718b9740306c656 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 11:30:45 +0400 Subject: [PATCH 1/4] =?UTF-8?q?8=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/BackUpLogic.cs | 101 ++++++++++++++++++ .../Attributes/ColumnAttribute.cs | 26 +++++ .../Attributes/GridViewAutoSize.cs | 20 ++++ .../BindingModels/BackUpSaveBindingModel.cs | 13 +++ 4 files changed, 160 insertions(+) create mode 100644 ComputersShop/ComputersShopBusinessLogic/BusinessLogic/BackUpLogic.cs create mode 100644 ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs create mode 100644 ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs create mode 100644 ComputersShop/ComputersShopContracts/BindingModels/BackUpSaveBindingModel.cs diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/BackUpLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..88027bc --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/BackUpLogic.cs @@ -0,0 +1,101 @@ +using ComputersShopDataModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.BusinessLogic +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + + private readonly IBackUpInfo _backUpInfo; + + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + + public void CreateBackUp(BackUpSaveBinidngModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + _logger.LogDebug("Delete archive"); + string fileName = $"{model.FolderName}.zip"; + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + _logger.LogDebug("Find {count} types", types.Length); + foreach (var type in types) + { + 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/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs b/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..3ed8f81 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + public string Title { get; private set; } + public bool Visible { get; private set; } + public int Width { get; private set; } + public GridViewAutoSize GridViewAutoSize { get; private set; } + public bool IsUseAutoSize { get; private set; } + } +} diff --git a/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs b/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..a23edde --- /dev/null +++ b/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + None = 1, + ColumnHeader = 2, + AllCellsExceptHeader = 4, + AllCells = 6, + DisplayedCellsExceptHeader = 8, + DisplayedCells = 10, + Fill = 16 + } +} diff --git a/ComputersShop/ComputersShopContracts/BindingModels/BackUpSaveBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/BackUpSaveBindingModel.cs new file mode 100644 index 0000000..12d7c35 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/BackUpSaveBindingModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} -- 2.25.1 From 97138f65127b8b9e9aa7a4d811d9d54e02bbcc9f Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 11:35:18 +0400 Subject: [PATCH 2/4] 8 --- .../BindingModels/MessageInfoBindingModel.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs index 2966e42..f7cd9a0 100644 --- a/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs +++ b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -20,5 +20,6 @@ namespace ComputersShopContracts.BindingModels public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } + public int Id => throw new NotImplementedException(); } } -- 2.25.1 From 2629bbd404431d8bf20ab55ea838b91e24f39055 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 12:33:31 +0400 Subject: [PATCH 3/4] =?UTF-8?q?8=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogicsContracts/IBackUpLogic.cs | 14 ++ .../ComputersShopContracts.csproj | 8 +- .../DI/DependencyManager.cs | 43 ++++++ .../DI/IDependencyContainer.cs | 16 ++ .../DI/IImplementationExtension.cs | 14 ++ .../DI/ServiceDependencyContainer.cs | 60 ++++++++ .../DI/ServiceProviderLoader.cs | 59 ++++++++ .../DI/UnityDependencyContainer.cs | 40 +++++ .../StoragesContracts/IBackUpInfo.cs | 14 ++ .../ViewModels/ClientViewModel.cs | 10 +- .../ViewModels/ComponentViewModel.cs | 8 +- .../ViewModels/ComputerViewModel.cs | 9 +- .../ViewModels/OrderViewModel.cs | 37 +++-- .../Models/IMessageInfoModel.cs | 2 +- .../ComputersShopDatabaseImplement.csproj | 4 + .../DatabaseImplementationExtension.cs | 24 +++ .../Implements/BackUpInfo.cs | 32 ++++ .../Models/Client.cs | 7 +- .../Models/Component.cs | 5 + .../Models/Computer.cs | 5 + .../Models/Message.cs | 4 + .../Models/Order.cs | 56 +++---- .../ComputersShopFileImplement.csproj | 5 + .../FileImplementationExtension.cs | 24 +++ .../Implements/BackUpInfo.cs | 35 +++++ .../Models/Client.cs | 9 +- .../Models/Component.cs | 5 + .../Models/Computer.cs | 5 + .../Models/Message.cs | 8 + .../Models/Order.cs | 10 ++ .../ComputersShopListImplement.csproj | 4 + .../Implements/BackUpInfo.cs | 22 +++ .../ListImplementationExtension.cs | 23 +++ .../Models/Message.cs | 2 +- .../DataGridViewExtension.cs | 51 +++++++ .../ComputersShopView/FormClients.cs | 8 +- .../ComputersShopView/FormComponents.cs | 25 +--- .../ComputersShopView/FormComputer.cs | 72 ++++----- .../ComputersShopView/FormComputers.cs | 29 ++-- ComputersShop/ComputersShopView/FormMails.cs | 9 +- ComputersShop/ComputersShopView/FormMain.cs | 140 +++++++++++++----- ComputersShop/ComputersShopView/Program.cs | 75 +++++----- 42 files changed, 816 insertions(+), 216 deletions(-) create mode 100644 ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/DependencyManager.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/IDependencyContainer.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/IImplementationExtension.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/ServiceDependencyContainer.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/ServiceProviderLoader.cs create mode 100644 ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs create mode 100644 ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Implements/BackUpInfo.cs create mode 100644 ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs create mode 100644 ComputersShop/ComputersShopFileImplement/Implements/BackUpInfo.cs create mode 100644 ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs create mode 100644 ComputersShop/ComputersShopListImplement/ListImplementationExtension.cs create mode 100644 ComputersShop/ComputersShopView/DataGridViewExtension.cs diff --git a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..f5aba3b --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using ComputersShopContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj b/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj index 3dca1b9..09b804b 100644 --- a/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj +++ b/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj @@ -5,7 +5,13 @@ enable enable - + + + + + + + diff --git a/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs b/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..7db450e --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/DI/IDependencyContainer.cs b/ComputersShop/ComputersShopContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..b65ba3e --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/IDependencyContainer.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/DI/IImplementationExtension.cs b/ComputersShop/ComputersShopContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..f0d9c00 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + public void RegisterServices(); + } +} diff --git a/ComputersShop/ComputersShopContracts/DI/ServiceDependencyContainer.cs b/ComputersShop/ComputersShopContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..394c759 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/DI/ServiceProviderLoader.cs b/ComputersShop/ComputersShopContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..68b9ed2 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.DI +{ + public class ServiceProviderLoader + { + 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/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs b/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..b95f1ad --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + + } + + public T Resolve() + { + return _container.Resolve(); + } + + void IDependencyContainer.RegisterType(bool isSingle) + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + } +} diff --git a/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..8772025 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ClientViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ClientViewModel.cs index 37d8fb3..b5e6d2e 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ClientViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using ComputersShopDataModels.Models; +using ComputersShopContracts.Attributes; +using ComputersShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,15 +11,16 @@ namespace ComputersShopContracts.ViewModels { public class ClientViewModel : IClientModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО клиента")] + [Column("ФИО клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] + [Column("Логин (эл. почта)", width: 200)] public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column("Пароль", width: 150)] public string Password { get; set; } = string.Empty; } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs index 484c23c..7074d23 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs @@ -1,4 +1,5 @@ -using ComputersShopDataModels.Models; +using ComputersShopContracts.Attributes; +using ComputersShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,10 +11,11 @@ namespace ComputersShopContracts.ViewModels { public class ComponentViewModel : IComponentModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название компонента")] + [Column("Название комплектующего", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column("Цена", width: 100)] public double Cost { get; set; } } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs index bb8de43..8368571 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs @@ -1,4 +1,5 @@ -using ComputersShopDataModels.Models; +using ComputersShopContracts.Attributes; +using ComputersShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,11 +11,13 @@ namespace ComputersShopContracts.ViewModels { public class ComputerViewModel : IComputerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название изделия")] + [Column("Название компьютера", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComputerName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column("Цена", width: 100)] public double Price { get; set; } + [Column(visible: false)] public Dictionary ComputerComponents { get; diff --git a/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs index d5edd61..e7dc24d 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using ComputersShopDataModels.Enums; +using ComputersShopContracts.Attributes; +using ComputersShopDataModels.Enums; using ComputersShopDataModels.Models; using System; using System.Collections.Generic; @@ -11,25 +12,43 @@ namespace ComputersShopContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public int Id { get; set; } + + [Column(visible: false)] public int ComputerId { get; set; } - [DisplayName("Изделие")] + + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("Фамилия клиента")] + + [Column("Данные клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] public string ClientEmail { get; set; } = string.Empty; + + [Column(visible: false)] + public int? ImplementerId { get; set; } + + [Column("Данные исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ImplementerFIO { get; set; } = string.Empty; + + [Column("Компьютер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public string ComputerName { get; set; } = string.Empty; - [DisplayName("Количество")] + + [Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public int Count { get; set; } - [DisplayName("Сумма")] + + [Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public double Sum { get; set; } - [DisplayName("Статус")] + + [Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + + [Column("Дата создания", width: 100)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + + [Column("Дата выполнения", width: 100)] public DateTime? DateImplement { get; set; } } } diff --git a/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs index 5985ff7..77f4620 100644 --- a/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs +++ b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace ComputersShopDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } diff --git a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj index 74551a6..b864428 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj @@ -19,4 +19,8 @@ + + + + diff --git a/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs b/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..40e664d --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplement +{ + public class DatabaseImplementationExtension : IImplementationExtension + { + public int Priority => 2; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/ComputersShop/ComputersShopDatabaseImplement/Implements/BackUpInfo.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..70eff52 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,32 @@ +using ComputersShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new ComputersShopDataBase(); + 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/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs index 8de42c7..762c2ba 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs @@ -11,21 +11,26 @@ using ComputersShopDataModels.Models; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { [Required] + [DataMember] public string ClientFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Email { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; - + [DataMember] public int Id { get; set; } [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] public virtual List Messages { get; set; } = new(); diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs index 7168ead..332626d 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs @@ -8,15 +8,20 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string ComponentName { get; private set; } = string.Empty; [Required] + [DataMember] public double Cost { get; set; } [ForeignKey("ComponentId")] public virtual List ComputerComponents { get; set; } = diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs index 4d2bee4..8ee892c 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs @@ -8,15 +8,20 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Computer : IComputerModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ComputerName { get; set; } = string.Empty; [Required] + [DataMember] public double Price { get; set; } private Dictionary? _computerComponents = null; diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs index 42faf5e..6a28969 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ComputersShopDataBaseImplement.Models @@ -12,6 +13,7 @@ namespace ComputersShopDataBaseImplement.Models public class Message : IMessageInfoModel { [Key] + [DataMember] public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } @@ -40,6 +42,7 @@ namespace ComputersShopDataBaseImplement.Models MessageId = model.MessageId, SenderName = model.SenderName, DateDelivery = DateTime.SpecifyKind(model.DateDelivery, DateTimeKind.Utc) + }; } @@ -52,5 +55,6 @@ namespace ComputersShopDataBaseImplement.Models SenderName = SenderName, DateDelivery = DateDelivery, }; + public int Id => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs index 5775e5e..473582b 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs @@ -7,41 +7,42 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Order : IOrderModel { - public int Id { get; private set; } - [Required] - public int ComputerId { get; private set; } - - - - public virtual Computer Computer { get; set; } = new(); - + [DataMember] + public int ComputerId { get; set; } [Required] - public int Count { get; private set; } - - [Required] - public double Sum { get; private set; } - - [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - - [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; - - public DateTime? DateImplement { get; private set; } + [DataMember] public int ClientId { get; private set; } + [DataMember] + public int? ImplementerId { get; set; } [Required] - + [DataMember] + public int Count { get; set; } + [Required] + [DataMember] + public double Sum { get; set; } + [Required] + [DataMember] + public OrderStatus Status { get; set; } + [Required] + [DataMember] + public DateTime DateCreate { get; set; } + [DataMember] + public DateTime? DateImplement { get; set; } + public virtual Computer Computer { get; set; } public virtual Client Client { get; set; } - - public static Order Create(OrderBindingModel model) + public virtual Implementer? Implementer { get; set; } + public int Id { get; set; } + public static Order? Create(OrderBindingModel? model) { if (model == null) { @@ -52,11 +53,12 @@ namespace ComputersShopDatabaseImplement.Models Id = model.Id, ComputerId = model.ComputerId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement, + DateImplement = model.DateImplement }; } @@ -68,6 +70,7 @@ namespace ComputersShopDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() @@ -76,13 +79,14 @@ namespace ComputersShopDatabaseImplement.Models ComputerId = ComputerId, ClientId = ClientId, ClientFIO = Client.ClientFIO, - ComputerName = Computer.ComputerName, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - ClientEmail = Client.Email, + ComputerName = Computer.ComputerName }; } } diff --git a/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj b/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj index b897a9c..7e97c68 100644 --- a/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj +++ b/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj @@ -10,5 +10,10 @@ + + + + + diff --git a/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs b/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..7e1f56c --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplement +{ + public class FileImplementationExtension : IImplementationExtension + { + public int Priority => 1; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/ComputersShop/ComputersShopFileImplement/Implements/BackUpInfo.cs b/ComputersShop/ComputersShopFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..90c1403 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,35 @@ +using ComputersShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + // Получаем значения из singleton-объекта универсального свойства содержащее тип T + var source = DataFileSingleton.GetInstance(); + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/ComputersShop/ComputersShopFileImplement/Models/Client.cs b/ComputersShop/ComputersShopFileImplement/Models/Client.cs index 2394404..5833e5f 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Client.cs @@ -4,20 +4,23 @@ using ComputersShopDataModels.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 ComputersShopFileImplement.Models { + [DataContract] public class Client : IClientModel { + [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; - + [DataMember] public int Id { get; private set; } public static Client? Create(ClientBindingModel model) diff --git a/ComputersShop/ComputersShopFileImplement/Models/Component.cs b/ComputersShop/ComputersShopFileImplement/Models/Component.cs index c8ee0d0..f07aa7f 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Component.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Component.cs @@ -4,16 +4,21 @@ using ComputersShopDataModels.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 ComputersShopFileImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ComponentName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } public static Component? Create(ComponentBindingModel model) diff --git a/ComputersShop/ComputersShopFileImplement/Models/Computer.cs b/ComputersShop/ComputersShopFileImplement/Models/Computer.cs index f47a031..ded043d 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Computer.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Computer.cs @@ -4,16 +4,21 @@ using ComputersShopDataModels.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 ComputersShopFileImplement.Models { + [DataContract] public class Computer : IComputerModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ComputerName { get; private set; } = string.Empty; + [DataMember] public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _computerComponents = null; diff --git a/ComputersShop/ComputersShopFileImplement/Models/Message.cs b/ComputersShop/ComputersShopFileImplement/Models/Message.cs index 45ae353..b3b97c6 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Message.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Message.cs @@ -4,26 +4,34 @@ using ComputersShopDataModels.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 ComputersShopFileImplement.Models { + [DataContract] public class Message : IMessageInfoModel { + [DataMember] public string MessageId { get; private set; } = string.Empty; + [DataMember] public int? ClientId { get; private set; } + [DataMember] public string SenderName { get; private set; } = string.Empty; + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] public string Subject { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty; + public int Id => throw new NotImplementedException(); public static Message? Create(MessageInfoBindingModel model) { if (model == null) diff --git a/ComputersShop/ComputersShopFileImplement/Models/Order.cs b/ComputersShop/ComputersShopFileImplement/Models/Order.cs index 410edab..791585c 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Order.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Order.cs @@ -5,21 +5,31 @@ using ComputersShopDataModels.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 ComputersShopFileImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int ComputerId { get; private set; } + [DataMember] public int ClientId { get; set; } + [DataMember] public int Count { get; private set; } + [DataMember] public double Sum { get; private set; } + [DataMember] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; private set; } public static Order? Create(OrderBindingModel? model) diff --git a/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj b/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj index b4bbe77..79fdee4 100644 --- a/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj +++ b/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj @@ -9,5 +9,9 @@ + + + + diff --git a/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs b/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..b0ef815 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,22 @@ +using ComputersShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopListImplement.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/ComputersShop/ComputersShopListImplement/ListImplementationExtension.cs b/ComputersShop/ComputersShopListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..1dee32d --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/ListImplementationExtension.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopListImplement +{ + public class ListImplementationExtension : IImplementationExtension + { + public int Priority => 0; + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/ComputersShop/ComputersShopListImplement/Models/Message.cs b/ComputersShop/ComputersShopListImplement/Models/Message.cs index 3b579ae..41ddb94 100644 --- a/ComputersShop/ComputersShopListImplement/Models/Message.cs +++ b/ComputersShop/ComputersShopListImplement/Models/Message.cs @@ -22,7 +22,7 @@ namespace ComputersShopListImplement.Models public string Subject { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty; - + public int Id => throw new NotImplementedException(); public static Message? Create(MessageInfoBindingModel model) { if (model == null) diff --git a/ComputersShop/ComputersShopView/DataGridViewExtension.cs b/ComputersShop/ComputersShopView/DataGridViewExtension.cs new file mode 100644 index 0000000..361184a --- /dev/null +++ b/ComputersShop/ComputersShopView/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopView +{ + public static class DataGridViewExtension + { + public static void FillandConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + // ищем нужный нам атрибут + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = + (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode) + , columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +} diff --git a/ComputersShop/ComputersShopView/FormClients.cs b/ComputersShop/ComputersShopView/FormClients.cs index 80db11e..0bb9dcc 100644 --- a/ComputersShop/ComputersShopView/FormClients.cs +++ b/ComputersShop/ComputersShopView/FormClients.cs @@ -35,13 +35,7 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) diff --git a/ComputersShop/ComputersShopView/FormComponents.cs b/ComputersShop/ComputersShopView/FormComponents.cs index dddb46c..627786d 100644 --- a/ComputersShop/ComputersShopView/FormComponents.cs +++ b/ComputersShop/ComputersShopView/FormComponents.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ComputersShopContracts.DI; namespace ComputersShopView { @@ -33,13 +34,7 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) @@ -51,8 +46,7 @@ namespace ComputersShopView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponent)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComponent form) { if (form.ShowDialog() == DialogResult.OK) @@ -65,16 +59,11 @@ namespace ComputersShopView { if (dataGridView.SelectedRows.Count == 1) { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/ComputersShop/ComputersShopView/FormComputer.cs b/ComputersShop/ComputersShopView/FormComputer.cs index dcea46d..9e6b846 100644 --- a/ComputersShop/ComputersShopView/FormComputer.cs +++ b/ComputersShop/ComputersShopView/FormComputer.cs @@ -1,6 +1,7 @@ using ComputersShop; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using ComputersShopContracts.SearchModels; using ComputersShopDataModels.Models; using Microsoft.Extensions.Logging; @@ -23,6 +24,7 @@ namespace ComputersShopView private int? _id; private Dictionary _computerComponents; public int Id { set { _id = value; } } + public FormComputer(ILogger logger, IComputerLogic logic) { InitializeComponent(); @@ -30,30 +32,29 @@ namespace ComputersShopView _logic = logic; _computerComponents = new Dictionary(); } + private void FormComputer_Load(object sender, EventArgs e) { if (_id.HasValue) { - _logger.LogInformation("Загрузка изделия"); + _logger.LogInformation("Загрузка компьютера"); try { var view = _logic.ReadElement(new ComputerSearchModel { - Id = - _id.Value + Id = _id.Value }); if (view != null) { textBoxName.Text = view.ComputerName; textBoxPrice.Text = view.Price.ToString(); - _computerComponents = view.ComputerComponents ?? new - Dictionary(); + _computerComponents = view.ComputerComponents ?? new Dictionary(); LoadData(); } } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки изделия"); + _logger.LogError(ex, "Ошибка загрузки компьютера"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -61,7 +62,7 @@ namespace ComputersShopView } private void LoadData() { - _logger.LogInformation("Загрузка компонент изделия"); + _logger.LogInformation("Загрузка компонента компьютера"); try { if (_computerComponents != null) @@ -69,23 +70,20 @@ namespace ComputersShopView dataGridView.Rows.Clear(); foreach (var pc in _computerComponents) { - dataGridView.Rows.Add(new object[] { pc.Key, -pc.Value.Item1.ComponentName, pc.Value.Item2 }); + dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 }); } textBoxPrice.Text = CalcPrice().ToString(); } } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонент изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка загрузки компонента компьютера"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormComputerComponent)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComputerComponent form) { if (form.ShowDialog() == DialogResult.OK) @@ -94,8 +92,7 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); { return; } - _logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", - form.ComponentModel.ComponentName, form.Count); + _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); if (_computerComponents.ContainsKey(form.Id)) { _computerComponents[form.Id] = (form.ComponentModel, @@ -114,12 +111,10 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); { if (dataGridView.SelectedRows.Count == 1) { - var service = - Program.ServiceProvider?.GetService(typeof(FormComputerComponent)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComputerComponent form) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Id = id; form.Count = _computerComponents[id].Item2; if (form.ShowDialog() == DialogResult.OK) @@ -128,14 +123,14 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); { return; } - _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", - form.ComponentModel.ComponentName, form.Count); + _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); _computerComponents[form.Id] = (form.ComponentModel, form.Count); LoadData(); } } } } + private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -145,44 +140,41 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); { try { - _logger.LogInformation("Удаление компонента:{ ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); - + _logger.LogInformation("Удаление компонента: { ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); _computerComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } LoadData(); } } } + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxName.Text)) { - MessageBox.Show("Заполните название", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrEmpty(textBoxPrice.Text)) { - MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (_computerComponents == null || _computerComponents.Count == 0) { - MessageBox.Show("Заполните компоненты", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - _logger.LogInformation("Сохранение изделия"); + _logger.LogInformation("Сохранение компьютера"); try { var model = new ComputerBindingModel @@ -192,29 +184,28 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); Price = Convert.ToDouble(textBoxPrice.Text), ComputerComponents = _computerComponents }; - var operationResult = _id.HasValue ? _logic.Update(model) : - _logic.Create(model); + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", - MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка сохранения изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка сохранения компьютера"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } + private double CalcPrice() { double price = 0; @@ -224,5 +215,6 @@ pc.Value.Item1.ComponentName, pc.Value.Item2 }); } return Math.Round(price * 1.1, 2); } + } } diff --git a/ComputersShop/ComputersShopView/FormComputers.cs b/ComputersShop/ComputersShopView/FormComputers.cs index 45a2234..ffab6ef 100644 --- a/ComputersShop/ComputersShopView/FormComputers.cs +++ b/ComputersShop/ComputersShopView/FormComputers.cs @@ -1,6 +1,7 @@ using ComputersShop; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -18,6 +19,7 @@ namespace ComputersShopView { private readonly ILogger _logger; private readonly IComputerLogic _logic; + public FormComputers(ILogger logger, IComputerLogic logic) { InitializeComponent(); @@ -34,26 +36,19 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComputerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ComputerComponents"].Visible = false; - } - _logger.LogInformation("Загрузка изделия"); + dataGridView.FillandConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка компьютеров"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки изделия"); + _logger.LogError(ex, "Ошибка загрузки компьютеров"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputer)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComputer form) { if (form.ShowDialog() == DialogResult.OK) @@ -63,14 +58,13 @@ namespace ComputersShopView } } - private void ButtonUpdate_Click(object sender, EventArgs e) + private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputer)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComputer form) { - var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); if (form.ShowDialog() == DialogResult.OK) { @@ -80,14 +74,14 @@ namespace ComputersShopView } } - private void ButtonDelete_Click(object sender, EventArgs e) + private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление изделия"); + _logger.LogInformation("Удаление компьютера"); try { if (!_logic.Delete(new ComputerBindingModel @@ -101,7 +95,7 @@ namespace ComputersShopView } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления изделия"); + _logger.LogError(ex, "Ошибка удаления компьютера"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -111,7 +105,6 @@ namespace ComputersShopView private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); - } } } diff --git a/ComputersShop/ComputersShopView/FormMails.cs b/ComputersShop/ComputersShopView/FormMails.cs index 927b4d1..e33bd75 100644 --- a/ComputersShop/ComputersShopView/FormMails.cs +++ b/ComputersShop/ComputersShopView/FormMails.cs @@ -28,14 +28,7 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка писем"); } catch (Exception ex) diff --git a/ComputersShop/ComputersShopView/FormMain.cs b/ComputersShop/ComputersShopView/FormMain.cs index 26f5003..9b0accc 100644 --- a/ComputersShop/ComputersShopView/FormMain.cs +++ b/ComputersShop/ComputersShopView/FormMain.cs @@ -1,6 +1,7 @@ using ComputersShop; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using ComputersShopDataModels.Enums; using Microsoft.Extensions.Logging; using System; @@ -20,30 +21,29 @@ namespace ComputersShopView private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + private readonly IWorkProcess _workProcess; + private readonly IBackUpLogic _backUpLogic; + + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportlogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; - _reportLogic = reportLogic; + _reportLogic = reportlogic; + _workProcess = workProcess; + _backUpLogic = backUpLogic; } + private void FormMain_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { + _logger.LogInformation("Загрузка заказов"); try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ComputerId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ComputerName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -52,17 +52,17 @@ namespace ComputersShopView MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComponents form) { form.ShowDialog(); } } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + private void ComputersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputers)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComputers form) { form.ShowDialog(); @@ -70,7 +70,7 @@ namespace ComputersShopView } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + var service = DependencyManager.Instance.Resolve(); if (service is FormCreateOrder form) { form.ShowDialog(); @@ -82,12 +82,17 @@ namespace ComputersShopView if (dataGridView.SelectedRows.Count == 1) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ No{id}. Меняется статус на 'В работе'", id); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); try { var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { - Id = id + Id = id, + ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()) }); if (!operationResult) { @@ -107,12 +112,17 @@ namespace ComputersShopView if (dataGridView.SelectedRows.Count == 1) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ No{id}. Меняется статус на 'Готов'", id); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); try { var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { - Id = id + Id = id, + ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()) }); if (!operationResult) { @@ -132,18 +142,24 @@ namespace ComputersShopView if (dataGridView.SelectedRows.Count == 1) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ No{id}. Меняется статус на 'Выдан'", id); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); try { var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { - Id = id + Id = id, + ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value), + ImplementerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ImplementerId"].Value), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()) }); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); } - _logger.LogInformation("Заказ No{id} выдан", id); + _logger.LogInformation("Заказ №{id} выдан", id); LoadData(); } catch (Exception ex) @@ -153,11 +169,8 @@ namespace ComputersShopView } } } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void списокИзделийToolStripMenuItem_Click(object sender, EventArgs e) + + private void ComponentsDocxToolStripMenuItem_Click(object sender, EventArgs e) { using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; if (dialog.ShowDialog() == DialogResult.OK) @@ -167,30 +180,89 @@ namespace ComputersShopView } } - private void компонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) + private void ComputerComponentsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportComputerComponents)); + var service = DependencyManager.Instance.Resolve(); if (service is FormReportComputerComponents form) { form.ShowDialog(); } } - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + var service = DependencyManager.Instance.Resolve(); if (service is FormReportOrders form) { form.ShowDialog(); } } - private void clientsToolStripMenuItem_Click(object sender, EventArgs e) + + private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + var service = DependencyManager.Instance.Resolve(); if (service is FormClients form) { form.ShowDialog(); } } + + private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = DependencyManager.Instance.Resolve(); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + + private void DoWorkToolStripMenuItem_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 = DependencyManager.Instance.Resolve(); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void CreateBackupToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + MessageBox.Show("Бекап создан", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + + } } } diff --git a/ComputersShop/ComputersShopView/Program.cs b/ComputersShop/ComputersShopView/Program.cs index 67276f9..33c953e 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -14,14 +14,13 @@ using ComputersShopContracts.BindingModels; using ComputersShopBusinessLogic.BusinessLogics; using ComputersShopContracts.BusinessLogicContracts; using ComputersShopDataBaseImplement.Implements; +using ComputersShopContracts.DI; namespace ComputersShop { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -31,12 +30,10 @@ namespace ComputersShop // 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(); + InitDependency(); try { - var mailSender = _serviceProvider.GetService(); + var mailSender = DependencyManager.Instance.Resolve(); mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, @@ -51,46 +48,46 @@ namespace ComputersShop } catch (Exception ex) { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, "<22><> <20><> <20> <20><>"); + var logger = DependencyManager.Instance.Resolve(); + logger?.LogError(ex, "Error"); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); + 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 From ac7e0012600796e4880111d88a33687c05f953f2 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 12:36:02 +0400 Subject: [PATCH 4/4] 8 --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index ca1c7a3..911d658 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,9 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll +*.dll + # Mono auto generated files mono_crash.* -- 2.25.1