diff --git a/Confectionery/ConfectioneryBusinessLogic/BackUpLogic.cs b/Confectionery/ConfectioneryBusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..548cda6 --- /dev/null +++ b/Confectionery/ConfectioneryBusinessLogic/BackUpLogic.cs @@ -0,0 +1,102 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.StoragesContracts; +using ConfectioneryDataModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryBusinessLogic +{ + 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); + } + } +} \ No newline at end of file diff --git a/Confectionery/ConfectioneryContracts/Attributes/ColumnAttribute.cs b/Confectionery/ConfectioneryContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..20f005c --- /dev/null +++ b/Confectionery/ConfectioneryContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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/Confectionery/ConfectioneryContracts/Attributes/GridViewAutoSize.cs b/Confectionery/ConfectioneryContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..5066c83 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/Confectionery/ConfectioneryContracts/BindingModels/BackUpSaveBinidngModel.cs b/Confectionery/ConfectioneryContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..d9c4f01 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/Confectionery/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs b/Confectionery/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs index e101807..611b00a 100644 --- a/Confectionery/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs +++ b/Confectionery/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs @@ -9,6 +9,7 @@ namespace ConfectioneryContracts.BindingModels { public class MessageInfoBindingModel : IMessageInfoModel { + public int Id => throw new NotImplementedException(); public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } public string SenderName { get; set; } = string.Empty; diff --git a/Confectionery/ConfectioneryContracts/BusinessLogicsContracts/IBackUpLogic.cs b/Confectionery/ConfectioneryContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..d037887 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ConfectioneryContracts.BindingModels; + +namespace ConfectioneryContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/Confectionery/ConfectioneryContracts/ConfectioneryContracts.csproj b/Confectionery/ConfectioneryContracts/ConfectioneryContracts.csproj index 75c03cc..76424bf 100644 --- a/Confectionery/ConfectioneryContracts/ConfectioneryContracts.csproj +++ b/Confectionery/ConfectioneryContracts/ConfectioneryContracts.csproj @@ -9,6 +9,8 @@ + + diff --git a/Confectionery/ConfectioneryContracts/DI/DependencyManager.cs b/Confectionery/ConfectioneryContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..5ad4b3a --- /dev/null +++ b/Confectionery/ConfectioneryContracts/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 ConfectioneryContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new ServiceDependencyContainer(); + } + + public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } } + + /// + /// Иницализация библиотек, в которых идут установки зависомстей + /// + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + // регистрируем зависимости + ext.RegisterServices(); + } + + /// + /// Регистрация логгера + /// + /// + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Получение класса со всеми зависмостями + /// + /// + /// + public T Resolve() => _dependencyManager.Resolve(); + } +} diff --git a/Confectionery/ConfectioneryContracts/DI/IDependencyContainer.cs b/Confectionery/ConfectioneryContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..3570776 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/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 ConfectioneryContracts.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/Confectionery/ConfectioneryContracts/DI/IImplementationExtension.cs b/Confectionery/ConfectioneryContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..5a82ed5 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/Confectionery/ConfectioneryContracts/DI/ServiceDependencyContainer.cs b/Confectionery/ConfectioneryContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..eef5984 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/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 ConfectioneryContracts.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/Confectionery/ConfectioneryContracts/DI/ServiceProviderLoader.cs b/Confectionery/ConfectioneryContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..4b87754 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/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 ConfectioneryContracts.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/Confectionery/ConfectioneryContracts/DI/UnityDependencyContainer.cs b/Confectionery/ConfectioneryContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..91636b4 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Unity.Microsoft.Logging; +using Unity; +using Microsoft.Extensions.Logging; + +namespace ConfectioneryContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + + public void RegisterType(bool isSingle) where U : class, T where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + + public T Resolve() + { + return _container.Resolve(); + } + } +} diff --git a/Confectionery/ConfectioneryContracts/StoragesContracts/IBackUpInfo.cs b/Confectionery/ConfectioneryContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..3a66c37 --- /dev/null +++ b/Confectionery/ConfectioneryContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/Confectionery/ConfectioneryContracts/ViewModels/ClientViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/ClientViewModel.cs index 7b837cb..14fcb57 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/ClientViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; +using ConfectioneryDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,12 +11,13 @@ namespace ConfectioneryContracts.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/Confectionery/ConfectioneryContracts/ViewModels/ComponentViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/ComponentViewModel.cs index 7ef4f36..5d0d131 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/ComponentViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/ComponentViewModel.cs @@ -1,4 +1,5 @@ using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,12 +9,13 @@ using System.Threading.Tasks; namespace ConfectioneryContracts.ViewModels { - public class ComponentViewModel : IComponentModel - { - public int Id { get; set; } - [DisplayName("Название компонента")] - public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Cost { get; set; } - } + public class ComponentViewModel : IComponentModel + { + [Column(visible: false)] + public int Id { get; set; } + [Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ComponentName { get; set; } = string.Empty; + [Column(title: "Цена", width: 150)] + public double Cost { get; set; } + } } diff --git a/Confectionery/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs index 7427339..cc178f7 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,18 +11,19 @@ namespace ConfectioneryContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 100)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] + [Column(title: "Стаж работы", width: 60)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column(title: "Квалификация", width: 60)] public int Qualification { get; set; } } } diff --git a/Confectionery/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs index 6f8e090..d7f41f6 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,23 @@ namespace ConfectioneryContracts.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; } } diff --git a/Confectionery/ConfectioneryContracts/ViewModels/OrderViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/OrderViewModel.cs index e1dbe9f..7085703 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/OrderViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/OrderViewModel.cs @@ -1,5 +1,6 @@ using ConfectioneryDataModels.Enums; using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -11,28 +12,32 @@ namespace ConfectioneryContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(title: "Номер", width: 90)] public int Id { get; set; } + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 190)] public string ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] public string ClientEmail { get; set; } = string.Empty; + [Column(visible: false)] public int? ImplementerId { get; set; } - [DisplayName("Исполнитель")] + [Column(title: "Исполнитель", width: 150)] public string? ImplementerFIO { get; set; } = null; + [Column(visible: false)] public int PastryId { get; set; } - [DisplayName("Изделие")] + [Column(title: "Изделие", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string PastryName { get; set; } = string.Empty; - [DisplayName("Количество")] + [Column(title: "Количество", width: 100)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 120)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 70)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 120)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 120)] public DateTime? DateImplement { get; set; } } } diff --git a/Confectionery/ConfectioneryContracts/ViewModels/PastryViewModel.cs b/Confectionery/ConfectioneryContracts/ViewModels/PastryViewModel.cs index 15257b0..841d3e5 100644 --- a/Confectionery/ConfectioneryContracts/ViewModels/PastryViewModel.cs +++ b/Confectionery/ConfectioneryContracts/ViewModels/PastryViewModel.cs @@ -1,4 +1,5 @@ using ConfectioneryDataModels.Models; +using ConfectioneryContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,13 +9,15 @@ using System.Threading.Tasks; namespace ConfectioneryContracts.ViewModels { - public class PastryViewModel : IPastryModel - { - public int Id { get; set; } - [DisplayName("Название изделия")] - public string PastryName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Price { get; set; } - public Dictionary PastryComponents { get; set; } = new(); - } + public class PastryViewModel : IPastryModel + { + [Column(visible: false)] + public int Id { get; set; } + [Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string PastryName { get; set; } = string.Empty; + [Column(title: "Цена", width: 70)] + public double Price { get; set; } + [Column(visible: false)] + public Dictionary PastryComponents { get; set; } = new(); + } } diff --git a/Confectionery/ConfectioneryDataModels/IMessageInfoModel.cs b/Confectionery/ConfectioneryDataModels/IMessageInfoModel.cs index ac8025d..01536e5 100644 --- a/Confectionery/ConfectioneryDataModels/IMessageInfoModel.cs +++ b/Confectionery/ConfectioneryDataModels/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace ConfectioneryDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } int? ClientId { get; } diff --git a/Confectionery/ConfectioneryDatabaseImplement/BackUpInfo.cs b/Confectionery/ConfectioneryDatabaseImplement/BackUpInfo.cs new file mode 100644 index 0000000..8285fba --- /dev/null +++ b/Confectionery/ConfectioneryDatabaseImplement/BackUpInfo.cs @@ -0,0 +1,32 @@ +using ConfectioneryContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new ConfectioneryDatabase(); + 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/Confectionery/ConfectioneryDatabaseImplement/Client.cs b/Confectionery/ConfectioneryDatabaseImplement/Client.cs index f5eda43..9ec9f80 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/Client.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/Client.cs @@ -8,17 +8,22 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ConfectioneryDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } - + [DataMember] [Required] public string ClientFIO { get; set; } = string.Empty; + [DataMember] [Required] public string Email { get; set; } = string.Empty; + [DataMember] [Required] public string Password { get; set; } = string.Empty; diff --git a/Confectionery/ConfectioneryDatabaseImplement/Component.cs b/Confectionery/ConfectioneryDatabaseImplement/Component.cs index a350c35..6602010 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/Component.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/Component.cs @@ -3,54 +3,59 @@ using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace ConfectioneryDatabaseImplement.Models { - public class Component : IComponentModel - { - public int Id { get; private set; } - [Required] - public string ComponentName { get; private set; } = string.Empty; - [Required] - public double Cost { get; set; } - [ForeignKey("ComponentId")] - public virtual List PastryComponents { get; set; } = new(); - public static Component? Create(ComponentBindingModel model) - { - if (model == null) - { - return null; - } - return new Component() - { - Id = model.Id, - ComponentName = model.ComponentName, - Cost = model.Cost - }; - } - public static Component Create(ComponentViewModel model) - { - return new Component - { - Id = model.Id, - ComponentName = model.ComponentName, - Cost = model.Cost - }; - } - public void Update(ComponentBindingModel model) - { - if (model == null) - { - return; - } - ComponentName = model.ComponentName; - Cost = model.Cost; - } - public ComponentViewModel GetViewModel => new() - { - Id = Id, - ComponentName = ComponentName, - Cost = Cost - }; - } + [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 PastryComponents { get; set; } = new(); + public static Component? Create(ComponentBindingModel model) + { + if (model == null) + { + return null; + } + return new Component() + { + Id = model.Id, + ComponentName = model.ComponentName, + Cost = model.Cost + }; + } + public static Component Create(ComponentViewModel model) + { + return new Component + { + Id = model.Id, + ComponentName = model.ComponentName, + Cost = model.Cost + }; + } + public void Update(ComponentBindingModel model) + { + if (model == null) + { + return; + } + ComponentName = model.ComponentName; + Cost = model.Cost; + } + public ComponentViewModel GetViewModel => new() + { + Id = Id, + ComponentName = ComponentName, + Cost = Cost + }; + } } \ No newline at end of file diff --git a/Confectionery/ConfectioneryDatabaseImplement/ConfectioneryDatabaseImplement.csproj b/Confectionery/ConfectioneryDatabaseImplement/ConfectioneryDatabaseImplement.csproj index 428d10d..1d9f5f7 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/ConfectioneryDatabaseImplement.csproj +++ b/Confectionery/ConfectioneryDatabaseImplement/ConfectioneryDatabaseImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/Confectionery/ConfectioneryDatabaseImplement/DatabaseImplementationExtension.cs b/Confectionery/ConfectioneryDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..5fb0f57 --- /dev/null +++ b/Confectionery/ConfectioneryDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,27 @@ +using ConfectioneryContracts.DI; +using ConfectioneryContracts.StoragesContracts; +using ConfectioneryDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryDatabaseImplement +{ + 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/Confectionery/ConfectioneryDatabaseImplement/Implementer.cs b/Confectionery/ConfectioneryDatabaseImplement/Implementer.cs index 7282a3e..1b16f8f 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/Implementer.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/Implementer.cs @@ -8,22 +8,25 @@ using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace ConfectioneryDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } - + [DataMember] [Required] public string ImplementerFIO { get; set; } = string.Empty; - + [DataMember] [Required] public string Password { get; set; } = string.Empty; - + [DataMember] [Required] public int WorkExperience { get; set; } - + [DataMember] [Required] public int Qualification { get; set; } diff --git a/Confectionery/ConfectioneryDatabaseImplement/MessageInfo.cs b/Confectionery/ConfectioneryDatabaseImplement/MessageInfo.cs index 926aa49..bb22a39 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/MessageInfo.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/MessageInfo.cs @@ -8,28 +8,32 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace ConfectioneryDatabaseImplement.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; diff --git a/Confectionery/ConfectioneryDatabaseImplement/Order.cs b/Confectionery/ConfectioneryDatabaseImplement/Order.cs index 9f70fa3..16355d2 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/Order.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/Order.cs @@ -6,39 +6,42 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ConfectioneryDatabaseImplement.Models { + [DataContract] public class Order : IOrderModel { - public int Id { get; private set; } + [DataMember] + public int Id { get; set; } + [DataMember] [Required] - public int ClientId { get; private set; } - - public virtual Client Client { get; private set; } = new(); - + public int PastryId { get; set; } + [DataMember] [Required] - public int PastryId { get; private set; } - - public virtual Pastry Pastry { get; set; } = new(); + public int ClientId { get; set; } + [DataMember] public int? ImplementerId { get; private set; } - public virtual Implementer? Implementer { get; set; } = new(); - + [DataMember] [Required] - public int Count { get; private set; } - + public int Count { get; set; } + [DataMember] [Required] - public double Sum { get; private set; } - + public double Sum { get; set; } + [DataMember] [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - + public OrderStatus Status { get; set; } + [DataMember] [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; - - public DateTime? DateImplement { get; private set; } + public DateTime DateCreate { get; set; } + [DataMember] + public DateTime? DateImplement { get; set; } + public virtual Pastry Pastry { get; set; } + public virtual Client Client { get; set; } + public virtual Implementer? Implementer { get; set; } public static Order Create(ConfectioneryDatabase context, OrderBindingModel model) { diff --git a/Confectionery/ConfectioneryDatabaseImplement/Pastry.cs b/Confectionery/ConfectioneryDatabaseImplement/Pastry.cs index ea42b37..1f56e28 100644 --- a/Confectionery/ConfectioneryDatabaseImplement/Pastry.cs +++ b/Confectionery/ConfectioneryDatabaseImplement/Pastry.cs @@ -8,89 +8,95 @@ using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace ConfectioneryDatabaseImplement.Models { - public class Pastry : IPastryModel - { - public int Id { get; set; } - [Required] - public string PastryName { get; set; } = string.Empty; - [Required] - public double Price { get; set; } - private Dictionary? _pastryComponents = null; - [NotMapped] - public Dictionary PastryComponents - { - get - { - if (_pastryComponents == null) - { - _pastryComponents = Components - .ToDictionary(recPC => recPC.ComponentId, recPC => - (recPC.Component as IComponentModel, recPC.Count)); - } - return _pastryComponents; - } - } - [ForeignKey("PastryId")] - public virtual List Components { get; set; } = new(); - [ForeignKey("PastryId")] - public virtual List Orders { get; set; } = new(); - public static Pastry Create(ConfectioneryDatabase context, PastryBindingModel model) - { - return new Pastry() - { - Id = model.Id, - PastryName = model.PastryName, - Price = model.Price, - Components = model.PastryComponents.Select(x => new PastryComponent - { - Component = context.Components.First(y => y.Id == x.Key), - Count = x.Value.Item2 - }).ToList() - }; - } - public void Update(PastryBindingModel model) - { - PastryName = model.PastryName; - Price = model.Price; - } - public PastryViewModel GetViewModel => new() - { - Id = Id, - PastryName = PastryName, - Price = Price, - PastryComponents = PastryComponents - }; - public void UpdateComponents(ConfectioneryDatabase context, PastryBindingModel model) - { - var pastryComponents = context.PastryComponents.Where(rec => rec.PastryId == model.Id).ToList(); - if (pastryComponents != null && pastryComponents.Count > 0) - { // удалили те, которых нет в модели - context.PastryComponents.RemoveRange(pastryComponents.Where(rec => !model.PastryComponents.ContainsKey(rec.ComponentId))); - context.SaveChanges(); - // обновили количество у существующих записей - foreach (var updateComponent in pastryComponents) - { - updateComponent.Count = model.PastryComponents[updateComponent.ComponentId].Item2; - model.PastryComponents.Remove(updateComponent.ComponentId); - } - context.SaveChanges(); - } - var pastry = context.Pastrys.First(x => x.Id == Id); - foreach (var pc in model.PastryComponents) - { - context.PastryComponents.Add(new PastryComponent - { - Pastry = pastry, - Component = context.Components.First(x => x.Id == pc.Key), - Count = pc.Value.Item2 - }); - context.SaveChanges(); - } - _pastryComponents = null; - } - } + [DataContract] + public class Pastry : IPastryModel + { + [DataMember] + public int Id { get; set; } + [DataMember] + [Required] + public string PastryName { get; set; } = string.Empty; + [DataMember] + [Required] + public double Price { get; set; } + private Dictionary? _pastryComponents = null; + [DataMember] + [NotMapped] + public Dictionary PastryComponents + { + get + { + if (_pastryComponents == null) + { + _pastryComponents = Components + .ToDictionary(recPC => recPC.ComponentId, recPC => + (recPC.Component as IComponentModel, recPC.Count)); + } + return _pastryComponents; + } + } + [ForeignKey("PastryId")] + public virtual List Components { get; set; } = new(); + [ForeignKey("PastryId")] + public virtual List Orders { get; set; } = new(); + public static Pastry Create(ConfectioneryDatabase context, PastryBindingModel model) + { + return new Pastry() + { + Id = model.Id, + PastryName = model.PastryName, + Price = model.Price, + Components = model.PastryComponents.Select(x => new PastryComponent + { + Component = context.Components.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + public void Update(PastryBindingModel model) + { + PastryName = model.PastryName; + Price = model.Price; + } + public PastryViewModel GetViewModel => new() + { + Id = Id, + PastryName = PastryName, + Price = Price, + PastryComponents = PastryComponents + }; + public void UpdateComponents(ConfectioneryDatabase context, PastryBindingModel model) + { + var pastryComponents = context.PastryComponents.Where(rec => rec.PastryId == model.Id).ToList(); + if (pastryComponents != null && pastryComponents.Count > 0) + { // удалили те, которых нет в модели + context.PastryComponents.RemoveRange(pastryComponents.Where(rec => !model.PastryComponents.ContainsKey(rec.ComponentId))); + context.SaveChanges(); + // обновили количество у существующих записей + foreach (var updateComponent in pastryComponents) + { + updateComponent.Count = model.PastryComponents[updateComponent.ComponentId].Item2; + model.PastryComponents.Remove(updateComponent.ComponentId); + } + context.SaveChanges(); + } + var pastry = context.Pastrys.First(x => x.Id == Id); + foreach (var pc in model.PastryComponents) + { + context.PastryComponents.Add(new PastryComponent + { + Pastry = pastry, + Component = context.Components.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _pastryComponents = null; + } + } } diff --git a/Confectionery/ConfectioneryFileImplement/BackUpInfo.cs b/Confectionery/ConfectioneryFileImplement/BackUpInfo.cs new file mode 100644 index 0000000..cee3913 --- /dev/null +++ b/Confectionery/ConfectioneryFileImplement/BackUpInfo.cs @@ -0,0 +1,44 @@ +using ConfectioneryContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryFileImplement +{ + 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/Confectionery/ConfectioneryFileImplement/Client.cs b/Confectionery/ConfectioneryFileImplement/Client.cs index c87c19f..0ab8629 100644 --- a/Confectionery/ConfectioneryFileImplement/Client.cs +++ b/Confectionery/ConfectioneryFileImplement/Client.cs @@ -4,73 +4,82 @@ using ConfectioneryDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; -namespace ConfectioneryFileImplement +namespace ConfectioneryFileImplement.Models { - public class Client : IClientModel - { - public int Id { get; set; } - public string ClientFIO { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; - public string Email { get; set; } = string.Empty; + [DataContract] + public class Client : IClientModel + { + [DataMember] + public int Id { get; private set; } - public static Client? Create(ClientBindingModel? model) - { - if (model == null) - { - return null; - } - return new Client() - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Password = model.Password, - Email = model.Email - }; - } + [DataMember] + public string ClientFIO { get; private set; } = string.Empty; - public static Client? Create(XElement element) - { - if (element == null) - { - return null; - } - return new Client() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ClientFIO = element.Attribute("ClientFIO")!.Value, - Password = element.Attribute("Password")!.Value, - Email = element.Attribute("Email")!.Value - }; - } + [DataMember] + public string Email { get; private set; } = string.Empty; - public void Update(ClientBindingModel? model) - { - if (model == null) - { - return; - } - ClientFIO = model.ClientFIO; - Password = model.Password; - Email = model.Email; - } + [DataMember] + public string Password { get; private set; } = string.Empty; - public ClientViewModel GetViewModel => new() - { - Id = Id, - ClientFIO = ClientFIO, - Password = Password, - Email = Email - }; + public static Client? Create(ClientBindingModel? model) + { + if (model == null) + { + return null; + } + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Password = model.Password, + Email = model.Email + }; + } - public XElement GetXElement => new("Client", - new XAttribute("Id", Id), - new XElement("ClientFIO", ClientFIO), - new XElement("Password", Password), - new XElement("Email", Email)); - } + public static Client? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Client() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ClientFIO = element.Attribute("ClientFIO")!.Value, + Password = element.Attribute("Password")!.Value, + Email = element.Attribute("Email")!.Value + }; + } + + public void Update(ClientBindingModel? model) + { + if (model == null) + { + return; + } + ClientFIO = model.ClientFIO; + Password = model.Password; + Email = model.Email; + } + + public ClientViewModel GetViewModel => new() + { + Id = Id, + ClientFIO = ClientFIO, + Password = Password, + Email = Email + }; + + public XElement GetXElement => new("Client", + new XAttribute("Id", Id), + new XElement("ClientFIO", ClientFIO), + new XElement("Password", Password), + new XElement("Email", Email)); + } } diff --git a/Confectionery/ConfectioneryFileImplement/Component.cs b/Confectionery/ConfectioneryFileImplement/Component.cs index 38ab4a0..cbeea94 100644 --- a/Confectionery/ConfectioneryFileImplement/Component.cs +++ b/Confectionery/ConfectioneryFileImplement/Component.cs @@ -1,59 +1,64 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace ConfectioneryFileImplement.Models { - public class Component : IComponentModel - { - public int Id { get; private set; } - public string ComponentName { get; private set; } = string.Empty; - public double Cost { get; set; } - public static Component? Create(ComponentBindingModel model) - { - if (model == null) - { - return null; - } - return new Component() - { - Id = model.Id, - ComponentName = model.ComponentName, - Cost = model.Cost - }; - } - public static Component? Create(XElement element) - { - if (element == null) - { - return null; - } - return new Component() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ComponentName = element.Element("ComponentName")!.Value, - Cost = Convert.ToDouble(element.Element("Cost")!.Value) - }; - } - public void Update(ComponentBindingModel model) - { - if (model == null) - { - return; - } - ComponentName = model.ComponentName; - Cost = model.Cost; - } - public ComponentViewModel GetViewModel => new() - { - Id = Id, - ComponentName = ComponentName, - Cost = Cost - }; - public XElement GetXElement => new("Component", - new XAttribute("Id", Id), - new XElement("ComponentName", ComponentName), - new XElement("Cost", Cost.ToString())); - } + [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) + { + if (model == null) + { + return null; + } + return new Component() + { + Id = model.Id, + ComponentName = model.ComponentName, + Cost = model.Cost + }; + } + public static Component? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Component() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ComponentName = element.Element("ComponentName")!.Value, + Cost = Convert.ToDouble(element.Element("Cost")!.Value) + }; + } + public void Update(ComponentBindingModel model) + { + if (model == null) + { + return; + } + ComponentName = model.ComponentName; + Cost = model.Cost; + } + public ComponentViewModel GetViewModel => new() + { + Id = Id, + ComponentName = ComponentName, + Cost = Cost + }; + public XElement GetXElement => new("Component", + new XAttribute("Id", Id), + new XElement("ComponentName", ComponentName), + new XElement("Cost", Cost.ToString())); + } } diff --git a/Confectionery/ConfectioneryFileImplement/ConfectioneryFileImplement.csproj b/Confectionery/ConfectioneryFileImplement/ConfectioneryFileImplement.csproj index 965df58..e350124 100644 --- a/Confectionery/ConfectioneryFileImplement/ConfectioneryFileImplement.csproj +++ b/Confectionery/ConfectioneryFileImplement/ConfectioneryFileImplement.csproj @@ -16,4 +16,8 @@ + + + + diff --git a/Confectionery/ConfectioneryFileImplement/ImplementationExtension.cs b/Confectionery/ConfectioneryFileImplement/ImplementationExtension.cs new file mode 100644 index 0000000..4c1f970 --- /dev/null +++ b/Confectionery/ConfectioneryFileImplement/ImplementationExtension.cs @@ -0,0 +1,27 @@ +using ConfectioneryContracts.StoragesContracts; +using ConfectioneryDatabaseImplement.Implements; +using ConfectioneryContracts.DI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryFileImplement +{ + public class ImplementationExtension + { + 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/Confectionery/ConfectioneryFileImplement/Implementer.cs b/Confectionery/ConfectioneryFileImplement/Implementer.cs index 586579a..3c34e3f 100644 --- a/Confectionery/ConfectioneryFileImplement/Implementer.cs +++ b/Confectionery/ConfectioneryFileImplement/Implementer.cs @@ -4,23 +4,26 @@ using ConfectioneryDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace ConfectioneryFileImplement.Models { + [DataContract] public class Implementer : IImplementerModel { - public int Id { get; private set; } - - 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; } + [DataMember] + public int Id { get; set; } + [DataMember] + public string ImplementerFIO { get; set; } = string.Empty; + [DataMember] + public string Password { get; set; } = string.Empty; + [DataMember] + public int WorkExperience { get; set; } + [DataMember] + public int Qualification { get; set; } public static Implementer? Create(XElement element) { diff --git a/Confectionery/ConfectioneryFileImplement/MessageInfo.cs b/Confectionery/ConfectioneryFileImplement/MessageInfo.cs index 6889771..ac678c5 100644 --- a/Confectionery/ConfectioneryFileImplement/MessageInfo.cs +++ b/Confectionery/ConfectioneryFileImplement/MessageInfo.cs @@ -4,24 +4,29 @@ using ConfectioneryDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace ConfectioneryFileImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + [DataMember] + public int Id { get; private set; } + [DataMember] public string MessageId { get; private set; } = string.Empty; - + [DataMember] public int? ClientId { get; private set; } - + [DataMember] public string SenderName { get; private set; } = string.Empty; - + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; - + [DataMember] public string Subject { get; private set; } = string.Empty; - + [DataMember] public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) diff --git a/Confectionery/ConfectioneryFileImplement/Order.cs b/Confectionery/ConfectioneryFileImplement/Order.cs index e7e242f..85f350d 100644 --- a/Confectionery/ConfectioneryFileImplement/Order.cs +++ b/Confectionery/ConfectioneryFileImplement/Order.cs @@ -3,19 +3,38 @@ using ConfectioneryDataModels.Models; using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using System.Xml.Linq; +using System.Runtime.Serialization; namespace ConfectioneryFileImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } - public int ClientId { get; private set; } - public int? ImplementerId { get; set; } + + [DataMember] public int PastryId { 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; } - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - public DateTime DateCreate { get; private set; } = DateTime.Now; + + [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/Confectionery/ConfectioneryFileImplement/Pastry.cs b/Confectionery/ConfectioneryFileImplement/Pastry.cs index 7611b91..9256813 100644 --- a/Confectionery/ConfectioneryFileImplement/Pastry.cs +++ b/Confectionery/ConfectioneryFileImplement/Pastry.cs @@ -7,90 +7,95 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace ConfectioneryFileImplement.Models { - public class Pastry : IPastryModel - { - public int Id { get; private set; } - public string PastryName { get; private set; } = string.Empty; - public double Price { get; private set; } - public Dictionary Components { get; private set; } = new(); + [DataContract] + public class Pastry : IPastryModel + { + [DataMember] + public int Id { get; private set; } + [DataMember] + public string PastryName { get; private set; } = string.Empty; + [DataMember] + public double Price { get; private set; } + public Dictionary Components { get; private set; } = new(); - private Dictionary? _pastryComponents = null; - public Dictionary PastryComponents - { - get - { - if (_pastryComponents == null) - { - var source = DataFileSingleton.GetInstance(); - _pastryComponents = Components.ToDictionary(x => x.Key, y => - ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, - y.Value)); - } - return _pastryComponents; - } - } - public static Pastry? Create(PastryBindingModel model) - { - if (model == null) - { - return null; - } - return new Pastry() - { - Id = model.Id, - PastryName = model.PastryName, - Price = model.Price, - Components = model.PastryComponents.ToDictionary(x => x.Key, x - => x.Value.Item2) - }; - } - public static Pastry? Create(XElement element) - { - if (element == null) - { - return null; - } - return new Pastry() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - PastryName = element.Element("PastryName")!.Value, - Price = Convert.ToDouble(element.Element("Price")!.Value), - Components = element.Element("PastryComponents")!.Elements("PastryComponent").ToDictionary - (x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) - }; - } - public void Update(PastryBindingModel model) - { - if (model == null) - { - return; - } - PastryName = model.PastryName; - Price = model.Price; - Components = model.PastryComponents.ToDictionary(x => x.Key, x => x.Value.Item2); - _pastryComponents = null; - } - public PastryViewModel GetViewModel => new() - { - Id = Id, - PastryName = PastryName, - Price = Price, - PastryComponents = PastryComponents - }; - public XElement GetXElement => new("Pastry", - new XAttribute("Id", Id), - new XElement("PastryName", PastryName), - new XElement("Price", Price.ToString()), - new XElement("PastryComponents", Components.Select(x => - new XElement("PastryComponent", + private Dictionary? _pastryComponents = null; + public Dictionary PastryComponents + { + get + { + if (_pastryComponents == null) + { + var source = DataFileSingleton.GetInstance(); + _pastryComponents = Components.ToDictionary(x => x.Key, y => + ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, + y.Value)); + } + return _pastryComponents; + } + } + public static Pastry? Create(PastryBindingModel model) + { + if (model == null) + { + return null; + } + return new Pastry() + { + Id = model.Id, + PastryName = model.PastryName, + Price = model.Price, + Components = model.PastryComponents.ToDictionary(x => x.Key, x + => x.Value.Item2) + }; + } + public static Pastry? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Pastry() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + PastryName = element.Element("PastryName")!.Value, + Price = Convert.ToDouble(element.Element("Price")!.Value), + Components = element.Element("PastryComponents")!.Elements("PastryComponent").ToDictionary + (x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } + public void Update(PastryBindingModel model) + { + if (model == null) + { + return; + } + PastryName = model.PastryName; + Price = model.Price; + Components = model.PastryComponents.ToDictionary(x => x.Key, x => x.Value.Item2); + _pastryComponents = null; + } + public PastryViewModel GetViewModel => new() + { + Id = Id, + PastryName = PastryName, + Price = Price, + PastryComponents = PastryComponents + }; + public XElement GetXElement => new("Pastry", + new XAttribute("Id", Id), + new XElement("PastryName", PastryName), + new XElement("Price", Price.ToString()), + new XElement("PastryComponents", Components.Select(x => + new XElement("PastryComponent", - new XElement("Key", x.Key), + new XElement("Key", x.Key), - new XElement("Value", x.Value))) + new XElement("Value", x.Value))) - .ToArray())); - } + .ToArray())); + } } diff --git a/Confectionery/ConfectioneryListImplement/BackUpInfo.cs b/Confectionery/ConfectioneryListImplement/BackUpInfo.cs new file mode 100644 index 0000000..fbfb17d --- /dev/null +++ b/Confectionery/ConfectioneryListImplement/BackUpInfo.cs @@ -0,0 +1,22 @@ +using ConfectioneryContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + throw new NotImplementedException(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + throw new NotImplementedException(); + } + } +} diff --git a/Confectionery/ConfectioneryListImplement/ConfectioneryListImplement.csproj b/Confectionery/ConfectioneryListImplement/ConfectioneryListImplement.csproj index 4473d7c..23e3c50 100644 --- a/Confectionery/ConfectioneryListImplement/ConfectioneryListImplement.csproj +++ b/Confectionery/ConfectioneryListImplement/ConfectioneryListImplement.csproj @@ -16,4 +16,8 @@ + + + + diff --git a/Confectionery/ConfectioneryListImplement/ImplementationExtension.cs b/Confectionery/ConfectioneryListImplement/ImplementationExtension.cs new file mode 100644 index 0000000..6e58c2d --- /dev/null +++ b/Confectionery/ConfectioneryListImplement/ImplementationExtension.cs @@ -0,0 +1,27 @@ +using ConfectioneryContracts.DI; +using ConfectioneryContracts.StoragesContracts; +using ConfectioneryListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryListImplement +{ + public class ImplementationExtension : 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/Confectionery/ConfectioneryListImplement/MessageInfo.cs b/Confectionery/ConfectioneryListImplement/MessageInfo.cs index 81d7bad..6ff054b 100644 --- a/Confectionery/ConfectioneryListImplement/MessageInfo.cs +++ b/Confectionery/ConfectioneryListImplement/MessageInfo.cs @@ -11,6 +11,7 @@ namespace ConfectioneryListImplement.Models { public class MessageInfo : IMessageInfoModel { + public int Id => throw new NotImplementedException(); public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } diff --git a/Confectionery/ConfectioneryView/DataGridViewExtension.cs b/Confectionery/ConfectioneryView/DataGridViewExtension.cs new file mode 100644 index 0000000..4099850 --- /dev/null +++ b/Confectionery/ConfectioneryView/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ConfectioneryContracts.Attributes; + +namespace ConfectioneryView +{ + 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/Confectionery/ConfectioneryView/FormClients.cs b/Confectionery/ConfectioneryView/FormClients.cs index a93ec53..e059d83 100644 --- a/Confectionery/ConfectioneryView/FormClients.cs +++ b/Confectionery/ConfectioneryView/FormClients.cs @@ -33,18 +33,12 @@ namespace ConfectioneryView private void LoadData() { - 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("Загрузка списка клиентов"); - } - catch (Exception ex) + try + { + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка списка клиентов"); + } + catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки списка клиентов"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); diff --git a/Confectionery/ConfectioneryView/FormComponents.cs b/Confectionery/ConfectioneryView/FormComponents.cs index fb3ad31..05f66dd 100644 --- a/Confectionery/ConfectioneryView/FormComponents.cs +++ b/Confectionery/ConfectioneryView/FormComponents.cs @@ -1,5 +1,6 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,102 +14,89 @@ using System.Windows.Forms; namespace ConfectioneryView { - public partial class FormComponents : Form - { - private readonly ILogger _logger; - private readonly IComponentLogic _logic; - public FormComponents(ILogger logger, IComponentLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public partial class FormComponents : Form + { + private readonly ILogger _logger; + private readonly IComponentLogic _logic; + public FormComponents(ILogger logger, IComponentLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } - private void buttonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent 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) + { + LoadData(); + } + } - private void FormComponents_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка компонентов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки компонентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void FormComponents_Load(object sender, EventArgs e) + { + LoadData(); + } + 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 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 = 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 form = DependencyManager.Instance.Resolve(); - 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 ComponentBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } - } - 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 ComponentBindingModel + { + 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/Confectionery/ConfectioneryView/FormImplementers.cs b/Confectionery/ConfectioneryView/FormImplementers.cs index be8dafb..f787819 100644 --- a/Confectionery/ConfectioneryView/FormImplementers.cs +++ b/Confectionery/ConfectioneryView/FormImplementers.cs @@ -1,5 +1,6 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -29,14 +30,7 @@ namespace ConfectioneryView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) @@ -54,13 +48,10 @@ namespace ConfectioneryView private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } @@ -68,14 +59,11 @@ namespace ConfectioneryView { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/Confectionery/ConfectioneryView/FormMail.cs b/Confectionery/ConfectioneryView/FormMail.cs index 3def25c..e823f99 100644 --- a/Confectionery/ConfectioneryView/FormMail.cs +++ b/Confectionery/ConfectioneryView/FormMail.cs @@ -28,15 +28,7 @@ namespace ConfectioneryView { 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/Confectionery/ConfectioneryView/FormMain.Designer.cs b/Confectionery/ConfectioneryView/FormMain.Designer.cs index 7803f70..e1cdeb3 100644 --- a/Confectionery/ConfectioneryView/FormMain.Designer.cs +++ b/Confectionery/ConfectioneryView/FormMain.Designer.cs @@ -40,12 +40,13 @@ componentPastryToolStripMenuItem = new ToolStripMenuItem(); ordersListToolStripMenuItem = new ToolStripMenuItem(); startWorkToolStripMenuItem = new ToolStripMenuItem(); + mailToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - mailToolStripMenuItem = new ToolStripMenuItem(); + createBackupToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -63,7 +64,7 @@ // menuStrip // menuStrip.ImageScalingSize = new Size(24, 24); - menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчетыToolStripMenuItem, startWorkToolStripMenuItem, mailToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчетыToolStripMenuItem, startWorkToolStripMenuItem, mailToolStripMenuItem, createBackupToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(1666, 33); @@ -140,6 +141,13 @@ startWorkToolStripMenuItem.Text = "Запуск работ"; startWorkToolStripMenuItem.Click += startWorkToolStripMenuItem_Click; // + // mailToolStripMenuItem + // + mailToolStripMenuItem.Name = "mailToolStripMenuItem"; + mailToolStripMenuItem.Size = new Size(90, 29); + mailToolStripMenuItem.Text = "Письма"; + mailToolStripMenuItem.Click += mailToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -195,12 +203,12 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += buttonRef_Click; // - // mailToolStripMenuItem + // createBackupToolStripMenuItem // - mailToolStripMenuItem.Name = "mailToolStripMenuItem"; - mailToolStripMenuItem.Size = new Size(90, 29); - mailToolStripMenuItem.Text = "Письма"; - mailToolStripMenuItem.Click += mailToolStripMenuItem_Click; + createBackupToolStripMenuItem.Name = "createBackupToolStripMenuItem"; + createBackupToolStripMenuItem.Size = new Size(145, 29); + createBackupToolStripMenuItem.Text = "Создать бекап"; + createBackupToolStripMenuItem.Click += createBackupToolStripMenuItem_Click; // // FormMain // @@ -245,5 +253,6 @@ private ToolStripMenuItem startWorkToolStripMenuItem; private ToolStripMenuItem implementersToolStripMenuItem; private ToolStripMenuItem mailToolStripMenuItem; + private ToolStripMenuItem createBackupToolStripMenuItem; } } \ No newline at end of file diff --git a/Confectionery/ConfectioneryView/FormMain.cs b/Confectionery/ConfectioneryView/FormMain.cs index 03aa49d..86ce360 100644 --- a/Confectionery/ConfectioneryView/FormMain.cs +++ b/Confectionery/ConfectioneryView/FormMain.cs @@ -1,6 +1,8 @@ -using ConfectioneryContracts.BindingModels; +using ConfectioneryBusinessLogic; +using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using ConfectioneryContracts.DI; using System; using System.Collections.Generic; using System.ComponentModel; @@ -19,14 +21,16 @@ namespace ConfectioneryView private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; + private readonly IBackUpLogic _backUpLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + 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,17 +41,7 @@ namespace ConfectioneryView _logger.LogInformation("Загрузка заказов"); try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["PastryId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientEmail"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["PastryName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -58,29 +52,20 @@ namespace ConfectioneryView } 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 pastryToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPastrys)); - if (service is FormPastrys 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 buttonTakeOrderInWork_Click(object sender, EventArgs e) @@ -168,21 +153,14 @@ namespace ConfectioneryView private void componentPastryToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportPastryComponents)); - if (service is FormReportPastryComponents form) - { - form.ShowDialog(); - } - + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ordersListToolStripMenuItem_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 pastrysListToolStripMenuItem_Click(object sender, EventArgs e) @@ -201,34 +179,50 @@ namespace ConfectioneryView 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 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/Confectionery/ConfectioneryView/FormPastry.cs b/Confectionery/ConfectioneryView/FormPastry.cs index ec9f503..f19d8ee 100644 --- a/Confectionery/ConfectioneryView/FormPastry.cs +++ b/Confectionery/ConfectioneryView/FormPastry.cs @@ -1,5 +1,6 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.DI; using ConfectioneryContracts.SearchModels; using ConfectioneryDataModels.Models; using Microsoft.Extensions.Logging; @@ -15,227 +16,217 @@ using System.Windows.Forms; namespace ConfectioneryView { - public partial class FormPastry : Form - { - private readonly ILogger _logger; - private readonly IPastryLogic _logic; - private int? _id; - private Dictionary _pastryComponents; - public int Id { set { _id = value; } } + public partial class FormPastry : Form + { + private readonly ILogger _logger; + private readonly IPastryLogic _logic; + private int? _id; + private Dictionary _pastryComponents; + public int Id { set { _id = value; } } - public FormPastry(ILogger logger, IPastryLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - _pastryComponents = new Dictionary(); - } + public FormPastry(ILogger logger, IPastryLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _pastryComponents = new Dictionary(); + } - private void buttonSave_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxName.Text)) - { - MessageBox.Show("Заполните название", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (string.IsNullOrEmpty(textBoxPrice.Text)) - { - MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - return; - } - if (_pastryComponents == null || _pastryComponents.Count == 0) - { - MessageBox.Show("Заполните компоненты", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Сохранение изделия"); - try - { - var model = new PastryBindingModel - { - Id = _id ?? 0, - PastryName = textBoxName.Text, - Price = Convert.ToDouble(textBoxPrice.Text), - PastryComponents = _pastryComponents - }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + return; + } + if (_pastryComponents == null || _pastryComponents.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение изделия"); + try + { + var model = new PastryBindingModel + { + Id = _id ?? 0, + PastryName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + PastryComponents = _pastryComponents + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void FormPastry_Load(object sender, EventArgs e) - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.AllowUserToAddRows = false; - DataGridViewTextBoxColumn Id = new DataGridViewTextBoxColumn(); - DataGridViewTextBoxColumn Component = new DataGridViewTextBoxColumn(); - DataGridViewTextBoxColumn Number = new DataGridViewTextBoxColumn(); - Component.HeaderText = "Количество"; - Number.HeaderText = "Компонент"; - Number.Name = "Number"; - Id.Name = "Id"; - dataGridView.Columns.Add(Id); - dataGridView.Columns.Add(Number); - dataGridView.Columns.Add(Component); - dataGridView.Columns["Id"].Visible = false; + private void FormPastry_Load(object sender, EventArgs e) + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.AllowUserToAddRows = false; + DataGridViewTextBoxColumn Id = new DataGridViewTextBoxColumn(); + DataGridViewTextBoxColumn Component = new DataGridViewTextBoxColumn(); + DataGridViewTextBoxColumn Number = new DataGridViewTextBoxColumn(); + Component.HeaderText = "Количество"; + Number.HeaderText = "Компонент"; + Number.Name = "Number"; + Id.Name = "Id"; + dataGridView.Columns.Add(Id); + dataGridView.Columns.Add(Number); + dataGridView.Columns.Add(Component); + dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["Number"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - if (_id.HasValue) - { - _logger.LogInformation("Загрузка суши"); - try - { - var view = _logic.ReadElement(new PastrySearchModel - { - Id = _id.Value - }); - if (view != null) - { - textBoxName.Text = view.PastryName; - textBoxPrice.Text = view.Price.ToString(); - _pastryComponents = view.PastryComponents ?? new - Dictionary(); - LoadData(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки суши"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - private void LoadData() - { - _logger.LogInformation("Загрузка компонент изделия"); - try - { - if (_pastryComponents != null) - { - dataGridView.Rows.Clear(); - foreach (var pc in _pastryComponents) - { - dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 }); - } - textBoxPrice.Text = CalcPrice().ToString(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки компонент изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } + dataGridView.Columns["Number"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + if (_id.HasValue) + { + _logger.LogInformation("Загрузка суши"); + try + { + var view = _logic.ReadElement(new PastrySearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxName.Text = view.PastryName; + textBoxPrice.Text = view.Price.ToString(); + _pastryComponents = view.PastryComponents ?? new + Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки суши"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void LoadData() + { + _logger.LogInformation("Загрузка компонент изделия"); + try + { + if (_pastryComponents != null) + { + dataGridView.Rows.Clear(); + foreach (var pc in _pastryComponents) + { + dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 }); + } + textBoxPrice.Text = CalcPrice().ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонент изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } - private void buttonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPastryComponent)); - if (service is FormPastryComponent form) - { - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Добавление нового компонента:{ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count); - if (_pastryComponents.ContainsKey(form.Id)) - { - _pastryComponents[form.Id] = (form.ComponentModel, - form.Count); - } - else - { - _pastryComponents.Add(form.Id, (form.ComponentModel, - form.Count)); - } - LoadData(); - } - } - } + private void buttonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + return; + } + _logger.LogInformation("Добавление нового ингридиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + if (_pastryComponents.ContainsKey(form.Id)) + { + _pastryComponents[form.Id] = (form.ComponentModel, + form.Count); + } + else + { + _pastryComponents.Add(form.Id, (form.ComponentModel, + form.Count)); + } + LoadData(); + } - private void buttonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = - Program.ServiceProvider?.GetService(typeof(FormPastryComponent)); - if (service is FormPastryComponent form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _pastryComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента: {ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count); - _pastryComponents[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 = _pastryComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Изменение ингридиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + _pastryComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); + } + } + } - private void buttonDel_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - try - { - _logger.LogInformation("Удаление компонента: {ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); _pastryComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - LoadData(); - } - } - } + private void buttonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление компонента: {ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); _pastryComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + } + } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void buttonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } - private double CalcPrice() - { - double price = 0; - foreach (var elem in _pastryComponents) - { - price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); - } - return Math.Round(price * 1.1, 2); - } - } + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + private double CalcPrice() + { + double price = 0; + foreach (var elem in _pastryComponents) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } + return Math.Round(price * 1.1, 2); + } + } } diff --git a/Confectionery/ConfectioneryView/FormPastrys.cs b/Confectionery/ConfectioneryView/FormPastrys.cs index c416875..1a5cbf9 100644 --- a/Confectionery/ConfectioneryView/FormPastrys.cs +++ b/Confectionery/ConfectioneryView/FormPastrys.cs @@ -10,105 +10,92 @@ using System.Windows.Forms; using Microsoft.Extensions.Logging; using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.DI; namespace ConfectioneryView { - public partial class FormPastrys : Form - { - private readonly ILogger _logger; - private readonly IPastryLogic _logic; - public FormPastrys(ILogger logger, IPastryLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } - private void FormPastrys_Load(object sender, EventArgs e) - { - LoadData(); - } + public partial class FormPastrys : Form + { + private readonly ILogger _logger; + private readonly IPastryLogic _logic; + public FormPastrys(ILogger logger, IPastryLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormPastrys_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["PastryComponents"].Visible = false; - dataGridView.Columns["PastryName"].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 buttonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPastry)); - if (service is FormPastry 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) + { + LoadData(); + } + } - private void buttonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPastry)); - if (service is FormPastry 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 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) - { - 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 PastryBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления кондитерского изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } + 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 PastryBindingModel + { + 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 buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/Confectionery/ConfectioneryView/Program.cs b/Confectionery/ConfectioneryView/Program.cs index 0ce7e90..627269f 100644 --- a/Confectionery/ConfectioneryView/Program.cs +++ b/Confectionery/ConfectioneryView/Program.cs @@ -10,6 +10,7 @@ using NLog.Extensions.Logging; using ConfectioneryBusinessLogic.BusinessLogics; using Microsoft.EntityFrameworkCore.Design; using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.DI; namespace ConfectioneryView { @@ -25,12 +26,10 @@ namespace ConfectioneryView 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, @@ -45,55 +44,59 @@ namespace ConfectioneryView } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); logger?.LogError(ex, "Mails Problem"); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + 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(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); + 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(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file diff --git a/Confectionery/ImplementationExtensions/ConfectioneryContracts.dll b/Confectionery/ImplementationExtensions/ConfectioneryContracts.dll new file mode 100644 index 0000000..ddbae4a Binary files /dev/null and b/Confectionery/ImplementationExtensions/ConfectioneryContracts.dll differ diff --git a/Confectionery/ImplementationExtensions/ConfectioneryDataModels.dll b/Confectionery/ImplementationExtensions/ConfectioneryDataModels.dll new file mode 100644 index 0000000..42e7ceb Binary files /dev/null and b/Confectionery/ImplementationExtensions/ConfectioneryDataModels.dll differ diff --git a/Confectionery/ImplementationExtensions/ConfectioneryDatabaseImplement.dll b/Confectionery/ImplementationExtensions/ConfectioneryDatabaseImplement.dll new file mode 100644 index 0000000..9aa1d19 Binary files /dev/null and b/Confectionery/ImplementationExtensions/ConfectioneryDatabaseImplement.dll differ diff --git a/Confectionery/ImplementationExtensions/ConfectioneryFileImplement.dll b/Confectionery/ImplementationExtensions/ConfectioneryFileImplement.dll new file mode 100644 index 0000000..ad32f90 Binary files /dev/null and b/Confectionery/ImplementationExtensions/ConfectioneryFileImplement.dll differ diff --git a/Confectionery/ImplementationExtensions/ConfectioneryListImplement.dll b/Confectionery/ImplementationExtensions/ConfectioneryListImplement.dll new file mode 100644 index 0000000..a88c8f0 Binary files /dev/null and b/Confectionery/ImplementationExtensions/ConfectioneryListImplement.dll differ