diff --git a/.gitignore b/.gitignore index ca1c7a3..3a45d0e 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,4 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +/ComputersShop/ImplementationExtensions diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/BackUpLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..e1659cc --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,99 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.StoragesContracts; +using ComputersShopDataModels; +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 ComputersShopBusinessLogic.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(BackUpSaveBindingModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + _logger.LogDebug("Delete archive"); + string fileName = $"{model.FolderName}.zip"; + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + _logger.LogDebug("Find {count} types", types.Length); + foreach (var type in types) + { + if (type.IsInterface && type.GetInterface(typeIId.Name) != null) + { + var modelType = _backUpInfo.GetTypeByModelInterface(type.Name); + if (modelType == null) + { + throw new InvalidOperationException($"Не найден класс-модель для {type.Name}"); + } + _logger.LogDebug("Call SaveToFile method for {name} type", type.Name); + // вызываем метод на выполнение + method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName }); + } + } + _logger.LogDebug("Create zip and remove folder"); + // архивируем + ZipFile.CreateFromDirectory(model.FolderName, fileName); + // удаляем папку + dirInfo.Delete(true); + } + catch (Exception) + { + throw; + } + } + private void SaveToFile(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + return; + } + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate); + jsonFormatter.WriteObject(fs, records); + } + } +} diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs index 568118f..e02e660 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -23,6 +23,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics private readonly AbstractMailWorker _mailWorker; static readonly object locker = new(); + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs index 36fcf6d..0e4d351 100644 --- a/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -19,6 +19,7 @@ namespace ComputersShopBusinessLogic.MailWorker protected string _popHost = string.Empty; protected int _popPort; private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; private readonly ILogger _logger; public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) { @@ -75,6 +76,7 @@ namespace ComputersShopBusinessLogic.MailWorker _logger.LogDebug("Check Mail: {Count} new mails", list.Count); foreach (var mail in list) { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; _messageInfoLogic.Create(mail); } } diff --git a/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs b/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..07d5361 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,20 @@ +namespace ComputersShopContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public string Title { get; private set; } + public bool Visible { get; private set; } + public int Width { get; private set; } + public GridViewAutoSize GridViewAutoSize { get; private set; } + public bool IsUseAutoSize { get; private set; } + public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + } +} diff --git a/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs b/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..17bd463 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,21 @@ +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..c3d58f1 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/BackUpSaveBindingModel.cs @@ -0,0 +1,7 @@ +namespace ComputersShopContracts.BindingModels +{ + public class BackUpSaveBindingModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs index 37eb64c..ab2cbe9 100644 --- a/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs +++ b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -9,6 +9,7 @@ namespace ComputersShopContracts.BindingModels { public class MessageInfoBindingModel : IMessageInfoModel { + public int Id => throw new NotImplementedException(); public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } public string SenderName { get; set; } = string.Empty; diff --git a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..13b8857 --- /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(BackUpSaveBindingModel model); + } +} diff --git a/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj b/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj index 7ff5503..6aba12b 100644 --- a/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj +++ b/ComputersShop/ComputersShopContracts/ComputersShopContracts.csproj @@ -13,6 +13,8 @@ + + diff --git a/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs b/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..dc6c99f --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/DependencyManager.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.Logging; + +namespace ComputersShopContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _lockObject = new(); + + private DependencyManager() + { + _dependencyManager = new UnityDependencyContainer(); + } + + public static DependencyManager Instance { get { if (_manager == null) { lock (_lockObject) { _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..eb1851f --- /dev/null +++ b/ComputersShop/ComputersShopContracts/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 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..8c84aa7 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +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..e20fd65 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/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 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..5ea7686 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,55 @@ +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 + { + /// + /// Загрузка всех классов-реализаций 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/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs b/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..d66beae --- /dev/null +++ b/ComputersShop/ComputersShopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,38 @@ +using Microsoft.Extensions.Logging; +using Unity.Microsoft.Logging; +using Unity; + + +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 U : class, T where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + + public T Resolve() + { + return _container.Resolve(); + } + } +} diff --git a/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..4340ec2 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,8 @@ +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 27ea807..1cab0a6 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,12 +11,16 @@ namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs index dc4627a..29e1955 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ComponentViewModel.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using ComputersShopDataModels.Models; +using ComputersShopContracts.Attributes; using System.ComponentModel; @@ -11,10 +12,13 @@ namespace ComputersShopContracts.ViewModels { public class ComponentViewModel : IComponentModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название компонента")] + + [Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] + + [Column(title: "Цена", width: 150)] public double Cost { get; set; } } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs index b75fe37..c6a5df5 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ComputerViewModel.cs @@ -4,20 +4,27 @@ using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using ComputersShopContracts.Attributes; using ComputersShopDataModels.Models; namespace ComputersShopContracts.ViewModels { public class ComputerViewModel : IComputerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название компьютера")] + [Column(title: "Название компьютера", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComputerName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Price { get; set; } - public Dictionary ComputerComponents { get; set; } = new(); + [Column(visible: false)] + public Dictionary ComputerComponents + { + get; + set; + } = new(); } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ImplementerViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ImplementerViewModel.cs index 030ad35..9cbac18 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/ImplementerViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/ImplementerViewModel.cs @@ -4,24 +4,26 @@ using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using ComputersShopContracts.Attributes; using ComputersShopDataModels.Models; namespace ComputersShopContracts.ViewModels { public class ImplementerViewModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 100)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] + [Column(title: "Стаж работы", width: 100)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column(title: "Квалификация", width: 100)] public int Qualification { get; set; } } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs index cf1de86..3d182b6 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,6 @@ -using System; +using ComputersShopContracts.Attributes; +using ComputersShopDataModels.Models; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; @@ -9,19 +11,25 @@ namespace ComputersShopContracts.ViewModels { public class MessageInfoViewModel { + [Column(visible: false)] + public int Id { get; set; } + + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; + + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] + [Column(title: "Отправитель", width: 150)] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата письма")] + [Column(title: "Дата письма", width: 120)] public DateTime DateDelivery { get; set; } - [DisplayName("Заголовок")] + [Column(title: "Дата письма", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Body { get; set; } = string.Empty; } } diff --git a/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs index b823472..a98a07a 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,39 +12,43 @@ namespace ComputersShopContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(title: "Номер", width: 100)] public int Id { get; set; } + [Column(visible: false)] public int ComputerId { get; set; } - [DisplayName("Компьютер")] + [Column(title: "Компьютеры", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComputerName { get; set; } = string.Empty; + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", 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; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + [Column(title: "Количество", width: 100)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 120)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 100)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 120)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 120)] public DateTime? DateImplement { get; set; } } -} \ No newline at end of file +} diff --git a/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs index aa325ce..bed34e1 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; } int? ClientId { get; } diff --git a/ComputersShop/ComputersShopDatabaseImplement/ComputerShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplement/ComputerShopDatabase.cs index 7d7d0dc..3e6d6a7 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputerShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputerShopDatabase.cs @@ -15,7 +15,7 @@ namespace ComputersShopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-1DE5E8N\SQLEXPRESS;Initial Catalog=ComputersShopDatabaseNew; + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-1DE5E8N\SQLEXPRESS;Initial Catalog=ComputersShopDatabaseNew8; Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); diff --git a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj index dec845d..03560bc 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabaseImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs b/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..7815e03 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,22 @@ +using ComputersShopContracts.DI; +using ComputersShopContracts.StoragesContracts; +using ComputersShopDatabaseImplement.Implements; + +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..b3a4097 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,33 @@ +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/Migrations/20240518091255_InitialCreate.Designer.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240519154028_InitialCreate.Designer.cs similarity index 99% rename from ComputersShop/ComputersShopDatabaseImplement/Migrations/20240518091255_InitialCreate.Designer.cs rename to ComputersShop/ComputersShopDatabaseImplement/Migrations/20240519154028_InitialCreate.Designer.cs index a999074..3e4f5fd 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240518091255_InitialCreate.Designer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240519154028_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ComputersShopDatabaseImplement.Migrations { [DbContext(typeof(ComputersShopDatabase))] - [Migration("20240518091255_InitialCreate")] + [Migration("20240519154028_InitialCreate")] partial class InitialCreate { /// diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240518091255_InitialCreate.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240519154028_InitialCreate.cs similarity index 100% rename from ComputersShop/ComputersShopDatabaseImplement/Migrations/20240518091255_InitialCreate.cs rename to ComputersShop/ComputersShopDatabaseImplement/Migrations/20240519154028_InitialCreate.cs diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs index c50ff57..22edb71 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs @@ -8,28 +8,28 @@ using System.Threading.Tasks; using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Models; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } - + [DataMember] [Required] public string ClientFIO { get; private set; } = string.Empty; - + [DataMember] [Required] public string Email { get; private set; } = string.Empty; - + [DataMember] [Required] public string Password { get; private set; } = string.Empty; - [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - [ForeignKey("ClientId")] public virtual List ClientMessages { get; set; } = new(); - public static Client? Create(ClientBindingModel model) { if (model == null) @@ -44,7 +44,6 @@ namespace ComputersShopDatabaseImplement.Models Password = model.Password }; } - public void Update(ClientBindingModel model) { if (model == null) @@ -55,7 +54,6 @@ namespace ComputersShopDatabaseImplement.Models Email = model.Email; Password = model.Password; } - public ClientViewModel GetViewModel => new() { Id = Id, @@ -64,4 +62,4 @@ namespace ComputersShopDatabaseImplement.Models Password = Password }; } -} \ No newline at end of file +} diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs index 0f7d27c..b9432f9 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Component.cs @@ -8,14 +8,19 @@ using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + [DataMember] [Required] public string ComponentName { get; private set; } = string.Empty; + [DataMember] [Required] public double Cost { get; set; } [ForeignKey("ComponentId")] @@ -30,7 +35,7 @@ namespace ComputersShopDatabaseImplement.Models { Id = model.Id, ComponentName = model.ComponentName, - Cost = model.Cost, + Cost = model.Cost }; } public static Component Create(ComponentViewModel model) @@ -59,3 +64,4 @@ namespace ComputersShopDatabaseImplement.Models }; } } + diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs index b6410ad..bab17a8 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs @@ -8,17 +8,27 @@ using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Computer : IComputerModel { + [DataMember] public int Id { get; set; } + + [DataMember] [Required] public string ComputerName { get; set; } = string.Empty; + + [DataMember] [Required] public double Price { get; set; } + private Dictionary? _computerComponents = null; + + [DataMember] [NotMapped] public Dictionary ComputerComponents { @@ -26,16 +36,19 @@ namespace ComputersShopDatabaseImplement.Models { if (_computerComponents == null) { - _computerComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => - (recPC.Component as IComponentModel, recPC.Count)); + _computerComponents = Components + .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _computerComponents; } } + [ForeignKey("ComputerId")] public virtual List Components { get; set; } = new(); + [ForeignKey("ComputerId")] public virtual List Orders { get; set; } = new(); + public static Computer Create(ComputersShopDatabase context, ComputerBindingModel model) { return new Computer() @@ -50,11 +63,13 @@ namespace ComputersShopDatabaseImplement.Models }).ToList() }; } + public void Update(ComputerBindingModel model) { ComputerName = model.ComputerName; Price = model.Price; } + public ComputerViewModel GetViewModel => new() { Id = Id, @@ -62,11 +77,12 @@ namespace ComputersShopDatabaseImplement.Models Price = Price, ComputerComponents = ComputerComponents }; + public void UpdateComponents(ComputersShopDatabase context, ComputerBindingModel model) { var computerComponents = context.ComputerComponents.Where(rec => rec.ComputerId == model.Id).ToList(); if (computerComponents != null && computerComponents.Count > 0) - { // удалили те, которых нет в модели + { // удалили те, которых нет в модели context.ComputerComponents.RemoveRange(computerComponents.Where(rec => !model.ComputerComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей @@ -78,13 +94,13 @@ namespace ComputersShopDatabaseImplement.Models context.SaveChanges(); } var computer = context.Computers.First(x => x.Id == Id); - foreach (var pc in model.ComputerComponents) + foreach (var ic in model.ComputerComponents) { context.ComputerComponents.Add(new ComputerComponent { Computer = computer, - Component = context.Components.First(x => x.Id == pc.Key), - Count = pc.Value.Item2 + Component = context.Components.First(x => x.Id == ic.Key), + Count = ic.Value.Item2 }); context.SaveChanges(); } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Implementer.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Implementer.cs index 740d726..582b49b 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Implementer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Implementer.cs @@ -8,28 +8,29 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using ComputersShopDataModels.Models; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } - + [DataMember] [Required] public string ImplementerFIO { get; set; } = string.Empty; - + [DataMember] [Required] public string Password { get; set; } = string.Empty; - + [DataMember] [Required] public int WorkExperience { get; set; } - + [DataMember] [Required] public int Qualification { get; set; } - [ForeignKey("ImplementerId")] public virtual List Orders { get; set; } = new(); - public static Implementer? Create(ImplementerBindingModel model) { if (model == null) @@ -45,7 +46,6 @@ namespace ComputersShopDatabaseImplement.Models Qualification = model.Qualification }; } - public static Implementer Create(ImplementerViewModel model) { return new Implementer @@ -57,7 +57,6 @@ namespace ComputersShopDatabaseImplement.Models Qualification = model.Qualification }; } - public void Update(ImplementerBindingModel model) { if (model == null) @@ -69,7 +68,6 @@ namespace ComputersShopDatabaseImplement.Models WorkExperience = model.WorkExperience; Qualification = model.Qualification; } - public ImplementerViewModel GetViewModel => new() { Id = Id, @@ -80,3 +78,4 @@ namespace ComputersShopDatabaseImplement.Models }; } } + diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs index 1349d0b..a2dcc14 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs @@ -8,31 +8,35 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ComputersShopDatabaseImplement.Models { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { + [NotMapped] + public int Id { get; private set; } + [DataMember] [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string MessageId { get; set; } = string.Empty; - + [DataMember] public int? ClientId { get; set; } - + [DataMember] [Required] public string SenderName { get; set; } = string.Empty; - + [DataMember] [Required] public DateTime DateDelivery { get; set; } + [DataMember] [Required] public string Subject { get; set; } = string.Empty; - + [DataMember] [Required] public string Body { get; set; } = string.Empty; - public virtual Client? Client { get; set; } - public static MessageInfo? Create(MessageInfoBindingModel? model) { if (model == null) @@ -49,7 +53,6 @@ namespace ComputersShopDatabaseImplement.Models Body = model.Body }; } - public MessageInfoViewModel GetViewModel => new() { MessageId = MessageId, diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs index efa255f..d9ade76 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs @@ -2,38 +2,50 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Enums; +using ComputersShopDataModels.Models; namespace ComputersShopDatabaseImplement.Models { - public class Order + [DataContract] + public class Order : IOrderModel { + [DataMember] public int Id { get; set; } + [DataMember] [Required] public int ComputerId { get; set; } + [DataMember] [Required] public int ClientId { get; set; } + [DataMember] public int? ImplementerId { get; private set; } + [DataMember] [Required] public int Count { get; set; } + [DataMember] [Required] public double Sum { get; set; } + [DataMember] [Required] public OrderStatus Status { get; set; } + [DataMember] [Required] public DateTime DateCreate { get; set; } + [DataMember] public DateTime? DateImplement { get; set; } public virtual Computer Computer { get; set; } diff --git a/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj b/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj index 8eb14fb..fa6e324 100644 --- a/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj +++ b/ComputersShop/ComputersShopFileImplement/ComputersShopFileImplement.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs b/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..62a4623 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/FileImplementationExtension.cs @@ -0,0 +1,22 @@ +using ComputersShopContracts.DI; +using ComputersShopContracts.StoragesContracts; +using ComputersShopFileImplement.Implements; + +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..fb07eff --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,36 @@ +using ComputersShopContracts.StoragesContracts; +using System.Reflection; + +namespace ComputersShopFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + private readonly DataFileSingleton source; + + public BackUpInfo() + { + source = DataFileSingleton.GetInstance(); + } + + public List? GetList() where T : class, new() + { + 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 b06e3f0..334c12b 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Client.cs @@ -1,19 +1,26 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; namespace ComputersShopFileImplement.Models { - public class Client + [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) { @@ -21,12 +28,12 @@ namespace ComputersShopFileImplement.Models { return null; } - return new Client() + return new() { Id = model.Id, ClientFIO = model.ClientFIO, Email = model.Email, - Password = model.Password, + Password = model.Password }; } public static Client? Create(XElement element) @@ -35,12 +42,12 @@ namespace ComputersShopFileImplement.Models { return null; } - return new Client() + return new() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ClientFIO = element.Element("ClientFIO")!.Value, + ClientFIO = element.Element("FIO")!.Value, Email = element.Element("Email")!.Value, - Password = element.Element("Password")!.Value, + Password = element.Element("Password")!.Value }; } public void Update(ClientBindingModel model) @@ -62,7 +69,7 @@ namespace ComputersShopFileImplement.Models }; public XElement GetXElement => new("Client", new XAttribute("Id", Id), - new XElement("ClientFIO", ClientFIO), + new XElement("FIO", ClientFIO), new XElement("Email", Email), new XElement("Password", Password) ); diff --git a/ComputersShop/ComputersShopFileImplement/Models/Component.cs b/ComputersShop/ComputersShopFileImplement/Models/Component.cs index 52a5e3c..0594305 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Component.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Component.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Models; +using System.Runtime.Serialization; 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) { @@ -58,8 +58,8 @@ namespace ComputersShopFileImplement.Models Cost = Cost }; public XElement GetXElement => new("Component", - new XAttribute("Id", Id), - new XElement("ComponentName", ComponentName), - new XElement("Cost", Cost.ToString())); + new XAttribute("Id", Id), + new XElement("ComponentName", ComponentName), + new XElement("Cost", Cost.ToString())); } } diff --git a/ComputersShop/ComputersShopFileImplement/Models/Computer.cs b/ComputersShop/ComputersShopFileImplement/Models/Computer.cs index afaa4d9..a1321c9 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Computer.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Computer.cs @@ -7,16 +7,27 @@ using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; 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; + + [DataMember] public Dictionary ComputerComponents { get @@ -24,14 +35,14 @@ namespace ComputersShopFileImplement.Models if (_computerComponents == null) { var source = DataFileSingleton.GetInstance(); - _computerComponents = Components.ToDictionary(x => x.Key, y => - ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, - y.Value)); + _computerComponents = Components.ToDictionary(x => x.Key, + y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _computerComponents; } } - public static Computer? Create(ComputerBindingModel model) + + public static Computer? Create(ComputerBindingModel? model) { if (model == null) { @@ -45,6 +56,7 @@ namespace ComputersShopFileImplement.Models Components = model.ComputerComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } + public static Computer? Create(XElement element) { if (element == null) @@ -56,14 +68,12 @@ namespace ComputersShopFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), ComputerName = element.Element("ComputerName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), - Components = - element.Element("ComputerComponents")!.Elements("ComputerComponent") - .ToDictionary(x => - Convert.ToInt32(x.Element("Key")?.Value), x => - Convert.ToInt32(x.Element("Value")?.Value)) + Components = element.Element("ComputerComponents")!.Elements("ComputerComponent") + .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } - public void Update(ComputerBindingModel model) + + public void Update(ComputerBindingModel? model) { if (model == null) { @@ -74,6 +84,7 @@ namespace ComputersShopFileImplement.Models Components = model.ComputerComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _computerComponents = null; } + public ComputerViewModel GetViewModel => new() { Id = Id, @@ -81,13 +92,14 @@ namespace ComputersShopFileImplement.Models Price = Price, ComputerComponents = ComputerComponents }; + public XElement GetXElement => new("Computer", - new XAttribute("Id", Id), - new XElement("ComputerName", ComputerName), - new XElement("Price", Price.ToString()), - new XElement("ComputerComponents", Components.Select(x => - new XElement("ComputerComponent", new XElement("Key", x.Key), - new XElement("Value", x.Value))).ToArray())); + new XAttribute("Id", Id), + new XElement("ComputerName", ComputerName), + new XElement("Price", Price.ToString()), + new XElement("ComputerComponents", Components.Select(x => new XElement("ComputerComponent", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray())); } } diff --git a/ComputersShop/ComputersShopFileImplement/Models/Implementer.cs b/ComputersShop/ComputersShopFileImplement/Models/Implementer.cs index 8ae5a5c..5bcff0c 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Implementer.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Implementer.cs @@ -4,18 +4,25 @@ 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 Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } + [DataMember] public string ImplementerFIO { get; set; } = string.Empty; + [DataMember] public string Password { get; set; } = string.Empty; + [DataMember] public int WorkExperience { get; set; } + [DataMember] public int Qualification { get; set; } public static Implementer? Create(ImplementerBindingModel? model) { diff --git a/ComputersShop/ComputersShopFileImplement/Models/MessageInfo.cs b/ComputersShop/ComputersShopFileImplement/Models/MessageInfo.cs index 8bd1a73..6053b4c 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/MessageInfo.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/MessageInfo.cs @@ -4,26 +4,29 @@ 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 { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { + public int Id { get; private set; } + [DataMember] public string MessageId { get; private set; } = string.Empty; - + [DataMember] public int? ClientId { get; private set; } - + [DataMember] public string SenderName { get; private set; } = string.Empty; - + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; - + [DataMember] public string Subject { get; private set; } = string.Empty; - + [DataMember] public string Body { get; private set; } = string.Empty; - public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) @@ -40,7 +43,6 @@ namespace ComputersShopFileImplement.Models Body = model.Body }; } - public static MessageInfo? Create(XElement element) { if (element == null) @@ -57,7 +59,6 @@ namespace ComputersShopFileImplement.Models Body = element.Element("Body")!.Value }; } - public MessageInfoViewModel GetViewModel => new() { MessageId = MessageId, @@ -67,7 +68,6 @@ namespace ComputersShopFileImplement.Models Subject = Subject, Body = Body }; - public XElement GetXElement => new("MessageInfo", new XAttribute("MessageId", MessageId), new XElement("ClientId", ClientId), diff --git a/ComputersShop/ComputersShopFileImplement/Models/Order.cs b/ComputersShop/ComputersShopFileImplement/Models/Order.cs index bc9e5b0..467d08d 100644 --- a/ComputersShop/ComputersShopFileImplement/Models/Order.cs +++ b/ComputersShop/ComputersShopFileImplement/Models/Order.cs @@ -8,19 +8,30 @@ using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Enums; using ComputersShopDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; 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; private set; } + [DataMember] public int? ImplementerId { get; private set; } + [DataMember] public int Count { get; private set; } + [DataMember] public double Sum { get; private set; } + [DataMember] public OrderStatus Status { get; private set; } + [DataMember] public DateTime DateCreate { get; private set; } + [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 31f657b..15b5926 100644 --- a/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj +++ b/ComputersShop/ComputersShopListImplement/ComputersShopListImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs b/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..43935c2 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,21 @@ +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..e31eb38 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/ListImplementationExtension.cs @@ -0,0 +1,27 @@ +using ComputersShopContracts.DI; +using ComputersShopContracts.StoragesContracts; +using ComputersShopListImplement.Implements; +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/MessageInfo.cs b/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs index b5e97e7..4471687 100644 --- a/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs +++ b/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs @@ -11,6 +11,7 @@ namespace ComputersShopListImplement.Models { public class MessageInfo : IMessageInfoModel { + public int Id => throw new NotImplementedException(); public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } public string SenderName { get; private set; } = string.Empty; diff --git a/ComputersShop/ComputersShopView/DataGridViewExtension.cs b/ComputersShop/ComputersShopView/DataGridViewExtension.cs new file mode 100644 index 0000000..dfda2ed --- /dev/null +++ b/ComputersShop/ComputersShopView/DataGridViewExtension.cs @@ -0,0 +1,45 @@ +using ComputersShopContracts.Attributes; + +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 1d6e510..046ba27 100644 --- a/ComputersShop/ComputersShopView/FormClients.cs +++ b/ComputersShop/ComputersShopView/FormClients.cs @@ -17,31 +17,28 @@ namespace ComputersShopView public partial class FormClients : Form { private readonly ILogger _logger; - private readonly IClientLogic _clientLogic; - public FormClients(ILogger logger, IClientLogic clientLogic) + private readonly IClientLogic _logic; + public FormClients(ILogger logger, IClientLogic logic) { InitializeComponent(); _logger = logger; - _clientLogic = clientLogic; + _logic = logic; + LoadData(); + } + private void FormClients_Load(object sender, EventArgs e) + { LoadData(); } private void LoadData() { try { - var list = _clientLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Password"].Visible = false; - } - _logger.LogInformation("Load clients"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Clients loading"); } catch (Exception ex) { - _logger.LogError(ex, "Load clients error"); + _logger.LogError(ex, "Clients loading error"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -53,16 +50,13 @@ namespace ComputersShopView { if (dataGridView.SelectedRows.Count == 1) { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show("Удалить клиента?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Delete client"); + _logger.LogInformation("Deletion of client"); try { - if (!_clientLogic.Delete(new ClientBindingModel - { - Id = id - })) + if (!_logic.Delete(new ClientBindingModel { Id = id })) { throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); } @@ -70,7 +64,7 @@ namespace ComputersShopView } catch (Exception ex) { - _logger.LogError(ex, "Delete client error"); + _logger.LogError(ex, "Client deletion error"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/ComputersShop/ComputersShopView/FormComponents.cs b/ComputersShop/ComputersShopView/FormComponents.cs index 5dd3e12..99daf46 100644 --- a/ComputersShop/ComputersShopView/FormComponents.cs +++ b/ComputersShop/ComputersShopView/FormComponents.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using Microsoft.Extensions.Logging; @@ -18,8 +19,7 @@ namespace ComputersShopView { private readonly ILogger _logger; private readonly IComponentLogic _logic; - public FormComponents(ILogger logger, IComponentLogic -logic) + public FormComponents(ILogger logger, IComponentLogic logic) { InitializeComponent(); _logger = logger; @@ -33,49 +33,32 @@ logic) { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка компонентов"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Components loading"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + _logger.LogError(ex, "Components loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 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(); - } + 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(); - } + LoadData(); } } } @@ -83,18 +66,13 @@ logic) { if (dataGridView.SelectedRows.Count == 1) { - if (MessageBox.Show("Удалить запись?", "Вопрос", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление компонента"); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Deletion of component"); try { - if (!_logic.Delete(new ComponentBindingModel - { - Id = id - })) + if (!_logic.Delete(new ComponentBindingModel { Id = id })) { throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); } @@ -102,9 +80,8 @@ logic) } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Component deletion error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ComputersShop/ComputersShopView/FormComputer.cs b/ComputersShop/ComputersShopView/FormComputer.cs index eec94a6..7bcd1d6 100644 --- a/ComputersShop/ComputersShopView/FormComputer.cs +++ b/ComputersShop/ComputersShopView/FormComputer.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using ComputersShopContracts.SearchModels; using ComputersShopDataModels.Models; using Microsoft.Extensions.Logging; @@ -83,53 +84,42 @@ namespace ComputersShopView } 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) { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - if (_computerComponents.ContainsKey(form.Id)) - { - _computerComponents[form.Id] = (form.ComponentModel, - form.Count); - } - else - { - _computerComponents.Add(form.Id, (form.ComponentModel, - form.Count)); - } - LoadData(); + return; } + _logger.LogInformation("Adding new component: {ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count); + if (_computerComponents.ContainsKey(form.Id)) + { + _computerComponents[form.Id] = (form.ComponentModel, form.Count); + } + else + { + _computerComponents.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 = _computerComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _computerComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) + if (form.ComponentModel == null) { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _computerComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); + return; } + _logger.LogInformation("Component editing: {ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count); + _computerComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); } } } diff --git a/ComputersShop/ComputersShopView/FormComputers.cs b/ComputersShop/ComputersShopView/FormComputers.cs index 835777d..ce5ec37 100644 --- a/ComputersShop/ComputersShopView/FormComputers.cs +++ b/ComputersShop/ComputersShopView/FormComputers.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using Microsoft.Extensions.Logging; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; namespace ComputersShopView { @@ -33,32 +34,22 @@ 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; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Computers loading"); } catch (Exception ex) { - _logger.LogError(ex, "Computers loading error"); + _logger.LogError(ex, "Ice creams loading error"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 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(); - } + LoadData(); } } @@ -66,14 +57,11 @@ namespace ComputersShopView { 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(); - } + LoadData(); } } } diff --git a/ComputersShop/ComputersShopView/FormImplementers.cs b/ComputersShop/ComputersShopView/FormImplementers.cs index 4ee1647..57e328a 100644 --- a/ComputersShop/ComputersShopView/FormImplementers.cs +++ b/ComputersShop/ComputersShopView/FormImplementers.cs @@ -1,5 +1,6 @@ using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -33,16 +34,7 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Password"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["WorkExperience"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Qualification"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Implementers loading"); } catch (Exception ex) @@ -54,32 +46,24 @@ namespace ComputersShopView private void ButtonAdd_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) { + LoadData(); + } + } + private void ButtonEdit_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); if (form.ShowDialog() == DialogResult.OK) { LoadData(); } } } - - private void ButtonEdit_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } - private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/ComputersShop/ComputersShopView/FormMails.cs b/ComputersShop/ComputersShopView/FormMails.cs index e546ce7..8e1acf3 100644 --- a/ComputersShop/ComputersShopView/FormMails.cs +++ b/ComputersShop/ComputersShopView/FormMails.cs @@ -30,14 +30,7 @@ namespace ComputersShopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Messages loading"); } catch (Exception ex) diff --git a/ComputersShop/ComputersShopView/FormMain.Designer.cs b/ComputersShop/ComputersShopView/FormMain.Designer.cs index 2001a0a..8caa0dc 100644 --- a/ComputersShop/ComputersShopView/FormMain.Designer.cs +++ b/ComputersShop/ComputersShopView/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(); @@ -55,7 +56,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(1147, 28); @@ -139,6 +141,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(65, 24); + this.почтаToolStripMenuItem.Text = "Почта"; + this.почтаToolStripMenuItem.Click += new System.EventHandler(this.ПочтаToolStripMenuItem_Click); + // // dataGridView // this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) @@ -183,12 +192,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(65, 24); - this.почтаToolStripMenuItem.Text = "Почта"; - this.почтаToolStripMenuItem.Click += new System.EventHandler(this.ПочтаToolStripMenuItem_Click); + this.создатьБэкапToolStripMenuItem.Name = "создатьБэкапToolStripMenuItem"; + this.создатьБэкапToolStripMenuItem.Size = new System.Drawing.Size(122, 24); + this.создатьБэкапToolStripMenuItem.Text = "Создать бэкап"; + this.создатьБэкапToolStripMenuItem.Click += new System.EventHandler(this.СоздатьБэкапToolStripMenuItem_Click); // // FormMain // @@ -230,5 +239,6 @@ private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem почтаToolStripMenuItem; + private ToolStripMenuItem создатьБэкапToolStripMenuItem; } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopView/FormMain.cs b/ComputersShop/ComputersShopView/FormMain.cs index f72a866..0522709 100644 --- a/ComputersShop/ComputersShopView/FormMain.cs +++ b/ComputersShop/ComputersShopView/FormMain.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using ComputersShopBusinessLogic.BusinessLogics; using ComputersShopContracts.BindingModels; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.DI; using Microsoft.Extensions.Logging; namespace ComputersShopView @@ -20,7 +21,8 @@ namespace ComputersShopView 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; @@ -28,6 +30,7 @@ namespace ComputersShopView _reportLogic = reportLogic; _reportLogic = reportLogic; _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) { @@ -37,52 +40,31 @@ namespace ComputersShopView { try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ComputerId"].Visible = false; - dataGridView.Columns["ComputerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientEmail"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка заказов"); + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); + _logger.LogInformation("Orders loading"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки заказов"); + _logger.LogError(ex, "Orders loading error"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 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 ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private void ButtonIssuedOrder_Click(object sender, EventArgs e) { @@ -131,51 +113,59 @@ namespace ComputersShopView private void компонентыПоКомпьютерамToolStripMenuItem_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 списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) { - form.ShowDialog(); + _reportLogic.SaveComputersToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } + 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); - MessageBox.Show("Процесс обработки запущен", "Сообщение", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _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(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } 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 BackUpSaveBindingModel + { + 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 2c90e09..34e90ec 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -2,21 +2,17 @@ using ComputersShopBusinessLogic.BusinessLogics; using ComputersShopBusinessLogic.OfficePackage.Implements; using ComputersShopBusinessLogic.OfficePackage; using ComputersShopContracts.BusinessLogicsContracts; -using ComputersShopContracts.StoragesContracts; -using ComputersShopDatabaseImplement.Implements; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; -using System; using ComputersShopBusinessLogic.MailWorker; using ComputersShopContracts.BindingModels; +using ComputersShopContracts.DI; +using ComputersShopView; -namespace ComputersShopView +namespace ComputerShopView { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -26,12 +22,10 @@ namespace ComputersShopView // 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, @@ -46,56 +40,52 @@ namespace ComputersShopView } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); logger?.LogError(ex, "Mails Problem"); } - 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(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddSingleton(); - - 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.AddTransient(); - services.AddTransient(); + 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) => ServiceProvider?.GetService()?.MailCheck(); + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file