diff --git a/SushiBar/SushiBarBusinessLogic/BackUpLogic.cs b/SushiBar/SushiBarBusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..d820434 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic/BackUpLogic.cs @@ -0,0 +1,103 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.StoragesContracts; +using SushiBarDataModels; +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 SushiBarBusinessLogic +{ + 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/SushiBar/SushiBarContracts/Attributes/ColumnAttribute.cs b/SushiBar/SushiBarContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..6f9c44b --- /dev/null +++ b/SushiBar/SushiBarContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,25 @@ +namespace SushiBarContracts.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; + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/Attributes/GridViewAutoSize.cs b/SushiBar/SushiBarContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..796e101 --- /dev/null +++ b/SushiBar/SushiBarContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/SushiBar/SushiBarContracts/BindingModels/BackUpSaveBinidngModel.cs b/SushiBar/SushiBarContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..7b93ace --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs index b377905..1f1f4ce 100644 --- a/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs +++ b/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs @@ -15,5 +15,6 @@ namespace SushiBarContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } + public int Id => throw new NotImplementedException(); } } diff --git a/SushiBar/SushiBarContracts/BusinessLogicsContracts/IBackUpLogic.cs b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..b988a62 --- /dev/null +++ b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using SushiBarContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/DI/DependencyManager.cs b/SushiBar/SushiBarContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..0c76057 --- /dev/null +++ b/SushiBar/SushiBarContracts/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 SushiBarContracts.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(); + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/DI/IDependencyContainer.cs b/SushiBar/SushiBarContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..37cbf0b --- /dev/null +++ b/SushiBar/SushiBarContracts/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 SushiBarContracts.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/SushiBar/SushiBarContracts/DI/IImplementationExtension.cs b/SushiBar/SushiBarContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..6e9a8b1 --- /dev/null +++ b/SushiBar/SushiBarContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/DI/ServiceDependencyContainer.cs b/SushiBar/SushiBarContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..65b3e4a --- /dev/null +++ b/SushiBar/SushiBarContracts/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 SushiBarContracts.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/SushiBar/SushiBarContracts/DI/ServiceProviderLoader.cs b/SushiBar/SushiBarContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..c049275 --- /dev/null +++ b/SushiBar/SushiBarContracts/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 SushiBarContracts.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/SushiBar/SushiBarContracts/StoragesContracts/IBackUpInfo.cs b/SushiBar/SushiBarContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..d51e70a --- /dev/null +++ b/SushiBar/SushiBarContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/ViewModels/ClientViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ClientViewModel.cs index 2b6bbaf..8e1896c 100644 --- a/SushiBar/SushiBarContracts/ViewModels/ClientViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/ClientViewModel.cs @@ -6,17 +6,20 @@ using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using SushiBarContracts.Attributes; +using SushiBarDataModels.Models; namespace SushiBarContracts.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/SushiBar/SushiBarContracts/ViewModels/ComponentViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ComponentViewModel.cs index 3d112ef..3abbbc7 100644 --- a/SushiBar/SushiBarContracts/ViewModels/ComponentViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/ComponentViewModel.cs @@ -1,4 +1,5 @@ -using SushiBarDataModels.Models; +using SushiBarContracts.Attributes; +using SushiBarDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,10 +11,13 @@ namespace SushiBarContracts.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/SushiBar/SushiBarContracts/ViewModels/ImplementerViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ImplementerViewModel.cs index 271bfbb..313922c 100644 --- a/SushiBar/SushiBarContracts/ViewModels/ImplementerViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using SushiBarDataModels; +using SushiBarContracts.Attributes; +using SushiBarDataModels; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,20 +9,23 @@ using System.Threading.Tasks; namespace SushiBarContracts.ViewModels { - public class ImplementerViewModel : IImplementerModel - { - public int Id { get; set; } + public class ImplementerViewModel : IImplementerModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 100)] - [DisplayName("Стаж работы")] - public int WorkExperience { get; set; } + public string Password { get; set; } = string.Empty; - [DisplayName("Квалификация")] - public int Qualification { get; set; } - } + [Column(title: "Стаж работы", width: 60)] + public int WorkExperience { get; set; } + + [Column(title: "Квалификация", width: 60)] + public int Qualification { get; set; } + } } + diff --git a/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs index e58287f..864b52e 100644 --- a/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using SushiBarDataModels.Models; +using SushiBarContracts.Attributes; +using SushiBarDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace SushiBarContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { + [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: 120)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Body { get; set; } = string.Empty; } -} \ No newline at end of file +} diff --git a/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs index 45bddb6..caaf8eb 100644 --- a/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using SushiBarDataModels.Enums; +using SushiBarContracts.Attributes; +using SushiBarDataModels.Enums; using SushiBarDataModels.Models; using System; using System.Collections.Generic; @@ -9,36 +10,46 @@ using System.Threading.Tasks; namespace SushiBarContracts.ViewModels { - public class OrderViewModel : IOrderModel - { - [DisplayName("Номер")] - public int Id { get; set; } - public int? ImplementerId { get; set; } - [DisplayName("Исполнитель")] - public string? ImplementerFIO { get; set; } = null; - public int SushiId { get; set; } - public int ClientId { get; set; } + public class OrderViewModel : IOrderModel + { + [Column(title: "Номер", width: 90)] + public int Id { get; set; } + + [Column(visible: false)] + public int ClientId { get; set; } + + [Column(title: "Имя клиента", width: 190)] + public string ClientFIO { get; set; } = string.Empty; + + [Column(visible: false)] public string ClientEmail { get; set; } = string.Empty; - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] + public int? ImplementerId { get; set; } - [DisplayName("Изделие")] - public string SushiName { get; set; } = string.Empty; + [Column(title: "Исполнитель", width: 150)] + public string? ImplementerFIO { get; set; } = null; - [DisplayName("Количество")] - public int Count { get; set; } + [Column(visible: false)] + public int SushiId { get; set; } - [DisplayName("Сумма")] - public double Sum { get; set; } + [Column(title: "Суши", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string SushiName { get; set; } = string.Empty; - [DisplayName("Статус")] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [Column(title: "Количество", width: 100)] + public int Count { get; set; } - [DisplayName("Дата создания")] - public DateTime DateCreate { get; set; } = DateTime.Now; + [Column(title: "Сумма", width: 120)] + public double Sum { get; set; } - [DisplayName("Дата выполнения")] - public DateTime? DateImplement { get; set; } - } + [Column(title: "Статус", width: 70)] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + + [Column(title: "Дата создания", width: 120)] + public DateTime DateCreate { get; set; } = DateTime.Now; + + [Column(title: "Дата выполнения", width: 120)] + public DateTime? DateImplement { get; set; } + } } + diff --git a/SushiBar/SushiBarContracts/ViewModels/SushiViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/SushiViewModel.cs index 9beb5ef..5346691 100644 --- a/SushiBar/SushiBarContracts/ViewModels/SushiViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/SushiViewModel.cs @@ -1,4 +1,5 @@ -using SushiBarDataModels.Models; +using SushiBarContracts.Attributes; +using SushiBarDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,15 +11,19 @@ namespace SushiBarContracts.ViewModels { public class SushiViewModel : ISushiModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название суши")] + [Column(title: "Название сущи", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string SushiName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 70)] public double Price { get; set; } + [Column(visible: false)] public Dictionary SushiComponents { get; set; } = new(); + } } + diff --git a/SushiBar/SushiBarDataModels/IMessageInfoModel.cs b/SushiBar/SushiBarDataModels/IMessageInfoModel.cs index e4c9086..8242afa 100644 --- a/SushiBar/SushiBarDataModels/IMessageInfoModel.cs +++ b/SushiBar/SushiBarDataModels/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace SushiBarDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } int? ClientId { get; } diff --git a/SushiBar/SushiBarDatabaseImplement/BackUpInfo.cs b/SushiBar/SushiBarDatabaseImplement/BackUpInfo.cs new file mode 100644 index 0000000..4687db9 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/BackUpInfo.cs @@ -0,0 +1,32 @@ +using SushiBarContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new SushiBarDatabase(); + 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/SushiBar/SushiBarDatabaseImplement/Client.cs b/SushiBar/SushiBarDatabaseImplement/Client.cs index b965618..7a7f4e0 100644 --- a/SushiBar/SushiBarDatabaseImplement/Client.cs +++ b/SushiBar/SushiBarDatabaseImplement/Client.cs @@ -1,76 +1,84 @@ using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; -using SushiBarDatabaseImplement.Models; using SushiBarDataModels.Models; -using System.ComponentModel.DataAnnotations.Schema; -using System.ComponentModel.DataAnnotations; using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -namespace SushiBarDatabaseImplement +namespace SushiBarDatabaseImplement.Models { - public class Client : IClientModel - { - public int Id { get; private set; } + [DataContract] + public class Client : IClientModel + { + [DataMember] + public int Id { get; private set; } - [Required] - public string ClientFIO { get; set; } = string.Empty; - [Required] - public string Email { get; set; } = string.Empty; - [Required] - public string Password { get; set; } = string.Empty; + [DataMember] + [Required] + public string ClientFIO { get; set; } = string.Empty; - [ForeignKey("ClientId")] + [DataMember] + [Required] + public string Email { get; set; } = string.Empty; + + [DataMember] + [Required] + public string Password { get; set; } = string.Empty; + + [ForeignKey("ClientId")] public virtual List ClientOrders { get; set; } = new(); [ForeignKey("ClientId")] public virtual List ClientMessages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { - if (model == null) - { - return null; - } - return new Client() - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Email = model.Email, - Password = model.Password - }; - } + if (model == null) + { + return null; + } + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password + }; + } - public static Client Create(ClientViewModel model) - { - return new Client - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Email = model.Email, - Password = model.Password - }; - } + public static Client Create(ClientViewModel model) + { + return new Client + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password + }; + } - public void Update(ClientBindingModel model) - { - if (model == null) - { - return; - } - ClientFIO = model.ClientFIO; - Email = model.Email; - Password = model.Password; - } + public void Update(ClientBindingModel model) + { + if (model == null) + { + return; + } + ClientFIO = model.ClientFIO; + Email = model.Email; + Password = model.Password; + } - public ClientViewModel GetViewModel => new() - { - Id = Id, - ClientFIO = ClientFIO, - Email = Email, - Password = Password - }; - } + public ClientViewModel GetViewModel => new() + { + Id = Id, + ClientFIO = ClientFIO, + Email = Email, + Password = Password + }; + } } diff --git a/SushiBar/SushiBarDatabaseImplement/Component.cs b/SushiBar/SushiBarDatabaseImplement/Component.cs index d555489..4e2a8d9 100644 --- a/SushiBar/SushiBarDatabaseImplement/Component.cs +++ b/SushiBar/SushiBarDatabaseImplement/Component.cs @@ -1,19 +1,31 @@ -using SushiBarContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; using SushiBarDataModels.Models; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; + namespace SushiBarDatabaseImplement.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")] public virtual List SushiComponents { get; set; } = new(); + public static Component? Create(ComponentBindingModel model) { if (model == null) @@ -27,6 +39,7 @@ namespace SushiBarDatabaseImplement.Models Cost = model.Cost }; } + public static Component Create(ComponentViewModel model) { return new Component @@ -36,6 +49,7 @@ namespace SushiBarDatabaseImplement.Models Cost = model.Cost }; } + public void Update(ComponentBindingModel model) { if (model == null) @@ -45,6 +59,7 @@ namespace SushiBarDatabaseImplement.Models ComponentName = model.ComponentName; Cost = model.Cost; } + public ComponentViewModel GetViewModel => new() { Id = Id, @@ -52,4 +67,4 @@ namespace SushiBarDatabaseImplement.Models Cost = Cost }; } -} \ No newline at end of file +} diff --git a/SushiBar/SushiBarDatabaseImplement/ImplementationExtension.cs b/SushiBar/SushiBarDatabaseImplement/ImplementationExtension.cs new file mode 100644 index 0000000..ca818f5 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/ImplementationExtension.cs @@ -0,0 +1,28 @@ +using SushiBar.StoragesContracts; +using SushiBarContracts.DI; +using SushiBarContracts.StoragesContracts; +using SushiBarDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDatabaseImplement +{ + public class ImplementationExtension : IImplementationExtension + { + public int Priority => 3; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarDatabaseImplement/Implementer.cs b/SushiBar/SushiBarDatabaseImplement/Implementer.cs index fc8c4ab..144538d 100644 --- a/SushiBar/SushiBarDatabaseImplement/Implementer.cs +++ b/SushiBar/SushiBarDatabaseImplement/Implementer.cs @@ -1,72 +1,73 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using SushiBarContracts.BindingModels; -using SushiBarContracts.SearchModels; -using SushiBarContracts.ViewModels; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; -using SushiBarDataModels; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarContracts.BindingModels; using SushiBarDatabaseImplement.Models; +using SushiBarContracts.ViewModels; +using System.Runtime.Serialization; -namespace SushiBarDatabaseImplement +namespace SushiBarDataModels.Models { - public class Implementer : IImplementerModel - { - public int Id { get; set; } + [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; } - [Required] - public string ImplementerFIO { get; set; } = string.Empty; + [ForeignKey("ImplementerId")] + public virtual List Order { get; set; } = new(); - [Required] - public string Password { get; set; } = string.Empty; + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification + }; + } - [Required] - public int WorkExperience { get; set; } + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } - [Required] - public int Qualification { get; set; } - - [ForeignKey("ImplementerId")] - public virtual List Order { get; set; } = new(); - - public static Implementer? Create(ImplementerBindingModel? model) - { - if (model == null) - { - return null; - } - return new Implementer() - { - Id = model.Id, - ImplementerFIO = model.ImplementerFIO, - Password = model.Password, - WorkExperience = model.WorkExperience, - Qualification = model.Qualification - }; - } - - public void Update(ImplementerBindingModel model) - { - if (model == null) - { - return; - } - ImplementerFIO = model.ImplementerFIO; - Password = model.Password; - WorkExperience = model.WorkExperience; - Qualification = model.Qualification; - } - - public ImplementerViewModel GetViewModel => new() - { - Id = Id, - ImplementerFIO = ImplementerFIO, - Password = Password, - WorkExperience = WorkExperience, - Qualification = Qualification - }; - } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + } } diff --git a/SushiBar/SushiBarDatabaseImplement/MessageInfo.cs b/SushiBar/SushiBarDatabaseImplement/MessageInfo.cs index d54e628..d655ce6 100644 --- a/SushiBar/SushiBarDatabaseImplement/MessageInfo.cs +++ b/SushiBar/SushiBarDatabaseImplement/MessageInfo.cs @@ -8,28 +8,38 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace SushiBarDatabaseImplement.Models { public class MessageInfo : IMessageInfoModel { + [NotMapped] + public int Id { get; private set; } + + [DataMember] [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string MessageId { get; set; } = string.Empty; + [DataMember] public int? ClientId { get; set; } public virtual Client? Client { get; set; } + [DataMember] [Required] public string SenderName { get; set; } = string.Empty; + [DataMember] [Required] public DateTime DateDelivery { get; set; } + [DataMember] [Required] public string Subject { get; set; } = string.Empty; + [DataMember] [Required] public string Body { get; set; } = string.Empty; @@ -61,4 +71,4 @@ namespace SushiBarDatabaseImplement.Models Body = Body }; } -} \ No newline at end of file +} diff --git a/SushiBar/SushiBarDatabaseImplement/Order.cs b/SushiBar/SushiBarDatabaseImplement/Order.cs index ff9c52b..50c4747 100644 --- a/SushiBar/SushiBarDatabaseImplement/Order.cs +++ b/SushiBar/SushiBarDatabaseImplement/Order.cs @@ -2,85 +2,100 @@ using SushiBarContracts.ViewModels; using SushiBarDataModels.Enums; using SushiBarDataModels.Models; +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 SushiBarDatabaseImplement.Models { - public class Order : IOrderModel - { - public int Id { get; private set; } + [DataContract] + public class Order : IOrderModel + { + [DataMember] + public int Id { get; private set; } + [DataMember] + [Required] + public int ClientId { get; private set; } + public virtual Client Client { get; private set; } = new(); + [DataMember] + [Required] + public int SushiId { get; private set; } - [Required] - public int ClientId { get; private set; } - public virtual Client Client { get; private set; } = new(); - [Required] - public int SushiId { get; private set; } + public virtual Sushi Sushi { get; set; } = new(); - public virtual Sushi Sushi { get; set; } = new(); + [DataMember] + [Required] + public int Count { get; private set; } - [Required] - public int Count { get; private set; } + [DataMember] + [Required] + public double Sum { get; private set; } - [Required] - public double Sum { get; private set; } + [DataMember] + [Required] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] + [Required] + public DateTime DateCreate { get; private set; } = DateTime.Now; - [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] + public DateTime? DateImplement { get; private set; } + [DataMember] + public int? ImplementerId { get; private set; } - public DateTime? DateImplement { get; private set; } - public int? ImplementerId { get; private set; } + public virtual Implementer? Implementer { get; set; } = new(); - public virtual Implementer? Implementer { get; set; } = new(); + public static Order Create(SushiBarDatabase context, OrderBindingModel model) + { + return new Order() + { + Id = model.Id, + ClientId = model.ClientId, + Client = context.Clients.First(x => x.Id == model.ClientId), + SushiId = model.SushiId, + Sushi = context.Sushis.First(x => x.Id == model.SushiId), + ImplementerId = model.ImplementerId, + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement, + }; + } - public static Order Create(SushiBarDatabase context, OrderBindingModel model) - { - return new Order() - { - Id = model.Id, - ClientId = model.ClientId, - Client = context.Clients.First(x => x.Id == model.ClientId), - SushiId = model.SushiId, - Sushi = context.Sushis.First(x => x.Id == model.SushiId), - ImplementerId = model.ImplementerId, - Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement, - }; - } + public void Update(SushiBarDatabase context, OrderBindingModel? model) + { + if (model == null) + { + return; + } + Status = model.Status; + DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null; + } - public void Update(SushiBarDatabase context, OrderBindingModel? model) - { - if (model == null) - { - return; - } - Status = model.Status; - DateImplement = model.DateImplement; - ImplementerId = model.ImplementerId; - Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null; - } - - public OrderViewModel GetViewModel => new() - { - Id = Id, - ClientId = ClientId, - ClientFIO = Client.ClientFIO, + public OrderViewModel GetViewModel => new() + { + Id = Id, + ClientId = ClientId, + ClientFIO = Client.ClientFIO, ClientEmail = Client.Email, SushiId = SushiId, - SushiName = Sushi.SushiName, - ImplementerId = ImplementerId, - ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement, - }; - } -} \ No newline at end of file + SushiName = Sushi.SushiName, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement, + }; + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Sushi.cs b/SushiBar/SushiBarDatabaseImplement/Sushi.cs index 85050d5..08d35cc 100644 --- a/SushiBar/SushiBarDatabaseImplement/Sushi.cs +++ b/SushiBar/SushiBarDatabaseImplement/Sushi.cs @@ -8,18 +8,26 @@ using System.Text; using System.Threading.Tasks; using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; +using System.Runtime.Serialization; namespace SushiBarDatabaseImplement.Models { + [DataContract] public class Sushi : ISushiModel { + [DataMember] public int Id { get; set; } + [DataMember] [Required] public string SushiName { get; set; } = string.Empty; + [DataMember] [Required] public double Price { get; set; } + + private Dictionary? _sushiComponents = null; + [DataMember] [NotMapped] public Dictionary SushiComponents { @@ -98,4 +106,4 @@ namespace SushiBarDatabaseImplement.Models _sushiComponents = null; } } -} +} diff --git a/SushiBar/SushiBarFileImplement/BackUpInfo.cs b/SushiBar/SushiBarFileImplement/BackUpInfo.cs new file mode 100644 index 0000000..1dd1f55 --- /dev/null +++ b/SushiBar/SushiBarFileImplement/BackUpInfo.cs @@ -0,0 +1,44 @@ +using SushiBarContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + private readonly DataFileSingleton source; + private readonly PropertyInfo[] sourceProperties; + + public BackUpInfo() + { + source = DataFileSingleton.GetInstance(); + sourceProperties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); + } + + public List? GetList() where T : class, new() + { + var requredType = typeof(T); + return (List?)sourceProperties.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == requredType) + ?.GetValue(source); + + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/SushiBar/SushiBarFileImplement/ImplementationExtension.cs b/SushiBar/SushiBarFileImplement/ImplementationExtension.cs new file mode 100644 index 0000000..80a1933 --- /dev/null +++ b/SushiBar/SushiBarFileImplement/ImplementationExtension.cs @@ -0,0 +1,29 @@ +using SushiBar.StoragesContracts; +using SushiBarContracts.DI; +using SushiBarContracts.StoragesContracts; + +using SushiBarFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarFileImplement +{ + public class ImplementationExtension : IImplementationExtension + { + public int Priority => 1; + + public void RegisterServices() + { + //TODO DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/SushiBar/SushiBarFileImplement/MessageInfo.cs b/SushiBar/SushiBarFileImplement/MessageInfo.cs index 811b998..4143ac1 100644 --- a/SushiBar/SushiBarFileImplement/MessageInfo.cs +++ b/SushiBar/SushiBarFileImplement/MessageInfo.cs @@ -76,5 +76,7 @@ namespace SushiBarFileImplement.Models new XAttribute("SenderName", SenderName), new XAttribute("DateDelivery", DateDelivery) ); + + public int Id => throw new NotImplementedException(); } } diff --git a/SushiBar/SushiBarListImplement/MessageInfo.cs b/SushiBar/SushiBarListImplement/MessageInfo.cs index 2c62f6f..d69dede 100644 --- a/SushiBar/SushiBarListImplement/MessageInfo.cs +++ b/SushiBar/SushiBarListImplement/MessageInfo.cs @@ -49,5 +49,7 @@ namespace SushiBarListImplement.Models SenderName = SenderName, DateDelivery = DateDelivery, }; + + public int Id => throw new NotImplementedException(); } } diff --git a/SushiBar/SushiBarView/DataGridViewExtension.cs b/SushiBar/SushiBarView/DataGridViewExtension.cs new file mode 100644 index 0000000..0aeff0d --- /dev/null +++ b/SushiBar/SushiBarView/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarContracts.Attributes; + +namespace SushiBarView +{ + internal static class DataGridViewExtension + { + public static void FillAndConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormClients.cs b/SushiBar/SushiBarView/FormClients.cs index 450573d..3a2a504 100644 --- a/SushiBar/SushiBarView/FormClients.cs +++ b/SushiBar/SushiBarView/FormClients.cs @@ -35,15 +35,9 @@ namespace SushiBarView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка клиентов"); - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка клиентов"); + } catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки клиентов"); diff --git a/SushiBar/SushiBarView/FormComponents.cs b/SushiBar/SushiBarView/FormComponents.cs index 30239fc..fc0d5b8 100644 --- a/SushiBar/SushiBarView/FormComponents.cs +++ b/SushiBar/SushiBarView/FormComponents.cs @@ -10,19 +10,26 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using SushiBarContracts.DI; namespace SushiBarView { public partial class FormComponents : Form { + public FormComponents() + { + InitializeComponent(); + } private readonly ILogger _logger; private readonly IComponentLogic _logic; - public FormComponents(ILogger logger, IComponentLogic logic) + public FormComponents(ILogger logger, IComponentLogic + logic) { InitializeComponent(); _logger = logger; _logic = logic; } + private void FormComponents_Load(object sender, EventArgs e) { LoadData(); @@ -48,32 +55,26 @@ namespace SushiBarView 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(); } } } @@ -82,10 +83,10 @@ namespace SushiBarView if (dataGridView.SelectedRows.Count == 1) { if (MessageBox.Show("Удалить запись?", "Вопрос", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); _logger.LogInformation("Удаление компонента"); try { @@ -102,7 +103,7 @@ namespace SushiBarView { _logger.LogError(ex, "Ошибка удаления компонента"); MessageBox.Show(ex.Message, "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -111,6 +112,6 @@ namespace SushiBarView { LoadData(); } + } } - diff --git a/SushiBar/SushiBarView/FormImplementers.cs b/SushiBar/SushiBarView/FormImplementers.cs index 0a0e121..34a1ef9 100644 --- a/SushiBar/SushiBarView/FormImplementers.cs +++ b/SushiBar/SushiBarView/FormImplementers.cs @@ -1,7 +1,7 @@ using Microsoft.Extensions.Logging; using SushiBarContracts.BindingModels; using SushiBarContracts.BusinessLogicsContracts; -using SushiBarContracts.ViewModels; +using SushiBarContracts.DI; using System; using System.Collections.Generic; using System.ComponentModel; @@ -14,105 +14,98 @@ using System.Windows.Forms; namespace SushiBarView { - public partial class FormImplementers : Form - { - private readonly ILogger _logger; - private readonly IImplementerLogic _logic; + public partial class FormImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; - public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) - { - InitializeComponent(); - _logger = logger; - _logic = implementerLogic; - } + public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) + { + InitializeComponent(); + _logger = logger; + _logic = implementerLogic; + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка исполнителей"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки исполнителей"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } + private void LoadData() + { + try + { + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } - private void FormImplementers_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } - private void buttonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + private void buttonAdd_Click(object sender, EventArgs e) + { + 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(FormImplementer)); - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - 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(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) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление исполнителя"); - try - { - if (!_logic.Delete(new ImplementerBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления исполнителя"); - MessageBox.Show(ex.Message, "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void buttonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление исполнителя"); + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/SushiBar/SushiBarView/FormMail.cs b/SushiBar/SushiBarView/FormMail.cs index 26889be..8bfc676 100644 --- a/SushiBar/SushiBarView/FormMail.cs +++ b/SushiBar/SushiBarView/FormMail.cs @@ -28,15 +28,7 @@ namespace SushiBarView { 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("Загрузка почтовых собщений"); } catch (Exception ex) diff --git a/SushiBar/SushiBarView/FormMain.cs b/SushiBar/SushiBarView/FormMain.cs index e2b4ebf..2b916d6 100644 --- a/SushiBar/SushiBarView/FormMain.cs +++ b/SushiBar/SushiBarView/FormMain.cs @@ -2,6 +2,8 @@ using SushiBarBusinessLogic.BusinessLogics; using SushiBarContracts.BindingModels; using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.DI; +using System.Windows.Forms; using System; using System.Collections.Generic; using System.ComponentModel; @@ -20,13 +22,15 @@ namespace SushiBarView 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) { @@ -37,15 +41,7 @@ namespace SushiBarView _logger.LogInformation("Загрузка заказов"); try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["SushiId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientEmail"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - } + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -56,29 +52,19 @@ namespace SushiBarView } private void componentsToolStripMenuItem_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 sushiToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSushis)); - if (service is FormSushis 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) { @@ -125,21 +111,13 @@ e) private void ComponentSushisToolStripMenuItem_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormReportSushiComponents)); - if (service is FormReportSushiComponents 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 ButtonRef_Click(object sender, EventArgs e) @@ -149,32 +127,48 @@ e) private void clientToolStripMenuItem_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 employersToolStripMenuItem_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 startWorkToolStripMenuItem_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 mailToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMail)); - if (service is FormMail form) + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + + private void createBackUpToolStripMenuItem_Click(object sender, EventArgs e) + { + try { - form.ShowDialog(); + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + MessageBox.Show("Бекап создан", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка создания бэкапа", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } } diff --git a/SushiBar/SushiBarView/FormSushi.cs b/SushiBar/SushiBarView/FormSushi.cs index a0c9da4..d0590c0 100644 --- a/SushiBar/SushiBarView/FormSushi.cs +++ b/SushiBar/SushiBarView/FormSushi.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using SushiBarContracts.DI; namespace SushiBarView { @@ -99,56 +100,44 @@ namespace SushiBarView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormSushiComponent)); - if (service is FormSushiComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() != DialogResult.OK) { + return; + } + _logger.LogInformation("Добавление нового ингридиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + if (_sushiComponents.ContainsKey(form.Id)) + { + _sushiComponents[form.Id] = (form.ComponentModel, + form.Count); + } + else + { + _sushiComponents.Add(form.Id, (form.ComponentModel, + form.Count)); + } + LoadData(); + } + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _sushiComponents[id].Item2; if (form.ShowDialog() == DialogResult.OK) { if (form.ComponentModel == null) { return; } - _logger.LogInformation("Добавление нового компонента: { ComponentName}- { Count}", form.ComponentModel.ComponentName, form.Count); - if (_sushiComponents.ContainsKey(form.Id)) - { - _sushiComponents[form.Id] = (form.ComponentModel, - form.Count); - } - else - { - _sushiComponents.Add(form.Id, (form.ComponentModel, - form.Count)); - } + _logger.LogInformation("Изменение компонента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + _sushiComponents[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(FormSushiComponent)); - if (service is FormSushiComponent form) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _sushiComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _sushiComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); - } - } - } - } private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/SushiBar/SushiBarView/FormSushis.cs b/SushiBar/SushiBarView/FormSushis.cs index 28ed8c3..25fb21b 100644 --- a/SushiBar/SushiBarView/FormSushis.cs +++ b/SushiBar/SushiBarView/FormSushis.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using SushiBarContracts.BindingModels; using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.DI; namespace SushiBarView { @@ -17,13 +18,11 @@ namespace SushiBarView { private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSushi)); - if (service is FormSushi form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); + } } @@ -46,15 +45,7 @@ namespace SushiBarView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["SushiComponents"].Visible = false; - dataGridView.Columns["SushiName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка суши"); } catch (Exception ex) @@ -68,14 +59,11 @@ namespace SushiBarView { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormSushi)); - if (service is FormSushi 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/SushiBar/SushiBarView/Program.cs b/SushiBar/SushiBarView/Program.cs index 674ae43..3314bee 100644 --- a/SushiBar/SushiBarView/Program.cs +++ b/SushiBar/SushiBarView/Program.cs @@ -1,18 +1,18 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SushiBarContracts.BusinessLogicsContracts; -using SushiBarDatabaseImplement.Implements; +using System; using SushiBarBusinessLogic.BusinessLogics; +using SushiBarDatabaseImplement.Implements; using SushiBarContracts.StoragesContracts; +using SushiBarView; using NLog.Extensions.Logging; using SushiBarBusinessLogic.OfficePackage.Implements; using SushiBarBusinessLogic.OfficePackage; -using Microsoft.EntityFrameworkCore.Design; using SushiBarBusinessLogic; -using SushiBarDatabaseImplement; using SushiBarBusinessLogic.MailWorker; using SushiBarContracts.BindingModels; - +using SushiBarContracts.DI; namespace SushiBarView { @@ -27,12 +27,10 @@ namespace SushiBarView static void Main() { 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, @@ -47,57 +45,47 @@ namespace SushiBarView } 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) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + private static void InitDependency() + { + DependencyManager.InitDependency(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddTransient(); - } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + DependencyManager.Instance.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file