diff --git a/.gitignore b/.gitignore index ca1c7a3..6f9ffd4 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,4 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +/Diner/ImplementationExtensions diff --git a/AbstractShopBusinessLogic/BusinessLogics/BackUpLogic.cs b/AbstractShopBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..e3098b6 --- /dev/null +++ b/AbstractShopBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,128 @@ +using DinerContracts.BindingModels; +using DinerContracts.BusinessLogicsContracts; +using DinerContracts.StoragesContracts; +using DinerDataModels; +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 DinerBusinessLogic.BusinessLogics +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + + private readonly IBackUpInfo _backUpInfo; + + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + + public void CreateBackUp(BackUpSaveBinidngModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + + _logger.LogDebug("Delete archive"); + + string fileName = $"{model.FolderName}.zip"; + + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + + _logger.LogDebug("Find {count} types", types.Length); + + foreach (var type in types) + { + //проверка на то, является ли тип интерфейсом и унаследован ли он от IId + 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; + } + + //три строчки ниже - сериализация файлов в json + 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/AbstractShopContracts/Attributes/ColumnAttribute.cs b/AbstractShopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..06b8e2b --- /dev/null +++ b/AbstractShopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public ColumnAttribute(string title = "", bool visible = true, int width = 0, + GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + + public string Title { get; private set; } + + public bool Visible { get; private set; } + + public int Width { get; private set; } + + public GridViewAutoSize GridViewAutoSize { get; private set; } + + public bool IsUseAutoSize { get; private set; } + } +} diff --git a/AbstractShopContracts/Attributes/GridViewAutoSize.cs b/AbstractShopContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..fa81793 --- /dev/null +++ b/AbstractShopContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/AbstractShopContracts/BindingModels/BackUpSaveBinidngModel.cs b/AbstractShopContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..328b219 --- /dev/null +++ b/AbstractShopContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/AbstractShopContracts/BindingModels/MailConfigBindingModel.cs b/AbstractShopContracts/BindingModels/MailConfigBindingModel.cs index 317d6a9..2a1bba0 100644 --- a/AbstractShopContracts/BindingModels/MailConfigBindingModel.cs +++ b/AbstractShopContracts/BindingModels/MailConfigBindingModel.cs @@ -8,6 +8,7 @@ namespace DinerContracts.BindingModels { public class MailConfigBindingModel { + public int Id { get; set; } public string MailLogin { get; set; } = string.Empty; public string MailPassword { get; set; } = string.Empty; diff --git a/AbstractShopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/AbstractShopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..2bcd9fa --- /dev/null +++ b/AbstractShopContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using DinerContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/AbstractShopContracts/DI/DependencyManager.cs b/AbstractShopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..42fa04b --- /dev/null +++ b/AbstractShopContracts/DI/DependencyManager.cs @@ -0,0 +1,63 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.DI +{ + /// + /// Менеджер для работы с зависимостями + /// + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new UnityDependencyContainer(); + } + + public static DependencyManager Instance + { + get + { + if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } + + return _manager; + } + } + + //Иницализация библиотек, в которых идут установки зависомстей + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + + // регистрируем зависимости + ext.RegisterServices(); + } + + //Регистрация логгера + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + //Получение класса со всеми зависмостями + public T Resolve() => _dependencyManager.Resolve(); + } + +} diff --git a/AbstractShopContracts/DI/IDependencyContainer.cs b/AbstractShopContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..8fb3a58 --- /dev/null +++ b/AbstractShopContracts/DI/IDependencyContainer.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.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/AbstractShopContracts/DI/IImplementationExtension.cs b/AbstractShopContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..ea24e61 --- /dev/null +++ b/AbstractShopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + + //Регистрация сервисов + public void RegisterServices(); + } +} diff --git a/AbstractShopContracts/DI/ServiceDependencyContainer.cs b/AbstractShopContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..9c7500f --- /dev/null +++ b/AbstractShopContracts/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 DinerContracts.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/AbstractShopContracts/DI/ServiceProviderLoader.cs b/AbstractShopContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..c3cef8c --- /dev/null +++ b/AbstractShopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.DI +{ + public static partial class ServiceProviderLoader + { + public static IImplementationExtension? GetImplementationExtensions() + { + IImplementationExtension? source = null; + + var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories); + + foreach (var file in files.Distinct()) + { + Assembly asm = Assembly.LoadFrom(file); + + foreach (var t in asm.GetExportedTypes()) + { + if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t)) + { + if (source == null) + { + source = (IImplementationExtension)Activator.CreateInstance(t)!; + } + else + { + var newSource = (IImplementationExtension)Activator.CreateInstance(t)!; + + if (newSource.Priority > source.Priority) + { + source = newSource; + } + } + } + } + } + + return source; + } + + private static string TryGetImplementationExtensionsFolder() + { + var directory = new DirectoryInfo(Directory.GetCurrentDirectory()); + + while (directory != null && !directory.GetDirectories("ImplementationExtensions", + SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions")) + { + directory = directory.Parent; + } + + return $"{directory?.FullName}\\ImplementationExtensions"; + } + } +} diff --git a/AbstractShopContracts/DI/UnityDependencyContainer.cs b/AbstractShopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..429a3b7 --- /dev/null +++ b/AbstractShopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Unity.Microsoft.Logging; +using Unity; + +namespace DinerContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + + } + + public T Resolve() + { + return _container.Resolve(); + } + + void IDependencyContainer.RegisterType(bool isSingle) + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + } +} diff --git a/AbstractShopContracts/DinerContracts.csproj b/AbstractShopContracts/DinerContracts.csproj index 692b9c3..4f55878 100644 --- a/AbstractShopContracts/DinerContracts.csproj +++ b/AbstractShopContracts/DinerContracts.csproj @@ -13,6 +13,8 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/AbstractShopContracts/StoragesContracts/IBackUpInfo.cs b/AbstractShopContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..5c9b36f --- /dev/null +++ b/AbstractShopContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/AbstractShopContracts/ViewModels/ClientViewModel.cs b/AbstractShopContracts/ViewModels/ClientViewModel.cs index 2bd31d1..3ceecf0 100644 --- a/AbstractShopContracts/ViewModels/ClientViewModel.cs +++ b/AbstractShopContracts/ViewModels/ClientViewModel.cs @@ -1,21 +1,17 @@ -using DinerDataModels.Models; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using DinerContracts.Attributes; +using DinerDataModels.Models; namespace DinerContracts.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/AbstractShopContracts/ViewModels/ComponentViewModel.cs b/AbstractShopContracts/ViewModels/ComponentViewModel.cs index 12ac568..304e4d5 100644 --- a/AbstractShopContracts/ViewModels/ComponentViewModel.cs +++ b/AbstractShopContracts/ViewModels/ComponentViewModel.cs @@ -1,14 +1,16 @@ using System.ComponentModel; using DinerDataModels.Models; +using DinerContracts.Attributes; namespace DinerContracts.ViewModels { public class ComponentViewModel : IComponentModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название компонента")] + [Column(title: "Название компонента", width: 150)] public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Cost { get; set; } } } diff --git a/AbstractShopContracts/ViewModels/ImplementerViewModel.cs b/AbstractShopContracts/ViewModels/ImplementerViewModel.cs index c5c1239..31e1c21 100644 --- a/AbstractShopContracts/ViewModels/ImplementerViewModel.cs +++ b/AbstractShopContracts/ViewModels/ImplementerViewModel.cs @@ -1,22 +1,24 @@ -using DinerDataModels.Models; +using DinerContracts.Attributes; +using DinerDataModels.Models; using System.ComponentModel; namespace DinerContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { - public int Id { get; set; } + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "ФИО исполнителя", width: 150)] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 150)] + public string Password { get; set; } = string.Empty; - [DisplayName("Стаж")] - public int WorkExperience { get; set; } + [Column(title: "Стаж", width: 150)] + public int WorkExperience { get; set; } - [DisplayName("Квалификация")] - public int Qualification { get; set; } + [Column(title: "Квалификация", width: 150)] + public int Qualification { get; set; } } } diff --git a/AbstractShopContracts/ViewModels/MessageInfoViewModel.cs b/AbstractShopContracts/ViewModels/MessageInfoViewModel.cs index 94bb898..5fd1ec3 100644 --- a/AbstractShopContracts/ViewModels/MessageInfoViewModel.cs +++ b/AbstractShopContracts/ViewModels/MessageInfoViewModel.cs @@ -1,23 +1,24 @@ -using System.ComponentModel; +using DinerContracts.Attributes; +using System.ComponentModel; namespace DinerContracts.ViewModels { public class MessageInfoViewModel { + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; - + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата отправки")] + [Column(title: "Дата отправки", width: 150)] public DateTime DateDelivery { get; set; } = DateTime.Now; - [DisplayName("Заголовок")] + [Column(title: "Заголовок", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", width: 150)] public string Body { get; set; } = string.Empty; } } diff --git a/AbstractShopContracts/ViewModels/OrderViewModel.cs b/AbstractShopContracts/ViewModels/OrderViewModel.cs index acbe911..facced7 100644 --- a/AbstractShopContracts/ViewModels/OrderViewModel.cs +++ b/AbstractShopContracts/ViewModels/OrderViewModel.cs @@ -1,32 +1,36 @@ using System.ComponentModel; using DinerDataModels.Models; using DinerDataModels.Enum; +using DinerContracts.Attributes; namespace DinerContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(visible: false)] public int Id { get; set; } + [Column(visible: false)] public int ClientId { get; set; } + [Column(visible: false)] public int? ImplementerId { get; set; } + [Column(visible: false)] public int SnackId { get; set; } - [DisplayName("Изделие")] + + [Column(title: "Изделие", width: 150)] public string SnackName { get; set; } = string.Empty; - - [DisplayName("Клиент")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Исполнитель")] + [Column(title: "ФИО исполнителя", width: 150)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + [Column(title: "Количество", width: 150)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 150)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 150)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 150)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 150)] public DateTime? DateImplement { get; set; } } } diff --git a/AbstractShopContracts/ViewModels/SnackViewModel.cs b/AbstractShopContracts/ViewModels/SnackViewModel.cs index 0e43889..98f70fb 100644 --- a/AbstractShopContracts/ViewModels/SnackViewModel.cs +++ b/AbstractShopContracts/ViewModels/SnackViewModel.cs @@ -1,15 +1,18 @@ -using DinerDataModels.Models; +using DinerContracts.Attributes; +using DinerDataModels.Models; using System.ComponentModel; namespace DinerContracts.ViewModels { public class SnackViewModel : ISnackModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название изделия")] + [Column(title: "Навание изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string SnackName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Price { get; set; } + [Column(visible: false)] public Dictionary SnackComponents { get; set; } = new(); } diff --git a/Diner/AbstractShopListImplement/DinerListImplement.csproj b/Diner/AbstractShopListImplement/DinerListImplement.csproj index 11e82ff..bf2d0ce 100644 --- a/Diner/AbstractShopListImplement/DinerListImplement.csproj +++ b/Diner/AbstractShopListImplement/DinerListImplement.csproj @@ -21,4 +21,8 @@ + + + + diff --git a/Diner/AbstractShopListImplement/Implements/BackUpInfo.cs b/Diner/AbstractShopListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..675219e --- /dev/null +++ b/Diner/AbstractShopListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,37 @@ +using DinerContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + var source = DataListSingleton.GetInstance(); + + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + + return null; + } + } +} diff --git a/Diner/AbstractShopListImplement/ListImplementationExtension.cs b/Diner/AbstractShopListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..43649f3 --- /dev/null +++ b/Diner/AbstractShopListImplement/ListImplementationExtension.cs @@ -0,0 +1,33 @@ +using DinerContracts.DI; +using DinerContracts.StoragesContracts; +using DinerListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerListImplement +{ + 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/Diner/AbstractShopListImplement/Models/MessageInfo.cs b/Diner/AbstractShopListImplement/Models/MessageInfo.cs index 19fde4e..0458643 100644 --- a/Diner/AbstractShopListImplement/Models/MessageInfo.cs +++ b/Diner/AbstractShopListImplement/Models/MessageInfo.cs @@ -4,6 +4,7 @@ using DinerDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; diff --git a/Diner/Diner/DataGridViewExtension.cs b/Diner/Diner/DataGridViewExtension.cs new file mode 100644 index 0000000..8ef6e62 --- /dev/null +++ b/Diner/Diner/DataGridViewExtension.cs @@ -0,0 +1,59 @@ +using DinerContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Diner +{ + 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/Diner/Diner/FormClients.cs b/Diner/Diner/FormClients.cs index 8df14f1..6efc484 100644 --- a/Diner/Diner/FormClients.cs +++ b/Diner/Diner/FormClients.cs @@ -36,13 +36,7 @@ namespace Diner _logger.LogInformation("Загрузка клиентов"); try { - var list = _clientLogic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_clientLogic.ReadList(null)); _logger.LogInformation("Успешная загрузка клиентов"); } diff --git a/Diner/Diner/FormComponents.cs b/Diner/Diner/FormComponents.cs index 87ff62a..3a4d03e 100644 --- a/Diner/Diner/FormComponents.cs +++ b/Diner/Diner/FormComponents.cs @@ -1,6 +1,7 @@ using DinerContracts.BindingModels; using DinerContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using DinerContracts.DI; namespace Diner { @@ -22,13 +23,7 @@ namespace Diner { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) @@ -40,29 +35,24 @@ namespace Diner } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { LoadData(); - } } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - form.Id = + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); if (form.ShowDialog() == DialogResult.OK) { LoadData(); } - } + } } private void ButtonDel_Click(object sender, EventArgs e) diff --git a/Diner/Diner/FormImplementers.cs b/Diner/Diner/FormImplementers.cs index 6518ba8..c67da74 100644 --- a/Diner/Diner/FormImplementers.cs +++ b/Diner/Diner/FormImplementers.cs @@ -10,6 +10,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using DinerContracts.DI; namespace Diner { @@ -36,16 +37,9 @@ namespace Diner { try { - var list = _logic.ReadList(null); + dataGridView.FillandConfigGrid(_logic.ReadList(null)); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - - _logger.LogInformation("Загрузка исполнителей"); + _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) { @@ -57,9 +51,9 @@ namespace Diner private void ButtonCreate_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormImplementer form) + if (form.ShowDialog() == DialogResult.OK) { if (form.ShowDialog() == DialogResult.OK) { @@ -72,20 +66,17 @@ namespace Diner { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - - if (form.ShowDialog() == DialogResult.OK) - { + if (form.ShowDialog() == DialogResult.OK) + { LoadData(); - } } } } + private void ButtonDelete_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/Diner/Diner/FormMails.cs b/Diner/Diner/FormMails.cs index 4a29d12..a318b5c 100644 --- a/Diner/Diner/FormMails.cs +++ b/Diner/Diner/FormMails.cs @@ -37,17 +37,9 @@ namespace Diner try { - var list = _messageLogic.ReadList(null); + dataGridView.FillandConfigGrid(_messageLogic.ReadList(null)); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - - _logger.LogInformation("Успешная загрузка писем"); + _logger.LogInformation("Успешная загрузка писем"); } catch (Exception ex) { diff --git a/Diner/Diner/FormMain.Designer.cs b/Diner/Diner/FormMain.Designer.cs index 97f758d..b76c310 100644 --- a/Diner/Diner/FormMain.Designer.cs +++ b/Diner/Diner/FormMain.Designer.cs @@ -20,198 +20,209 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - toolStrip = new ToolStrip(); - manualsToolStripLabel = new ToolStripDropDownButton(); - componentsToolStripMenuItem = new ToolStripMenuItem(); - snacksToolStripMenuItem = new ToolStripMenuItem(); - clientsToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - manualsStripDropDownButton = new ToolStripDropDownButton(); - listComponentsToolStripMenuItem = new ToolStripMenuItem(); - componentSnacksToolStripMenuItem = new ToolStripMenuItem(); - ordersToolStripMenuItem = new ToolStripMenuItem(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - workWithClientsToolStripMenuItem = new ToolStripMenuItem(); - toolStripDropDownButtonMails = new ToolStripDropDownButton(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - toolStrip.SuspendLayout(); - SuspendLayout(); - // - // dataGridView - // - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 27); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(986, 421); - dataGridView.TabIndex = 0; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(1040, 88); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(202, 29); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(1040, 159); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(202, 29); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(1040, 233); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(202, 29); - buttonRef.TabIndex = 5; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // toolStrip - // - toolStrip.ImageScalingSize = new Size(20, 20); - toolStrip.Items.AddRange(new ToolStripItem[] { manualsToolStripLabel, manualsStripDropDownButton, toolStripDropDownButton1, toolStripDropDownButtonMails }); - toolStrip.Location = new Point(0, 0); - toolStrip.Name = "toolStrip"; - toolStrip.Size = new Size(1280, 27); - toolStrip.TabIndex = 6; - toolStrip.Text = "toolStrip1"; - // - // manualsToolStripLabel - // - manualsToolStripLabel.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, snacksToolStripMenuItem, clientsToolStripMenuItem, исполнителиToolStripMenuItem }); - manualsToolStripLabel.Name = "manualsToolStripLabel"; - manualsToolStripLabel.Size = new Size(117, 24); - manualsToolStripLabel.Text = "Справочники"; - // - // componentsToolStripMenuItem - // - componentsToolStripMenuItem.Name = "componentsToolStripMenuItem"; - componentsToolStripMenuItem.Size = new Size(185, 26); - componentsToolStripMenuItem.Text = "Компоненты"; - componentsToolStripMenuItem.Click += ComponentToolStripMenuItem_Click; - // - // snacksToolStripMenuItem - // - snacksToolStripMenuItem.Name = "snacksToolStripMenuItem"; - snacksToolStripMenuItem.Size = new Size(185, 26); - snacksToolStripMenuItem.Text = "Закуски"; - snacksToolStripMenuItem.Click += ProductToolStripMenuItem_Click; - // - // clientsToolStripMenuItem - // - clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; - clientsToolStripMenuItem.Size = new Size(185, 26); - clientsToolStripMenuItem.Text = "Клиенты"; - clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(185, 26); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; - // - // manualsStripDropDownButton - // - manualsStripDropDownButton.DropDownItems.AddRange(new ToolStripItem[] { listComponentsToolStripMenuItem, componentSnacksToolStripMenuItem, ordersToolStripMenuItem }); - manualsStripDropDownButton.Name = "manualsStripDropDownButton"; - manualsStripDropDownButton.Size = new Size(73, 24); - manualsStripDropDownButton.Text = "Отчеты"; - // - // listComponentsToolStripMenuItem - // - listComponentsToolStripMenuItem.Name = "listComponentsToolStripMenuItem"; - listComponentsToolStripMenuItem.Size = new Size(267, 26); - listComponentsToolStripMenuItem.Text = "Список закусок"; - listComponentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // componentSnacksToolStripMenuItem - // - componentSnacksToolStripMenuItem.Name = "componentSnacksToolStripMenuItem"; - componentSnacksToolStripMenuItem.Size = new Size(267, 26); - componentSnacksToolStripMenuItem.Text = "Закуски по компонентам"; - componentSnacksToolStripMenuItem.Click += ComponentSnacksToolStripMenuItem_Click; - // - // ordersToolStripMenuItem - // - ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; - ordersToolStripMenuItem.Size = new Size(267, 26); - ordersToolStripMenuItem.Text = "Список заказов"; - ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // toolStripDropDownButton1 - // - toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); - toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(114, 24); - toolStripDropDownButton1.Text = "Запуск работ"; - toolStripDropDownButton1.Click += WorkProcessToolStripDropDownButton1_Click; - // - // workWithClientsToolStripMenuItem - // - workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem"; - workWithClientsToolStripMenuItem.Size = new Size(32, 19); - // - // toolStripDropDownButtonMails - // - toolStripDropDownButtonMails.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButtonMails.Image = (Image)resources.GetObject("toolStripDropDownButtonMails.Image"); - toolStripDropDownButtonMails.ImageTransparentColor = Color.Magenta; - toolStripDropDownButtonMails.Name = "toolStripDropDownButtonMails"; - toolStripDropDownButtonMails.Size = new Size(77, 24); - toolStripDropDownButtonMails.Text = "Письма"; - toolStripDropDownButtonMails.Click += WorkProcessToolStripDropDownButtonMails_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1280, 450); - Controls.Add(toolStrip); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Name = "FormMain"; - Text = "Закусочная"; - Load += FormMain_Load; - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - toolStrip.ResumeLayout(false); - toolStrip.PerformLayout(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + toolStrip = new ToolStrip(); + manualsToolStripLabel = new ToolStripDropDownButton(); + componentsToolStripMenuItem = new ToolStripMenuItem(); + snacksToolStripMenuItem = new ToolStripMenuItem(); + clientsToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + manualsStripDropDownButton = new ToolStripDropDownButton(); + listComponentsToolStripMenuItem = new ToolStripMenuItem(); + componentSnacksToolStripMenuItem = new ToolStripMenuItem(); + ordersToolStripMenuItem = new ToolStripMenuItem(); + toolStripDropDownButton1 = new ToolStripDropDownButton(); + toolStripDropDownButtonMails = new ToolStripDropDownButton(); + toolStripDropDownButtonBackup = new ToolStripDropDownButton(); + workWithClientsToolStripMenuItem = new ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + toolStrip.SuspendLayout(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 27); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(1034, 421); + dataGridView.TabIndex = 0; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1040, 88); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(202, 29); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1040, 159); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(202, 29); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(1040, 233); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(202, 29); + buttonRef.TabIndex = 5; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // toolStrip + // + toolStrip.ImageScalingSize = new Size(20, 20); + toolStrip.Items.AddRange(new ToolStripItem[] { manualsToolStripLabel, manualsStripDropDownButton, toolStripDropDownButton1, toolStripDropDownButtonMails, toolStripDropDownButtonBackup }); + toolStrip.Location = new Point(0, 0); + toolStrip.Name = "toolStrip"; + toolStrip.Size = new Size(1280, 27); + toolStrip.TabIndex = 6; + toolStrip.Text = "toolStrip1"; + // + // manualsToolStripLabel + // + manualsToolStripLabel.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, snacksToolStripMenuItem, clientsToolStripMenuItem, исполнителиToolStripMenuItem }); + manualsToolStripLabel.Name = "manualsToolStripLabel"; + manualsToolStripLabel.Size = new Size(117, 24); + manualsToolStripLabel.Text = "Справочники"; + // + // componentsToolStripMenuItem + // + componentsToolStripMenuItem.Name = "componentsToolStripMenuItem"; + componentsToolStripMenuItem.Size = new Size(185, 26); + componentsToolStripMenuItem.Text = "Компоненты"; + componentsToolStripMenuItem.Click += ComponentToolStripMenuItem_Click; + // + // snacksToolStripMenuItem + // + snacksToolStripMenuItem.Name = "snacksToolStripMenuItem"; + snacksToolStripMenuItem.Size = new Size(185, 26); + snacksToolStripMenuItem.Text = "Закуски"; + snacksToolStripMenuItem.Click += ProductToolStripMenuItem_Click; + // + // clientsToolStripMenuItem + // + clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; + clientsToolStripMenuItem.Size = new Size(185, 26); + clientsToolStripMenuItem.Text = "Клиенты"; + clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; + // + // manualsStripDropDownButton + // + manualsStripDropDownButton.DropDownItems.AddRange(new ToolStripItem[] { listComponentsToolStripMenuItem, componentSnacksToolStripMenuItem, ordersToolStripMenuItem }); + manualsStripDropDownButton.Name = "manualsStripDropDownButton"; + manualsStripDropDownButton.Size = new Size(73, 24); + manualsStripDropDownButton.Text = "Отчеты"; + // + // listComponentsToolStripMenuItem + // + listComponentsToolStripMenuItem.Name = "listComponentsToolStripMenuItem"; + listComponentsToolStripMenuItem.Size = new Size(267, 26); + listComponentsToolStripMenuItem.Text = "Список закусок"; + listComponentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // componentSnacksToolStripMenuItem + // + componentSnacksToolStripMenuItem.Name = "componentSnacksToolStripMenuItem"; + componentSnacksToolStripMenuItem.Size = new Size(267, 26); + componentSnacksToolStripMenuItem.Text = "Закуски по компонентам"; + componentSnacksToolStripMenuItem.Click += ComponentSnacksToolStripMenuItem_Click; + // + // ordersToolStripMenuItem + // + ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; + ordersToolStripMenuItem.Size = new Size(267, 26); + ordersToolStripMenuItem.Text = "Список заказов"; + ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // toolStripDropDownButton1 + // + toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); + toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; + toolStripDropDownButton1.Name = "toolStripDropDownButton1"; + toolStripDropDownButton1.Size = new Size(114, 24); + toolStripDropDownButton1.Text = "Запуск работ"; + toolStripDropDownButton1.Click += WorkProcessToolStripDropDownButton1_Click; + // + // toolStripDropDownButtonMails + // + toolStripDropDownButtonMails.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButtonMails.Image = (Image)resources.GetObject("toolStripDropDownButtonMails.Image"); + toolStripDropDownButtonMails.ImageTransparentColor = Color.Magenta; + toolStripDropDownButtonMails.Name = "toolStripDropDownButtonMails"; + toolStripDropDownButtonMails.Size = new Size(77, 24); + toolStripDropDownButtonMails.Text = "Письма"; + toolStripDropDownButtonMails.Click += WorkProcessToolStripDropDownButtonMails_Click; + // + // toolStripDropDownButtonBackup + // + toolStripDropDownButtonBackup.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButtonBackup.Image = (Image)resources.GetObject("toolStripDropDownButtonBackup.Image"); + toolStripDropDownButtonBackup.ImageTransparentColor = Color.Magenta; + toolStripDropDownButtonBackup.Name = "toolStripDropDownButtonBackup"; + toolStripDropDownButtonBackup.Size = new Size(122, 24); + toolStripDropDownButtonBackup.Text = "Создать бэкап"; + toolStripDropDownButtonBackup.Click += WorkProcessToolStripDropDownButtonBackup_Click; + // + // workWithClientsToolStripMenuItem + // + workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem"; + workWithClientsToolStripMenuItem.Size = new Size(32, 19); + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1280, 450); + Controls.Add(toolStrip); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Name = "FormMain"; + Text = "Закусочная"; + Load += FormMain_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + toolStrip.ResumeLayout(false); + toolStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private DataGridView dataGridView; + private DataGridView dataGridView; private Button buttonCreateOrder; private Button buttonIssuedOrder; private Button buttonRef; @@ -228,5 +239,6 @@ private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripDropDownButton toolStripDropDownButton1; private ToolStripDropDownButton toolStripDropDownButtonMails; - } + private ToolStripDropDownButton toolStripDropDownButtonBackup; + } } \ No newline at end of file diff --git a/Diner/Diner/FormMain.cs b/Diner/Diner/FormMain.cs index e5a8eaa..8bdb8fc 100644 --- a/Diner/Diner/FormMain.cs +++ b/Diner/Diner/FormMain.cs @@ -2,6 +2,8 @@ using DinerContracts.BusinessLogicsContracts; using DinerDataModels.Enum; using Microsoft.Extensions.Logging; +using DinerContracts.DI; +using Org.BouncyCastle.Asn1.X509; namespace Diner { @@ -13,35 +15,27 @@ namespace Diner 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) { LoadData(); } private void LoadData() { - // прописать логику + try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["SnackId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["SnackName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка заказов"); + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); + _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) { @@ -51,28 +45,20 @@ namespace Diner } private void ComponentToolStripMenuItem_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 ProductToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSnacks)); - if (service is FormSnacks 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(); + } @@ -118,54 +104,61 @@ namespace Diner private void ComponentSnacksToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportSnackComponents)); - if (service is FormReportSnackComponents 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 ClientsToolStripMenuItem_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 ImplementersToolStripMenuItem_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 WorkProcessToolStripDropDownButton1_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 WorkProcessToolStripDropDownButtonMails_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormMails form) + form.ShowDialog(); + } + private void WorkProcessToolStripDropDownButtonBackup_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/Diner/Diner/FormMain.resx b/Diner/Diner/FormMain.resx index 6602630..ec9d602 100644 --- a/Diner/Diner/FormMain.resx +++ b/Diner/Diner/FormMain.resx @@ -135,12 +135,23 @@ iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEISURBVEhL3ZErDsJAGIR7DlA47oArV8CDR9RiSDAQPBcA - Qx1BgUMQBEk1ooJAKE0I4Wlqf5gmu1n6oqW7hiZfthkx33aqeZ5HKvEFpmmSYRhSQScXINB1XSroDAke - 96cUpAmupyPZsx7Z8x4drAnPpQmsgU7LdoHDJNIEYjnAlyBXJ3jPhVyaYLca8nLMhX+CPJXAOT+ouTj5 - p5in4asApdWpS8XRwT+zShIFG/fOyxlZJbGC9f5G5bHzUf6LJFJQqTViyxlxEmRiHhLUW10qDbeRpUGC - ErwjE/OQoG9dIsviYGWsXMwxc24BYLcO5pgZc+cWJIG5MbsyAUDnHwlUAkFHJZraR9NeMVq3zi+WF/0A - AAAASUVORK5CYII= + YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEKSURBVEhL3ZG9DsFQHMXvczDZvIOtXsHObuhqkViI3Quw + 6CYmNoMYJJ0NBiFFIoIytOuf0+TeXP3yde+iyS+3OcP53Z4y3/dJJ4HAsiwyTVMp6BQCBIZhKAWdEcHV + vSlBmeB82NFy1KLluEWOPRC5MoHdMWhazwi4RJlALgf4EuT6BI+5kCsTrGddUY658E+QvyXYHq9UnRyC + U87f4aUApcXhnrI9Jzg/laQKFntXlHM+lSQK5psL5fvbp/JvJLGCQqmSWM5JkiCT84igXGtSrruKLQ0T + luAdmZxHBG37FFuWBC/j5XKOmX8WAH7rcI6ZMffPgjQwN2bXJgDo/COBTpjneQ2dML0PY3cISreGe8HM + qgAAAABJRU5ErkJggg== + + + + + iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 + YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEKSURBVEhL3ZG9DsFQHMXvczDZvIOtXsHObuhqkViI3Quw + 6CYmNoMYJJ0NBiFFIoIytOuf0+TeXP3yde+iyS+3OcP53Z4y3/dJJ4HAsiwyTVMp6BQCBIZhKAWdEcHV + vSlBmeB82NFy1KLluEWOPRC5MoHdMWhazwi4RJlALgf4EuT6BI+5kCsTrGddUY658E+QvyXYHq9UnRyC + U87f4aUApcXhnrI9Jzg/laQKFntXlHM+lSQK5psL5fvbp/JvJLGCQqmSWM5JkiCT84igXGtSrruKLQ0T + luAdmZxHBG37FFuWBC/j5XKOmX8WAH7rcI6ZMffPgjQwN2bXJgDo/COBTpjneQ2dML0PY3cISreGe8HM + qgAAAABJRU5ErkJggg== \ No newline at end of file diff --git a/Diner/Diner/FormSnack.cs b/Diner/Diner/FormSnack.cs index d5b4db6..b8be21f 100644 --- a/Diner/Diner/FormSnack.cs +++ b/Diner/Diner/FormSnack.cs @@ -2,6 +2,7 @@ using DinerContracts.BusinessLogicsContracts; using DinerContracts.SearchModels; using DinerDataModels.Models; +using DinerContracts.DI; using Microsoft.Extensions.Logging; namespace Diner @@ -70,11 +71,8 @@ namespace Diner } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormSnackComponent)); - if (service is FormSnackComponent form) - { - if (form.ShowDialog() == DialogResult.OK) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { if (form.ComponentModel == null) { @@ -92,18 +90,15 @@ namespace Diner form.Count)); } LoadData(); - } + } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = - Program.ServiceProvider?.GetService(typeof(FormSnackComponent)); - if (service is FormSnackComponent form) - { - int id = + var form = DependencyManager.Instance.Resolve(); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Id = id; form.Count = _productComponents[id].Item2; @@ -118,7 +113,6 @@ namespace Diner LoadData(); } } - } } private void ButtonDel_Click(object sender, EventArgs e) { diff --git a/Diner/Diner/FormSnacks.cs b/Diner/Diner/FormSnacks.cs index 4956cc8..5268e73 100644 --- a/Diner/Diner/FormSnacks.cs +++ b/Diner/Diner/FormSnacks.cs @@ -1,6 +1,7 @@ using DinerContracts.BindingModels; using DinerContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using DinerContracts.DI; namespace Diner { @@ -19,18 +20,10 @@ namespace Diner { try { - var list = _logic.ReadList(null); - - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["SnackName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["SnackComponents"].Visible = false; - } - + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); + } catch (Exception ex) { @@ -41,32 +34,26 @@ namespace Diner private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSnack)); - - if (service is FormSnack form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { LoadData(); - } + } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormSnack)); + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (service is FormSnack form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - - if (form.ShowDialog() == DialogResult.OK) + if (form.ShowDialog() == DialogResult.OK) { LoadData(); } } - } + } private void ButtonDel_Click(object sender, EventArgs e) { diff --git a/Diner/Diner/Program.cs b/Diner/Diner/Program.cs index aca355a..890587a 100644 --- a/Diner/Diner/Program.cs +++ b/Diner/Diner/Program.cs @@ -9,13 +9,13 @@ using DinerBusinessLogic.OfficePackage; using DinerBusinessLogic.OfficePackage.Implements; using DinerBusinessLogic.MailWorker; using DinerContracts.BindingModels; +using DinerContracts.DI; namespace Diner { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; + /// /// The main entry point for the application. /// @@ -26,73 +26,71 @@ namespace Diner // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); - try - { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); + InitDependency(); + try + { + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); - } - catch (Exception ex) - { - var logger = _serviceProvider.GetService(); + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = DependencyManager.Instance.Resolve(); + + logger?.LogError(ex, " "); + } + Application.Run(DependencyManager.Instance.Resolve()); - logger?.LogError(ex, " "); - } - Application.Run(_serviceProvider.GetRequiredService()); } - 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(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); - 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.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 diff --git a/Diner/DinerDataBaseImplement/DataBaseImplementationExtension.cs b/Diner/DinerDataBaseImplement/DataBaseImplementationExtension.cs new file mode 100644 index 0000000..8b4c56c --- /dev/null +++ b/Diner/DinerDataBaseImplement/DataBaseImplementationExtension.cs @@ -0,0 +1,33 @@ +using DinerContracts.DI; +using DinerContracts.StoragesContracts; +using DinerDataBaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerDataBaseImplement +{ + 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/Diner/DinerDataBaseImplement/DinerDataBaseImplement.csproj b/Diner/DinerDataBaseImplement/DinerDataBaseImplement.csproj index 9d6f52e..3b9d33c 100644 --- a/Diner/DinerDataBaseImplement/DinerDataBaseImplement.csproj +++ b/Diner/DinerDataBaseImplement/DinerDataBaseImplement.csproj @@ -21,4 +21,8 @@ + + + + diff --git a/Diner/DinerDataBaseImplement/Implements/BackUpInfo.cs b/Diner/DinerDataBaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..9cfd976 --- /dev/null +++ b/Diner/DinerDataBaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,35 @@ +using DinerContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerDataBaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new DinerDatabase(); + + 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/Diner/DinerDataBaseImplement/Models/Client.cs b/Diner/DinerDataBaseImplement/Models/Client.cs index 0e294f2..ab68764 100644 --- a/Diner/DinerDataBaseImplement/Models/Client.cs +++ b/Diner/DinerDataBaseImplement/Models/Client.cs @@ -8,20 +8,26 @@ using System.Text; using System.Threading.Tasks; using DinerContracts.BindingModels; using DinerContracts.ViewModels; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ClientFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Email { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; [ForeignKey("ClientId")] diff --git a/Diner/DinerDataBaseImplement/Models/Component.cs b/Diner/DinerDataBaseImplement/Models/Component.cs index c6e1401..157b5a7 100644 --- a/Diner/DinerDataBaseImplement/Models/Component.cs +++ b/Diner/DinerDataBaseImplement/Models/Component.cs @@ -3,15 +3,20 @@ using DinerContracts.ViewModels; using DinerDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string ComponentName { get; private set; } = string.Empty; [Required] + [DataMember] public double Cost { get; set; } [ForeignKey("ComponentId")] public virtual List SnackComponents { get; set; } = new(); diff --git a/Diner/DinerDataBaseImplement/Models/Implementer.cs b/Diner/DinerDataBaseImplement/Models/Implementer.cs index 1ad418f..2eee8ae 100644 --- a/Diner/DinerDataBaseImplement/Models/Implementer.cs +++ b/Diner/DinerDataBaseImplement/Models/Implementer.cs @@ -8,24 +8,31 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { - public class Implementer : IImplementerModel + [DataContract] + public class Implementer : IImplementerModel { - public int Id { get; set; } + [DataMember] + public int Id { get; set; } [Required] - public string ImplementerFIO { get; set; } = string.Empty; + [DataMember] + public string ImplementerFIO { get; set; } = string.Empty; [Required] - public string Password { get; set; } = string.Empty; + [DataMember] + public string Password { get; set; } = string.Empty; [Required] - public int WorkExperience { get; set; } + [DataMember] + public int WorkExperience { get; set; } [Required] - public int Qualification { get; set; } + [DataMember] + public int Qualification { get; set; } [ForeignKey("ImplementerId")] public virtual List Orders { get; set; } = new(); diff --git a/Diner/DinerDataBaseImplement/Models/MessageInfo.cs b/Diner/DinerDataBaseImplement/Models/MessageInfo.cs index db42cf7..b3ea514 100644 --- a/Diner/DinerDataBaseImplement/Models/MessageInfo.cs +++ b/Diner/DinerDataBaseImplement/Models/MessageInfo.cs @@ -7,12 +7,15 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { [Key] + [DataMember] public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } diff --git a/Diner/DinerDataBaseImplement/Models/Order.cs b/Diner/DinerDataBaseImplement/Models/Order.cs index dd662b3..d28e237 100644 --- a/Diner/DinerDataBaseImplement/Models/Order.cs +++ b/Diner/DinerDataBaseImplement/Models/Order.cs @@ -4,27 +4,37 @@ using DinerContracts.ViewModels; using DinerDataModels.Enum; using DinerDataModels.Models; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; using System.Xml.Linq; namespace DinerDataBaseImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public int ClientId { get; private set; } + [DataMember] public int? ImplementerId { get; private set; } [Required] + [DataMember] public int SnackId { get; private set; } [Required] + [DataMember] public int Count { get; private set; } [Required] + [DataMember] public double Sum { get; private set; } [Required] + [DataMember] public OrderStatus Status { get; private set; } [Required] + [DataMember] public DateTime DateCreate { get; private set; } - + [DataMember] public DateTime? DateImplement { get; private set; } public virtual Snack Snack { get; set; } diff --git a/Diner/DinerDataBaseImplement/Models/Snack.cs b/Diner/DinerDataBaseImplement/Models/Snack.cs index 50f99f8..e57213f 100644 --- a/Diner/DinerDataBaseImplement/Models/Snack.cs +++ b/Diner/DinerDataBaseImplement/Models/Snack.cs @@ -3,18 +3,24 @@ using DinerContracts.ViewModels; using DinerDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { + [DataContract] public class Snack : ISnackModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string SnackName { get; set; } = string.Empty; [Required] + [DataMember] public double Price { get; set; } private Dictionary? _snackComponents = null; [NotMapped] + [DataMember] public Dictionary SnackComponents { get diff --git a/Diner/DinerDataBaseImplement/Models/SnackComponent.cs b/Diner/DinerDataBaseImplement/Models/SnackComponent.cs index f137677..5426971 100644 --- a/Diner/DinerDataBaseImplement/Models/SnackComponent.cs +++ b/Diner/DinerDataBaseImplement/Models/SnackComponent.cs @@ -1,12 +1,14 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DinerDataBaseImplement.Models { + [DataContract] public class SnackComponent { public int Id { get; set; } diff --git a/Diner/DinerFileImplement/DinerFileImplement.csproj b/Diner/DinerFileImplement/DinerFileImplement.csproj index 031588f..c012636 100644 --- a/Diner/DinerFileImplement/DinerFileImplement.csproj +++ b/Diner/DinerFileImplement/DinerFileImplement.csproj @@ -18,6 +18,11 @@ + + + + + diff --git a/Diner/DinerFileImplement/FileImplementationExtension.cs b/Diner/DinerFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..8aa8823 --- /dev/null +++ b/Diner/DinerFileImplement/FileImplementationExtension.cs @@ -0,0 +1,33 @@ +using DinerContracts.DI; +using DinerContracts.StoragesContracts; +using DinerDataBaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerFileImplement +{ + 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/Diner/DinerFileImplement/Implements/BackUpInfo.cs b/Diner/DinerFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..4b7b41a --- /dev/null +++ b/Diner/DinerFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,37 @@ +using DinerContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DinerFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + var source = DataFileSingleton.GetInstance(); + + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + + return null; + } + } +} diff --git a/Diner/DinerFileImplement/Models/Client.cs b/Diner/DinerFileImplement/Models/Client.cs index 667d2fd..18fc7c7 100644 --- a/Diner/DinerFileImplement/Models/Client.cs +++ b/Diner/DinerFileImplement/Models/Client.cs @@ -7,17 +7,20 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerFileImplement.Models { + [DataContract] internal class Client : IClientModel { + [DataMember] public int Id { get; private set; } - + [DataMember] public string ClientFIO { get; private set; } = string.Empty; - + [DataMember] public string Email { get; private set; } = string.Empty; - + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) diff --git a/Diner/DinerFileImplement/Models/Component.cs b/Diner/DinerFileImplement/Models/Component.cs index e3378c6..e6644cf 100644 --- a/Diner/DinerFileImplement/Models/Component.cs +++ b/Diner/DinerFileImplement/Models/Component.cs @@ -2,13 +2,18 @@ using DinerContracts.ViewModels; using DinerDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerFileImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ComponentName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } public static Component? Create(ComponentBindingModel model) { diff --git a/Diner/DinerFileImplement/Models/Implementer.cs b/Diner/DinerFileImplement/Models/Implementer.cs index 7960a56..e167a85 100644 --- a/Diner/DinerFileImplement/Models/Implementer.cs +++ b/Diner/DinerFileImplement/Models/Implementer.cs @@ -7,20 +7,23 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerFileImplement.Models { - public class Implementer : IImplementerModel + [DataContract] + public class Implementer : IImplementerModel { public int Id { get; private set; } + [DataMember] + public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; + [DataMember] + public int WorkExperience { get; private set; } + [DataMember] - public string ImplementerFIO { get; private set; } = string.Empty; - - public string Password { get; private set; } = string.Empty; - - public int WorkExperience { get; private set; } - - public int Qualification { get; private set; } + public int Qualification { get; private set; } public static Implementer? Create(ImplementerBindingModel model) { diff --git a/Diner/DinerFileImplement/Models/MessageInfo.cs b/Diner/DinerFileImplement/Models/MessageInfo.cs index 1992938..ebc7e84 100644 --- a/Diner/DinerFileImplement/Models/MessageInfo.cs +++ b/Diner/DinerFileImplement/Models/MessageInfo.cs @@ -9,27 +9,29 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerDataBaseImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { - [Key] + [DataMember] public string MessageId { get; set; } = string.Empty; - + [DataMember] public int? ClientId { get; set; } - [Required] + [DataMember] public string SenderName { get; set; } = string.Empty; - [Required] + [DataMember] public DateTime DateDelivery { get; set; } = DateTime.Now; - [Required] + [DataMember] public string Subject { get; set; } = string.Empty; - [Required] + [DataMember] public string Body { get; set; } = string.Empty; diff --git a/Diner/DinerFileImplement/Models/Order.cs b/Diner/DinerFileImplement/Models/Order.cs index a57208f..df4672f 100644 --- a/Diner/DinerFileImplement/Models/Order.cs +++ b/Diner/DinerFileImplement/Models/Order.cs @@ -4,24 +4,30 @@ using DinerDataModels.Enum; using DinerDataModels.Models; using System.Reflection; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerFileImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int SnackID { 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/Diner/DinerFileImplement/Models/Snack.cs b/Diner/DinerFileImplement/Models/Snack.cs index 1462a34..75b4205 100644 --- a/Diner/DinerFileImplement/Models/Snack.cs +++ b/Diner/DinerFileImplement/Models/Snack.cs @@ -2,15 +2,22 @@ using DinerContracts.ViewModels; using DinerDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace DinerFileImplement.Models { + [DataContract] public class Snack : ISnackModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string SnackName { get; private set; } = string.Empty; + [DataMember] public double Price { get; private set; } + [DataMember] public Dictionary Components { get; private set; } = new(); + [DataMember] private Dictionary? _snackComponents = null; public Dictionary SnackComponents {