diff --git a/.gitignore b/.gitignore index ca1c7a3..d62d4cb 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,9 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll files +*.dll + # Mono auto generated files mono_crash.* diff --git a/AbstractComputerDataModel/Models/IMessageInfoModel.cs b/AbstractComputerDataModel/Models/IMessageInfoModel.cs index cb7fa30..09284c6 100644 --- a/AbstractComputerDataModel/Models/IMessageInfoModel.cs +++ b/AbstractComputerDataModel/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace ComputerShopDataModels.Models { - public class IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } int? ClientId { get; } diff --git a/ComputerShopBusinessLogic/BusinessLogics/BackUpLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..bac9958 --- /dev/null +++ b/ComputerShopBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,100 @@ +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.BusinessLogicsContracts; +using ComputerShopContracts.StoragesContracts; +using ComputerShopDataModels.Models; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopBusinessLogic.BusinessLogics +{ + 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/ComputerShopContracts/Attributes/ColumnAttribute.cs b/ComputerShopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..8833023 --- /dev/null +++ b/ComputerShopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.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/ComputerShopContracts/Attributes/GridViewAutoSize.cs b/ComputerShopContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..8e6f7e5 --- /dev/null +++ b/ComputerShopContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + None = 1, + ColumnHeader = 2, + AllCellsExceptHeader = 4, + AllCells = 6, + DisplayedCellsExceptHeader = 8, + DisplayedCells = 10, + Fill = 16 + } +} diff --git a/ComputerShopContracts/BindingModels/BackUpSaveBindingModel.cs b/ComputerShopContracts/BindingModels/BackUpSaveBindingModel.cs new file mode 100644 index 0000000..6834299 --- /dev/null +++ b/ComputerShopContracts/BindingModels/BackUpSaveBindingModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/ComputerShopContracts/BindingModels/MessageInfoBindingModel.cs b/ComputerShopContracts/BindingModels/MessageInfoBindingModel.cs index 1ef3b29..dde4a18 100644 --- a/ComputerShopContracts/BindingModels/MessageInfoBindingModel.cs +++ b/ComputerShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -20,5 +20,6 @@ namespace ComputerShopContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; + public int Id => throw new NotImplementedException(); } } diff --git a/ComputerShopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/ComputerShopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..66fa5fd --- /dev/null +++ b/ComputerShopContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using ComputerShopContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/ComputerShopContracts/ComputerShopContracts.csproj b/ComputerShopContracts/ComputerShopContracts.csproj index 5d5199e..be2efaa 100644 --- a/ComputerShopContracts/ComputerShopContracts.csproj +++ b/ComputerShopContracts/ComputerShopContracts.csproj @@ -16,6 +16,8 @@ + + diff --git a/ComputerShopContracts/DI/DependencyManager.cs b/ComputerShopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..43abccf --- /dev/null +++ b/ComputerShopContracts/DI/DependencyManager.cs @@ -0,0 +1,66 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.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/ComputerShopContracts/DI/IDependencyContainer.cs b/ComputerShopContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..161e368 --- /dev/null +++ b/ComputerShopContracts/DI/IDependencyContainer.cs @@ -0,0 +1,40 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.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/ComputerShopContracts/DI/IImplementationExtension.cs b/ComputerShopContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..14cb9ee --- /dev/null +++ b/ComputerShopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/ComputerShopContracts/DI/ServiceDependencyContainer.cs b/ComputerShopContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..4faa2c9 --- /dev/null +++ b/ComputerShopContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.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/ComputerShopContracts/DI/ServiceProviderLoader.cs b/ComputerShopContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..4747752 --- /dev/null +++ b/ComputerShopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.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/ComputerShopContracts/DI/UnityDependencyContainer.cs b/ComputerShopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..de20480 --- /dev/null +++ b/ComputerShopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,44 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Unity; +using Unity.Lifetime; +using Unity.Microsoft.Logging; + +namespace ComputerShopContracts.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/ComputerShopContracts/StoragesContracts/IBackUpInfo.cs b/ComputerShopContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..c9fed7e --- /dev/null +++ b/ComputerShopContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/ComputerShopContracts/ViewModels/ClientViewModel.cs b/ComputerShopContracts/ViewModels/ClientViewModel.cs index 3b26224..953a0c0 100644 --- a/ComputerShopContracts/ViewModels/ClientViewModel.cs +++ b/ComputerShopContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Models; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,12 +11,13 @@ namespace ComputerShopContracts.ViewModels { public class ClientViewModel : IClientModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] + [Column(title: "Логин (эл.почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 150)] public string Password { get; set; } = string.Empty; } } diff --git a/ComputerShopContracts/ViewModels/ComponentViewModel.cs b/ComputerShopContracts/ViewModels/ComponentViewModel.cs index 661912e..200766a 100644 --- a/ComputerShopContracts/ViewModels/ComponentViewModel.cs +++ b/ComputerShopContracts/ViewModels/ComponentViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Models; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,10 +11,11 @@ namespace ComputerShopContracts.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/ComputerShopContracts/ViewModels/ComputerViewModel.cs b/ComputerShopContracts/ViewModels/ComputerViewModel.cs index 8022b33..0f728d0 100644 --- a/ComputerShopContracts/ViewModels/ComputerViewModel.cs +++ b/ComputerShopContracts/ViewModels/ComputerViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Models; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,11 +11,13 @@ namespace ComputerShopContracts.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/ComputerShopContracts/ViewModels/ImplementerViewModel.cs b/ComputerShopContracts/ViewModels/ImplementerViewModel.cs index a7b530e..82bf2d0 100644 --- a/ComputerShopContracts/ViewModels/ImplementerViewModel.cs +++ b/ComputerShopContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Models; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,18 +11,19 @@ namespace ComputerShopContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО")] + [Column("ФИО", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column("Пароль", width: 200)] public string Password { get; set; } = string.Empty; - [DisplayName("Трудовой стаж")] + [Column("Трудовой стаж", width: 200)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column("Квалификация", width: 200)] public int Qualification { get; set; } } } diff --git a/ComputerShopContracts/ViewModels/MessageInfoViewModel.cs b/ComputerShopContracts/ViewModels/MessageInfoViewModel.cs index e242362..5dc40de 100644 --- a/ComputerShopContracts/ViewModels/MessageInfoViewModel.cs +++ b/ComputerShopContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Models; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,16 +11,19 @@ namespace ComputerShopContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; - + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] + [Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата письма")] + [Column("Дата письма", width: 100)] public DateTime DateDelivery { get; set; } - [DisplayName("Заголовок")] + [Column("Заголовок", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Body { get; set; } = string.Empty; + [Column(visible: false)] + public int Id => throw new NotImplementedException(); } } diff --git a/ComputerShopContracts/ViewModels/OrderViewModel.cs b/ComputerShopContracts/ViewModels/OrderViewModel.cs index 5b36388..da1a7c9 100644 --- a/ComputerShopContracts/ViewModels/OrderViewModel.cs +++ b/ComputerShopContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using ComputerShopDataModels.Enums; +using ComputerShopContracts.Attributes; +using ComputerShopDataModels.Enums; using ComputerShopDataModels.Models; using System; using System.Collections.Generic; @@ -11,30 +12,32 @@ namespace ComputerShopContracts.ViewModels { public class OrderViewModel : IOrderModel { + [Column(visible: false)] public int ComputerId { get; set; } - [DisplayName("Номер")] + [Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public int Id { get; set; } - [DisplayName("Компьютер")] + [Column("Компьютер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public string ComputerName { get; set; } = string.Empty; - + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("ФИО клиента")] + [Column("ФИО клиента", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public string ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] public int? ImplementerId { get; set; } - [DisplayName("ФИО исполнителя")] + [Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public string ImplementerFIO { 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/ComputerShopDatabaseImplement/ComputerShopDatabaseImplement.csproj b/ComputerShopDatabaseImplement/ComputerShopDatabaseImplement.csproj index d72067f..a28ee76 100644 --- a/ComputerShopDatabaseImplement/ComputerShopDatabaseImplement.csproj +++ b/ComputerShopDatabaseImplement/ComputerShopDatabaseImplement.csproj @@ -22,4 +22,8 @@ + + + + diff --git a/ComputerShopDatabaseImplement/DatabaseImplementationExtension.cs b/ComputerShopDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..bbb45a1 --- /dev/null +++ b/ComputerShopDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,27 @@ +using ComputerShopContracts.DI; +using ComputerShopContracts.StoragesContracts; +using ComputerShopDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopDatabaseImplement +{ + 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/ComputerShopDatabaseImplement/Implements/BackUpInfo.cs b/ComputerShopDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..9061ccd --- /dev/null +++ b/ComputerShopDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,32 @@ +using ComputerShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new ComputerShopDatabase(); + 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/ComputerShopDatabaseImplement/Models/Client.cs b/ComputerShopDatabaseImplement/Models/Client.cs index 787ed93..c502a87 100644 --- a/ComputerShopDatabaseImplement/Models/Client.cs +++ b/ComputerShopDatabaseImplement/Models/Client.cs @@ -8,20 +8,26 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ComputerShopDatabaseImplement.Models { + [DataContract] internal class Client : IClientModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string ClientFIO { get; private set; } = string.Empty; [Required] + [DataMember] public string Email { get; private set; } = string.Empty; [Required] + [DataMember] public string Password { get; private set; } = string.Empty; [ForeignKey("ClientId")] diff --git a/ComputerShopDatabaseImplement/Models/Component.cs b/ComputerShopDatabaseImplement/Models/Component.cs index 800f9c9..fc8873b 100644 --- a/ComputerShopDatabaseImplement/Models/Component.cs +++ b/ComputerShopDatabaseImplement/Models/Component.cs @@ -8,15 +8,20 @@ using ComputerShopContracts.ViewModels; using ComputerShopDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace ComputerShopDatabaseImplement.Models { + [DataContract] internal 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/ComputerShopDatabaseImplement/Models/Computer.cs b/ComputerShopDatabaseImplement/Models/Computer.cs index 3d4db22..16b2150 100644 --- a/ComputerShopDatabaseImplement/Models/Computer.cs +++ b/ComputerShopDatabaseImplement/Models/Computer.cs @@ -8,19 +8,24 @@ using System.Text; using System.Threading.Tasks; using ComputerShopContracts.BindingModels; using ComputerShopContracts.ViewModels; +using System.Runtime.Serialization; namespace ComputerShopDatabaseImplement.Models { + [DataContract] internal 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; + private Dictionary? _computerComponents = null; [NotMapped] + [DataMember] public Dictionary ComputerComponents { get diff --git a/ComputerShopDatabaseImplement/Models/Implementer.cs b/ComputerShopDatabaseImplement/Models/Implementer.cs index 0f9f47d..fa81976 100644 --- a/ComputerShopDatabaseImplement/Models/Implementer.cs +++ b/ComputerShopDatabaseImplement/Models/Implementer.cs @@ -5,21 +5,28 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ComputerShopDatabaseImplement.Models { + [DataContract] internal class Implementer : IImplementerModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; + [DataMember] public int WorkExperience { get; private set; } + [DataMember] public int Qualification { get; private set; } [ForeignKey("ImplementerId")] diff --git a/ComputerShopDatabaseImplement/Models/MessageInfo.cs b/ComputerShopDatabaseImplement/Models/MessageInfo.cs index ca487ef..e980f7d 100644 --- a/ComputerShopDatabaseImplement/Models/MessageInfo.cs +++ b/ComputerShopDatabaseImplement/Models/MessageInfo.cs @@ -5,28 +5,38 @@ 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 ComputerShopDatabaseImplement.Models { - internal class MessageInfo : IMessageInfoModel + [DataContract] + internal class MessageInfo : IMessageInfoModel { [Key] + [DataMember] public string MessageId { get; private set; } = string.Empty; + [DataMember] public int? ClientId { get; private set; } + [DataMember] public string SenderName { get; private set; } = string.Empty; + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] public string Subject { get; private set; } = string.Empty; + [DataMember] public string Body { get; private set; } = string.Empty; public virtual Client? Client { get; private set; } + public int Id => throw new NotImplementedException(); + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) diff --git a/ComputerShopDatabaseImplement/Models/Order.cs b/ComputerShopDatabaseImplement/Models/Order.cs index f138eba..ca86a17 100644 --- a/ComputerShopDatabaseImplement/Models/Order.cs +++ b/ComputerShopDatabaseImplement/Models/Order.cs @@ -12,27 +12,38 @@ using ComputerShopDataModels.Enums; using System.Reflection.Metadata; using DocumentFormat.OpenXml.InkML; using DocumentFormat.OpenXml.Office2010.Word; +using System.Runtime.Serialization; namespace ComputerShopDatabaseImplement.Models { + [DataContract] internal class Order : IOrderModel { public string ComputerName { get; private set; } = String.Empty; + + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public int ComputerId { get; private set; } [Required] + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } [Required] + [DataMember] public int Count { get; private set; } [Required] + [DataMember] public double Sum { get; private set; } [Required] + [DataMember] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; [Required] + [DataMember] public DateTime DateCreate { get; private set; } = DateTime.Now; - + [DataMember] public DateTime? DateImplement { get; private set; } public virtual Computer Computer { get; set; } diff --git a/ComputerShopFileImplement/ComputerShopFileImplement.csproj b/ComputerShopFileImplement/ComputerShopFileImplement.csproj index 0c3afa8..9cbd755 100644 --- a/ComputerShopFileImplement/ComputerShopFileImplement.csproj +++ b/ComputerShopFileImplement/ComputerShopFileImplement.csproj @@ -21,4 +21,8 @@ + + + + diff --git a/ComputerShopFileImplement/FileImplementationExtension.cs b/ComputerShopFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..18dab84 --- /dev/null +++ b/ComputerShopFileImplement/FileImplementationExtension.cs @@ -0,0 +1,27 @@ +using ComputerShopContracts.DI; +using ComputerShopContracts.StoragesContracts; +using ComputerShopFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopFileImplement +{ + 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/ComputerShopFileImplement/Implements/BackUpInfo.cs b/ComputerShopFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..8352a1e --- /dev/null +++ b/ComputerShopFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,33 @@ +using ComputerShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + var source = DataFileSingleton.GetInstance(); + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/ComputerShopFileImplement/Implements/ClientStorage.cs b/ComputerShopFileImplement/Implements/ClientStorage.cs new file mode 100644 index 0000000..10d14a8 --- /dev/null +++ b/ComputerShopFileImplement/Implements/ClientStorage.cs @@ -0,0 +1,87 @@ +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.SearchModels; +using ComputerShopContracts.StoragesContracts; +using ComputerShopContracts.ViewModels; +using ComputerShopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopFileImplement.Implements +{ + public class ClientStorage : IClientStorage + { + private readonly DataFileSingleton source; + public ClientStorage() + { + source = DataFileSingleton.GetInstance(); + } + + public ClientViewModel? GetElement(ClientSearchModel model) + { + if (string.IsNullOrEmpty(model.Email) && !model.Id.HasValue) + { + return null; + } + return source.Clients + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public List GetFilteredList(ClientSearchModel model) + { + if (string.IsNullOrEmpty(model.Email)) + { + return new(); + } + return source.Clients + .Where(x => x.Email.Contains(model.Email)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return source.Clients.Select(x => x.GetViewModel).ToList(); + } + + public ClientViewModel? Insert(ClientBindingModel model) + { + model.Id = source.Clients.Count > 0 ? source.Clients.Max(x => x.Id) + 1 : 1; + var newClient = Client.Create(model); + if (newClient == null) + { + return null; + } + source.Clients.Add(newClient); + source.SaveClients(); + return newClient.GetViewModel; + } + + public ClientViewModel? Update(ClientBindingModel model) + { + var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + client.Update(model); + source.SaveClients(); + return client?.GetViewModel; + } + + public ClientViewModel? Delete(ClientBindingModel model) + { + var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + source.Clients.Remove(client); + source.SaveClients(); + return client?.GetViewModel; + } + } + +} diff --git a/ComputerShopFileImplement/Models/Client.cs b/ComputerShopFileImplement/Models/Client.cs index 9d6158c..bda1e1b 100644 --- a/ComputerShopFileImplement/Models/Client.cs +++ b/ComputerShopFileImplement/Models/Client.cs @@ -4,20 +4,23 @@ using ComputerShopDataModels.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 ComputerShopFileImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } - + [DataMember] public string ClientFIO { get; private set; } = string.Empty; - + [DataMember] public string Email { get; private set; } = string.Empty; - + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) diff --git a/ComputerShopFileImplement/Models/Component.cs b/ComputerShopFileImplement/Models/Component.cs index 44ca5c8..593614b 100644 --- a/ComputerShopFileImplement/Models/Component.cs +++ b/ComputerShopFileImplement/Models/Component.cs @@ -7,13 +7,18 @@ using ComputerShopContracts.BindingModels; using ComputerShopContracts.ViewModels; using ComputerShopDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace ComputerShopFileImplement.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/ComputerShopFileImplement/Models/Computer.cs b/ComputerShopFileImplement/Models/Computer.cs index d3538e8..a2ec50c 100644 --- a/ComputerShopFileImplement/Models/Computer.cs +++ b/ComputerShopFileImplement/Models/Computer.cs @@ -6,18 +6,24 @@ using System.Threading.Tasks; using ComputerShopContracts.BindingModels; using ComputerShopContracts.ViewModels; using ComputerShopDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace ComputerShopFileImplement.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? _productComponents = null; + [DataMember] public Dictionary ComputerComponents { get diff --git a/ComputerShopFileImplement/Models/Implementer.cs b/ComputerShopFileImplement/Models/Implementer.cs index d8ac2e0..f941b26 100644 --- a/ComputerShopFileImplement/Models/Implementer.cs +++ b/ComputerShopFileImplement/Models/Implementer.cs @@ -4,22 +4,25 @@ using ComputerShopDataModels.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 ComputerShopFileImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; private set; } - + [DataMember] public string ImplementerFIO { get; private set; } = string.Empty; - + [DataMember] public string Password { get; private set; } = string.Empty; - + [DataMember] public int WorkExperience { get; private set; } - + [DataMember] public int Qualification { get; private set; } public static Implementer? Create(XElement element) diff --git a/ComputerShopFileImplement/Models/MessageInfo.cs b/ComputerShopFileImplement/Models/MessageInfo.cs index 3f34a64..63464e6 100644 --- a/ComputerShopFileImplement/Models/MessageInfo.cs +++ b/ComputerShopFileImplement/Models/MessageInfo.cs @@ -4,26 +4,31 @@ using ComputerShopDataModels.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 ComputerShopFileImplement.Models { + [DataContract] public class MessageInfo : 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; - + [DataMember] public string Body { get; private set; } = string.Empty; + public int Id => throw new NotImplementedException(); + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) diff --git a/ComputerShopFileImplement/Models/Order.cs b/ComputerShopFileImplement/Models/Order.cs index 178f919..ee0dc74 100644 --- a/ComputerShopFileImplement/Models/Order.cs +++ b/ComputerShopFileImplement/Models/Order.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; @@ -11,24 +12,28 @@ using ComputerShopDataModels.Models; namespace ComputerShopFileImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int ComputerId { get; private set; } + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } public string ComputerName { get; private set; } = string.Empty; - + [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; } - + [DataMember] public int Id { get; private set; } public static Order? Create(OrderBindingModel? model) diff --git a/ComputerShopListImplement/ComputerShopListImplement.csproj b/ComputerShopListImplement/ComputerShopListImplement.csproj index d72067f..a28ee76 100644 --- a/ComputerShopListImplement/ComputerShopListImplement.csproj +++ b/ComputerShopListImplement/ComputerShopListImplement.csproj @@ -22,4 +22,8 @@ + + + + diff --git a/ComputerShopListImplement/Implements/BackUpInfo.cs b/ComputerShopListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..2e3eeb3 --- /dev/null +++ b/ComputerShopListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,22 @@ +using ComputerShopContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopListImplement.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/ComputerShopListImplement/Models/MessageInfo.cs b/ComputerShopListImplement/Models/MessageInfo.cs index 666b7f3..ba220b9 100644 --- a/ComputerShopListImplement/Models/MessageInfo.cs +++ b/ComputerShopListImplement/Models/MessageInfo.cs @@ -23,6 +23,8 @@ namespace ComputerShopListImplement.Models public string Body { get; private set; } = string.Empty; + public int Id => throw new NotImplementedException(); + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) diff --git a/ComputersShop/DataGridViewExtension.cs b/ComputersShop/DataGridViewExtension.cs new file mode 100644 index 0000000..cf43bf6 --- /dev/null +++ b/ComputersShop/DataGridViewExtension.cs @@ -0,0 +1,50 @@ +using ComputerShopContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShop +{ + 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/FormClients.cs b/ComputersShop/FormClients.cs index 356bba9..6b6c263 100644 --- a/ComputersShop/FormClients.cs +++ b/ComputersShop/FormClients.cs @@ -33,13 +33,7 @@ namespace ComputersShop { 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/FormComponents.cs b/ComputersShop/FormComponents.cs index cbb372e..7f1ccb2 100644 --- a/ComputersShop/FormComponents.cs +++ b/ComputersShop/FormComponents.cs @@ -2,6 +2,7 @@ using ComputerShopContracts.BindingModels; using ComputerShopContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using ComputerShopContracts.DI; namespace ComputersShop { @@ -23,13 +24,7 @@ namespace ComputersShop { 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) @@ -41,28 +36,21 @@ namespace ComputersShop } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - 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) + 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(); - } } } } diff --git a/ComputersShop/FormComputer.cs b/ComputersShop/FormComputer.cs index 775269c..d7334e1 100644 --- a/ComputersShop/FormComputer.cs +++ b/ComputersShop/FormComputer.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using ComputerShopContracts.BindingModels; using ComputerShopContracts.BusinessLogicsContracts; +using ComputerShopContracts.DI; using ComputerShopContracts.SearchModels; using ComputerShopDataModels.Models; using Microsoft.Extensions.Logging; @@ -80,11 +81,9 @@ namespace ComputersShop } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputerComponent)); - if (service is FormComputerComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { if (form.ComponentModel == null) { return; @@ -99,23 +98,19 @@ namespace ComputersShop _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(FormComputerComponent)); - if (service is FormComputerComponent form) + 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) { - 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; @@ -123,7 +118,6 @@ namespace ComputersShop _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); _productComponents[form.Id] = (form.ComponentModel, form.Count); LoadData(); - } } } } diff --git a/ComputersShop/FormComputers.cs b/ComputersShop/FormComputers.cs index e550f0a..f78483c 100644 --- a/ComputersShop/FormComputers.cs +++ b/ComputersShop/FormComputers.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using ComputerShopContracts.DI; namespace ComputersShop { @@ -32,14 +33,7 @@ namespace ComputersShop { 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; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компьютеров"); } catch (Exception ex) @@ -51,13 +45,10 @@ namespace ComputersShop private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputer)); - if (service is FormComputer form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { LoadData(); - } } } @@ -65,14 +56,11 @@ namespace ComputersShop { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputer)); - if (service is FormComputer 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(); - } } } } diff --git a/ComputersShop/FormImplementers.cs b/ComputersShop/FormImplementers.cs index 256852d..b55ded7 100644 --- a/ComputersShop/FormImplementers.cs +++ b/ComputersShop/FormImplementers.cs @@ -1,5 +1,6 @@ using ComputerShopContracts.BindingModels; using ComputerShopContracts.BusinessLogicsContracts; +using ComputerShopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -32,13 +33,7 @@ namespace ComputersShop { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) @@ -51,13 +46,10 @@ namespace ComputersShop private void buttonCreate_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { LoadData(); - } } } @@ -65,14 +57,11 @@ namespace ComputersShop { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer 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(); - } } } } diff --git a/ComputersShop/FormMails.cs b/ComputersShop/FormMails.cs index b768a79..6531282 100644 --- a/ComputersShop/FormMails.cs +++ b/ComputersShop/FormMails.cs @@ -28,14 +28,7 @@ namespace ComputersShop { 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/FormMain.Designer.cs b/ComputersShop/FormMain.Designer.cs index da97691..96c2e0b 100644 --- a/ComputersShop/FormMain.Designer.cs +++ b/ComputersShop/FormMain.Designer.cs @@ -39,11 +39,12 @@ this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.ButtonCreateOrder = new System.Windows.Forms.Button(); this.ButtonIssuedOrder = new System.Windows.Forms.Button(); this.ButtonRef = new System.Windows.Forms.Button(); - this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.создатьБэкапToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -54,7 +55,8 @@ this.справочникиToolStripMenuItem, this.отчетыToolStripMenuItem, this.запускРаботToolStripMenuItem, - this.письмаToolStripMenuItem}); + this.письмаToolStripMenuItem, + this.создатьБэкапToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1006, 24); @@ -138,6 +140,13 @@ this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); // + // письмаToolStripMenuItem + // + this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + this.письмаToolStripMenuItem.Size = new System.Drawing.Size(62, 20); + this.письмаToolStripMenuItem.Text = "Письма"; + this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click); + // // dataGridView // this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; @@ -177,12 +186,12 @@ this.ButtonRef.UseVisualStyleBackColor = true; this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click); // - // письмаToolStripMenuItem + // создатьБэкапToolStripMenuItem // - this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; - this.письмаToolStripMenuItem.Size = new System.Drawing.Size(62, 20); - this.письмаToolStripMenuItem.Text = "Письма"; - this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click); + this.создатьБэкапToolStripMenuItem.Name = "создатьБэкапToolStripMenuItem"; + this.создатьБэкапToolStripMenuItem.Size = new System.Drawing.Size(97, 20); + this.создатьБэкапToolStripMenuItem.Text = "Создать бэкап"; + this.создатьБэкапToolStripMenuItem.Click += new System.EventHandler(this.создатьБэкапToolStripMenuItem_Click); // // FormMain // @@ -224,5 +233,6 @@ private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem письмаToolStripMenuItem; + private ToolStripMenuItem создатьБэкапToolStripMenuItem; } } \ No newline at end of file diff --git a/ComputersShop/FormMain.cs b/ComputersShop/FormMain.cs index 3a8bc9a..a7a4b96 100644 --- a/ComputersShop/FormMain.cs +++ b/ComputersShop/FormMain.cs @@ -1,5 +1,6 @@ using ComputerShopContracts.BindingModels; using ComputerShopContracts.BusinessLogicsContracts; +using ComputerShopContracts.DI; using ComputerShopDataModels.Enums; using Microsoft.Extensions.Logging; using System; @@ -20,14 +21,15 @@ namespace ComputersShop private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + private readonly IBackUpLogic _backUpLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; - + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) @@ -39,14 +41,7 @@ namespace ComputersShop _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["ImplementerId"].Visible = false; - } + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -58,46 +53,30 @@ namespace ComputersShop private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void КомпьютерыToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComputers)); - if (service is FormComputers form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } + 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(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private void ButtonOrderReady_Click(object sender, EventArgs e) @@ -148,34 +127,49 @@ namespace ComputersShop private void ComponentComputersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportComputerComponents)); - if (service is FormReportComputerComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + _workProcess.DoWork(DependencyManager.Instance.Resolve(), _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void письмаToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); - if (service is FormMails form) + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + + private void создатьБэкапToolStripMenuItem_Click(object sender, EventArgs e) + { + try { - form.ShowDialog(); + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + MessageBox.Show("Бекап создан", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ComputersShop/Program.cs b/ComputersShop/Program.cs index e55d673..1134116 100644 --- a/ComputersShop/Program.cs +++ b/ComputersShop/Program.cs @@ -9,13 +9,12 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using ComputerShopBusinessLogic.MailWorker; using ComputerShopContracts.BindingModels; +using ComputerShopContracts.DI; namespace ComputersShop { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -25,12 +24,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, @@ -45,54 +42,51 @@ namespace ComputersShop } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); logger?.LogError(ex, " "); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - 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(isSingle: true); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + 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(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file