diff --git a/.gitignore b/.gitignore index ca1c7a3..9965e6d 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,4 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +ImplementationExtensions/ diff --git a/BlacksmithWorkshop/BlacksmithListImplement/BlacksmithWorkshopListImplement.csproj b/BlacksmithWorkshop/BlacksmithListImplement/BlacksmithWorkshopListImplement.csproj index 4b96496..7e1a0f0 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/BlacksmithWorkshopListImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithListImplement/BlacksmithWorkshopListImplement.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..d572e96 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,21 @@ +using BlacksmithWorkshopContracts.StorageContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement.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/BlacksmithWorkshop/BlacksmithListImplement/ListImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..c202ed0 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithListImplement/ListImplementationExtension.cs @@ -0,0 +1,26 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StorageContracts; +using BlacksmithWorkshopListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopListImplement +{ + public class ListImplementationExtension : IImplementationExtension + { + public int Priority => 0; + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/Client.cs index 28fbe2b..cdae659 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/Client.cs @@ -4,16 +4,22 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopListImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ClientFIO { get; private set; } = string.Empty; + [DataMember] public string Email { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel? model) { diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/Component.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/Component.cs index 31b0f31..2bb3764 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/Component.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/Component.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; @@ -10,10 +11,14 @@ using BlacksmithWorkshopDataModels.Models; namespace BlacksmithWorkshopListImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ComponentName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } public static Component? Create(ComponentBindingModel? model) { diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/Implementer.cs index 0e7d98e..7bc4503 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/Implementer.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/Implementer.cs @@ -4,18 +4,25 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopListImplement.Models { - public class Implementer : IImplementerModel + [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; private set; } + [DataMember] + public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; + [DataMember] + public int WorkExperience { get; private set; } + [DataMember] + public int Qualification { get; private set; } public static Implementer? Create(ImplementerBindingModel? model) { if (model == null) diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/Manufacture.cs index 5997b50..9fe85cd 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/Manufacture.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/Manufacture.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; @@ -10,10 +11,14 @@ using BlacksmithWorkshopDataModels.Models; namespace BlacksmithWorkshopListImplement.Models { + [DataContract] public class Manufacture : IManufactureModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ManufactureName { get; private set; } = string.Empty; + [DataMember] public double Price { get; private set; } public Dictionary ManufactureComponents { diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/MessageInfo.cs index 6a2cd5b..f6c5bd0 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/MessageInfo.cs @@ -4,19 +4,27 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopListImplement.Models { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { - public string MessageId { get; private set; } = string.Empty; - public int? ClientId { get; private set; } - public string SenderName { get; private set; } = string.Empty; - public DateTime DateDelivery { get; private set; } = DateTime.Now; - public string Subject { get; private set; } = string.Empty; - public string Body { get; private set; } = string.Empty; + [DataMember] + public string MessageId { get; private set; } = string.Empty; + [DataMember] + public int? ClientId { get; private set; } + [DataMember] + public string SenderName { get; private set; } = string.Empty; + [DataMember] + public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] + public string Subject { get; private set; } = string.Empty; + [DataMember] + public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel? model) { if (model == null) @@ -42,5 +50,6 @@ namespace BlacksmithWorkshopListImplement.Models Subject = Subject, Body = Body }; - } + public int Id => throw new NotImplementedException(); + } } diff --git a/BlacksmithWorkshop/BlacksmithListImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithListImplement/Models/Order.cs index 8364b11..3630d31 100644 --- a/BlacksmithWorkshop/BlacksmithListImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithListImplement/Models/Order.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; @@ -13,17 +14,28 @@ using BlacksmithWorkshopDataModels.Models; namespace BlacksmithWorkshopListImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int ManufactureId { get; private set; } + [DataMember] public string ManufactureName { get; private set; } = string.Empty; + [DataMember] public int ClientId { get; private set; } - public int? ImplementerId { get; private set; } - public int Count { get; private set; } + [DataMember] + public int? ImplementerId { get; private set; } + [DataMember] + public int Count { get; private set; } + [DataMember] public double Sum { get; private set; } + [DataMember] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [DataMember] public DateTime DateCreate { get; set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; set; } public static Order? Create(OrderBindingModel? model) { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/BackUpLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..c70f1fd --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,99 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.StorageContracts; +using BlacksmithWorkshopDataModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopBusinessLogic.BusinessLogics +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + private readonly IBackUpInfo _backUpInfo; + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + public void CreateBackUp(BackUpSaveBinidngModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + _logger.LogDebug("Delete archive"); + string fileName = $"{model.FolderName}.zip"; + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + _logger.LogDebug("Find {count} types", types.Length); + foreach (var type in types) + { + if (type.IsInterface && type.GetInterface(typeIId.Name) != null) + { + var modelType = _backUpInfo.GetTypeByModelInterface(type.Name); + if (modelType == null) + { + throw new InvalidOperationException($"Не найден класс-модель для {type.Name}"); + } + _logger.LogDebug("Call SaveToFile method for {name} type", type.Name); + // вызываем метод на выполнение + method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName }); + } + } + _logger.LogDebug("Create zip and remove folder"); + // архивируем + ZipFile.CreateFromDirectory(model.FolderName, fileName); + // удаляем папку + dirInfo.Delete(true); + } + catch (Exception) + { + throw; + } + } + private void SaveToFile(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + return; + } + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate); + jsonFormatter.WriteObject(fs, records); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..110d52b --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public string Title { get; private set; } + public bool Visible { get; private set; } + public int Width { get; private set; } + public GridViewAutoSize GridViewAutoSize { get; private set; } + public bool IsUseAutoSize { get; private set; } + public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSise.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSise.cs new file mode 100644 index 0000000..4dc72c3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/Attributes/GridViewAutoSise.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + None = 1, + ColumnHeader = 2, + AllCellsExceptHeader = 4, + AllCells = 6, + DisplayedCellsExceptHeader = 8, + DisplayedCells = 10, + Fill = 16 + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..01c9bd9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs index d1d449a..e779366 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MessageInfoBindingModel.cs @@ -15,5 +15,6 @@ namespace BlacksmithWorkshopContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } - } + public int Id => throw new NotImplementedException(); + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj index 0a3442d..ec22d7f 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BlacksmithWorkshopContracts.csproj @@ -10,6 +10,9 @@ + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..02be40d --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using BlacksmithWorkshopContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..ef2e0f3 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/DependencyManager.cs @@ -0,0 +1,59 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + private DependencyManager() + { + _dependencyManager = new UnityDependencyContainer(); + } + public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } } + /// + /// Иницализация библиотек, в которых идут установки зависомстей + /// + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + // регистрируем зависимости + ext.RegisterServices(); + } + /// + /// Регистрация логгера + /// + /// + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + /// + /// Получение класса со всеми зависмостями + /// + /// + /// + public T Resolve() => _dependencyManager.Resolve(); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..d0ec9fb --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IDependencyContainer.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..29abb06 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..032a2e2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,56 @@ +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 BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..46723f2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..12826c9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,38 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Unity.Microsoft.Logging; +using Unity; + +namespace BlacksmithWorkshopContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + + } + public T Resolve() + { + return _container.Resolve(); + } + void IDependencyContainer.RegisterType(bool isSingle) + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/StorageContracts/IBackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StorageContracts/IBackUpInfo.cs new file mode 100644 index 0000000..cfeaf15 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/StorageContracts/IBackUpInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopContracts.StorageContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs index bfdc6d1..2fffe80 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,12 +11,13 @@ namespace BlacksmithWorkshopContracts.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/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ComponentViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ComponentViewModel.cs index e9bacd4..8965998 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ComponentViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ComponentViewModel.cs @@ -5,15 +5,17 @@ using System.Text; using System.Threading.Tasks; using System.ComponentModel; using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; namespace BlacksmithWorkshopContracts.ViewModels { public class ComponentViewModel : IComponentModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название компонента")] + [Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public double Cost { get; set; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs index a3da2f8..be50e82 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -13,14 +14,15 @@ namespace BlacksmithWorkshopContracts.ViewModels /// public class ImplementerViewModel : IImplementerModel { - public int Id { get; set; } - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] - public int WorkExperience { get; set; } - [DisplayName("Квалификация")] - public int Qualification { get; set; } + [Column(visible: false)] + public int Id { get; set; } + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "Пароль", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Password { get; set; } = string.Empty; + [Column(title: "Стаж работы", width: 150)] + public int WorkExperience { get; set; } + [Column(title: "Квалификация", width: 150)] + public int Qualification { get; set; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs index 742f441..f0b6463 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/ManufactureViewModel.cs @@ -5,16 +5,19 @@ using System.Text; using System.Threading.Tasks; using System.ComponentModel; using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; namespace BlacksmithWorkshopContracts.ViewModels { public class ManufactureViewModel : IManufactureModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название изделия")] + [Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ManufactureName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Price { get; set; } + [Column(visible: false)] public Dictionary ManufactureComponents { get; diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs index 73112be..7feec8e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; +using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,17 +9,21 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopContracts.ViewModels { - public class MessageInfoViewModel : IMessageInfoModel + public class MessageInfoViewModel : IMessageInfoModel { - public string MessageId { get; set; } = string.Empty; + [Column(visible: false)] + public string MessageId { get; set; } = string.Empty; + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] - public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата письма")] - public DateTime DateDelivery { get; set; } - [DisplayName("Заголовок")] - public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] - public string Body { get; set; } = string.Empty; - } + [Column(title: "Отправитель", width: 150)] + public string SenderName { get; set; } = string.Empty; + [Column(title: "Дата письма", width: 150)] + public DateTime DateDelivery { get; set; } + [Column(title: "Заголовок", width: 150)] + public string Subject { get; set; } = string.Empty; + [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Body { get; set; } = string.Empty; + [Column(visible: false)] + public int Id => throw new NotImplementedException(); + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs index dd42120..ea1de12 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopContracts/ViewModels/OrderViewModel.cs @@ -7,31 +7,35 @@ using System.Threading.Tasks; using BlacksmithWorkshopDataModels.Enums; using System.ComponentModel; using BlacksmithWorkshopDataModels.Models; +using BlacksmithWorkshopContracts.Attributes; namespace BlacksmithWorkshopContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(title: "Номер", width: 100)] public int Id { get; set; } + [Column(visible: false)] public int ManufactureId { get; set; } - [DisplayName("Изделие")] + [Column(title: "Изделие", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ManufactureName { get; set; } = string.Empty; + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("Клиент")] + [Column(title: "Клиент", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ClientFIO { get; set; } = string.Empty; - public int? ImplementerId { get; set; } - [DisplayName("ФИО исполнителя")] - public string? ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + [Column(visible: false)] + public int? ImplementerId { get; set; } + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string? ImplementerFIO { get; set; } = string.Empty; + [Column(title: "Количество", width: 150)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 150)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 150)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 150)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 150)] public DateTime? DateImplement { get; set; } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs index bd28f75..5a343af 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDataModels/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } int? ClientId { get; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj index 592c18e..7bc72e2 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/BlacksmithWorkshopDatabaseImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DatabaseImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..fa46d00 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,26 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StorageContracts; +using BlacksmithWorkshopDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement +{ + 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/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..6da0590 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,31 @@ +using BlacksmithWorkshopContracts.StorageContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new BlacksmithWorkshopDatabase(); + 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/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20230504000559_WithMessageInfo.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20230504000559_WithMessageInfo.Designer.cs deleted file mode 100644 index 5072774..0000000 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20230504000559_WithMessageInfo.Designer.cs +++ /dev/null @@ -1,296 +0,0 @@ -// -using System; -using BlacksmithWorkshopDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace BlacksmithWorkshopDatabaseImplement.Migrations -{ - [DbContext(typeof(BlacksmithWorkshopDatabase))] - [Migration("20230504000559_WithMessageInfo")] - partial class WithMessageInfo - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.5") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ClientFIO") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Email") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Password") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.HasKey("Id"); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Cost") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Components"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ImplementerFIO") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Password") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Qualification") - .HasColumnType("int"); - - b.Property("WorkExperience") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.ToTable("Implementers"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ManufactureName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Price") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Manufactures"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => - { - b.Property("MessageId") - .HasColumnType("nvarchar(450)"); - - b.Property("Body") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("ClientId") - .HasColumnType("int"); - - b.Property("DateDelivery") - .HasColumnType("datetime2"); - - b.Property("SenderName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Subject") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.HasKey("MessageId"); - - b.HasIndex("ClientId"); - - b.ToTable("MessageInfos"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ClientId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("ImplementerId") - .HasColumnType("int"); - - b.Property("ManufactureId") - .HasColumnType("int"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.HasIndex("ImplementerId"); - - b.HasIndex("ManufactureId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component") - .WithMany("ManufactureComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Components") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany() - .HasForeignKey("ClientId"); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b => - { - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer") - .WithMany("Orders") - .HasForeignKey("ImplementerId"); - - b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture") - .WithMany("Orders") - .HasForeignKey("ManufactureId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - - b.Navigation("Implementer"); - - b.Navigation("Manufacture"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b => - { - b.Navigation("ManufactureComponents"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs index ea9c699..bd113a6 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Client.cs @@ -8,17 +8,23 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ClientFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Email { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Component.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Component.cs index cc61a50..5d5778e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Component.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Component.cs @@ -3,15 +3,20 @@ using BlacksmithWorkshopContracts.ViewModels; using BlacksmithWorkshopDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } [Required] + [DataMember] public string ComponentName { get; private set; } = string.Empty; [Required] + [DataMember] public double Cost { get; set; } [ForeignKey("ComponentId")] public virtual List ManufactureComponents { get; set; } = new(); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs index 5291348..57c5b1b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Implementer.cs @@ -7,20 +7,28 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; +using BlacksmithWorkshopDataModels.Models; namespace BlacksmithWorkshopDatabaseImplement.Models { - public class Implementer - { - public int Id { get; private set; } + [DataContract] + public class Implementer : IImplementerModel + { + [DataMember] + public int Id { get; private set; } [Required] - public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] + public string ImplementerFIO { get; private set; } = string.Empty; [Required] - public string Password { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; [Required] - public int WorkExperience { get; private set; } + [DataMember] + public int WorkExperience { get; private set; } [Required] - public int Qualification { get; private set; } + [DataMember] + public int Qualification { get; private set; } [ForeignKey("ImplementerId")] public virtual List Orders { get; set; } = new(); public static Implementer? Create(ImplementerBindingModel model) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs index 08ed6ec..a778b44 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Manufacture.cs @@ -3,14 +3,20 @@ using BlacksmithWorkshopContracts.ViewModels; using BlacksmithWorkshopDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; + namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Manufacture : IManufactureModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ManufactureName { get; set; } = string.Empty; [Required] + [DataMember] public double Price { get; set; } private Dictionary? _manufactureComponents = null; [NotMapped] diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs index 3b8596f..9b75275 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/MessageInfo.cs @@ -4,25 +4,36 @@ using BlacksmithWorkshopDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { - [Key] - public string MessageId { get; set; } = string.Empty; - public int? ClientId { get; set; } + [NotMapped] + public int Id => throw new NotImplementedException(); + [Key] + [DataMember] + public string MessageId { get; set; } = string.Empty; + [DataMember] + public int? ClientId { get; set; } [Required] - public string SenderName { get; set; } = string.Empty; + [DataMember] + public string SenderName { get; set; } = string.Empty; [Required] - public DateTime DateDelivery { get; set; } = DateTime.Now; + [DataMember] + public DateTime DateDelivery { get; set; } = DateTime.Now; [Required] - public string Subject { get; set; } = string.Empty; + [DataMember] + public string Subject { get; set; } = string.Empty; [Required] - public string Body { get; set; } = string.Empty; + [DataMember] + public string Body { get; set; } = string.Empty; public virtual Client? Client { get; set; } public static MessageInfo? Create(MessageInfoBindingModel? model) { @@ -49,5 +60,5 @@ namespace BlacksmithWorkshopDatabaseImplement.Models Subject = Subject, Body = Body }; - } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs index 0cdd85e..7701ae9 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Models/Order.cs @@ -7,26 +7,36 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace BlacksmithWorkshopDatabaseImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public int ManufactureId { get; set; } [Required] + [DataMember] public int ClientId { get; set; } - public int? ImplementerId { get; set; } + [DataMember] + public int? ImplementerId { get; set; } [Required] + [DataMember] public int Count { get; set; } [Required] + [DataMember] public double Sum { get; set; } [Required] + [DataMember] public OrderStatus Status { get; set; } [Required] + [DataMember] public DateTime DateCreate { get; set; } public DateTime? DateImplement { get; set; } public virtual Manufacture Manufacture { get; set; } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj index b65badc..d1597ab 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/BlacksmithWorkshopFileImplement.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..8bb6798 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/FileImplementationExtension.cs @@ -0,0 +1,26 @@ +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopContracts.StorageContracts; +using BlacksmithWorkshopFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement +{ + public class FileImplementationExtension : IImplementationExtension + { + public int Priority => 1; + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..738f591 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,34 @@ +using BlacksmithWorkshopContracts.StorageContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + // Получаем значения из singleton-объекта универсального свойства содержащее тип T + var source = DataFileSingleton.GetInstance(); + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + return null; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs index 939c264..81c5a49 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Client.cs @@ -4,17 +4,23 @@ using BlacksmithWorkshopDataModels.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 BlacksmithWorkshopFileImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ClientFIO { get; private set; } = string.Empty; + [DataMember] public string Email { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel? model) { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Component.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Component.cs index 8e02925..fa5131d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Component.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Component.cs @@ -8,13 +8,18 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.ViewModels; using BlacksmithWorkshopDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace BlacksmithWorkshopFileImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ComponentName { get; private set; } = string.Empty; + [DataMember] public double Cost { get; set; } public static Component? Create(ComponentBindingModel model) { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs index ede4368..49e2925 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Implementer.cs @@ -4,19 +4,26 @@ using BlacksmithWorkshopDataModels.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 BlacksmithWorkshopFileImplement.Models { - public class Implementer : IImplementerModel + [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; private set; } + [DataMember] + public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; + [DataMember] + public int WorkExperience { get; private set; } + [DataMember] + public int Qualification { get; private set; } public static Implementer? Create(ImplementerBindingModel? model) { if (model == null) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs index 7db4b4f..ec3a3bc 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Manufacture.cs @@ -8,13 +8,18 @@ using System.Xml.Linq; using BlacksmithWorkshopDataModels.Models; using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.ViewModels; +using System.Runtime.Serialization; namespace BlacksmithWorkshopFileImplement.Models { + [DataContract] public class Manufacture : IManufactureModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ManufactureName { get; private set; } = string.Empty; + [DataMember] public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _manufactureComponents = null; diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs index 3ef9c6e..efcac67 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/MessageInfo.cs @@ -4,20 +4,28 @@ using BlacksmithWorkshopDataModels.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 BlacksmithWorkshopFileImplement.Models { - public class MessageInfo : IMessageInfoModel + [DataContract] + public class MessageInfo : IMessageInfoModel { - public string MessageId { get; set; } = string.Empty; - public int? ClientId { get; set; } - public string SenderName { get; set; } = string.Empty; - public DateTime DateDelivery { get; set; } = DateTime.Now; - public string Subject { get; set; } = string.Empty; - public string Body { get; set; } = string.Empty; + [DataMember] + public string MessageId { get; set; } = string.Empty; + [DataMember] + public int? ClientId { get; set; } + [DataMember] + public string SenderName { get; set; } = string.Empty; + [DataMember] + public DateTime DateDelivery { get; set; } = DateTime.Now; + [DataMember] + public string Subject { get; set; } = string.Empty; + [DataMember] + public string Body { get; set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) @@ -66,5 +74,7 @@ namespace BlacksmithWorkshopFileImplement.Models new XElement("DateDelivery", DateDelivery), new XElement("Subject", Subject), new XElement("Body", Body)); - } + + public int Id => throw new NotImplementedException(); + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs index 718554c..963774b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopFileImplement/Models/Order.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; @@ -12,16 +13,26 @@ using BlacksmithWorkshopDataModels.Models; namespace BlacksmithWorkshopFileImplement.Models { + [DataContract] public class Order : IOrderModel { + [DataMember] public int Id { get; private set; } + [DataMember] public int ManufactureId { get; private set; } + [DataMember] public int ClientId { get; private set; } - public string ManufactureName { get; private set; } = string.Empty; + [DataMember] + public string ManufactureName { get; private set; } = string.Empty; + [DataMember] public int Count { get; private set; } + [DataMember] public double Sum { get; private set; } + [DataMember] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; private set; } public static Order? Create(OrderBindingModel? model) { diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs new file mode 100644 index 0000000..6e45513 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using BlacksmithWorkshopContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlacksmithWorkshopView +{ + internal static class DataGridViewExtension + { + public static void FillAndConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + // ищем нужный нам атрибут + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs index df6484c..bf5d47d 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormClients.cs @@ -31,13 +31,7 @@ namespace BlacksmithWorkshopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormComponents.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormComponents.cs index 24f27fc..8e33252 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormComponents.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormComponents.cs @@ -12,6 +12,7 @@ using Microsoft.Extensions.Logging; using BlacksmithWorkshopView; using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; namespace BlacksmithWorkshopView { @@ -33,14 +34,7 @@ namespace BlacksmithWorkshopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) @@ -52,20 +46,17 @@ namespace BlacksmithWorkshopView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); + var service = DependencyManager.Instance.Resolve(); if (service is FormComponent form) { form.Id = diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs index b2a01e8..fd0f309 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormCreateOrder.cs @@ -23,7 +23,6 @@ namespace BlacksmithWorkshopView private readonly IManufactureLogic _logicM; private readonly IOrderLogic _logicO; private readonly IClientLogic _logicC; - private List? _list; public FormCreateOrder(ILogger logger, IManufactureLogic logicM, IOrderLogic logicO, IClientLogic logicC) { InitializeComponent(); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs index f06719d..3b57fc4 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormImplementers.cs @@ -1,5 +1,6 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -31,16 +32,7 @@ namespace BlacksmithWorkshopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Password"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["WorkExperience"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Qualification"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) @@ -51,27 +43,21 @@ namespace BlacksmithWorkshopView } 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(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + 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/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs index 594be5f..e6125e4 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.Designer.cs @@ -39,11 +39,12 @@ componentsManufactureToolStripMenuItem = new ToolStripMenuItem(); orderListToolStripMenuItem = new ToolStripMenuItem(); workToolStripMenuItem = new ToolStripMenuItem(); + messagesToolStripMenuItem = new ToolStripMenuItem(); + backupToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - messagesToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -51,11 +52,11 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { guideToolStripMenuItem, отчетыToolStripMenuItem, workToolStripMenuItem, messagesToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { guideToolStripMenuItem, отчетыToolStripMenuItem, workToolStripMenuItem, messagesToolStripMenuItem, backupToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(6, 3, 0, 3); - menuStrip1.Size = new Size(1313, 30); + menuStrip1.Size = new Size(1470, 30); menuStrip1.TabIndex = 0; menuStrip1.Text = "menuStrip1"; // @@ -129,22 +130,38 @@ workToolStripMenuItem.Text = "Запуск работ"; workToolStripMenuItem.Click += WorkStartToolStripMenuItem_Click; // + // messagesToolStripMenuItem + // + messagesToolStripMenuItem.Name = "messagesToolStripMenuItem"; + messagesToolStripMenuItem.Size = new Size(77, 24); + messagesToolStripMenuItem.Text = "Письма"; + messagesToolStripMenuItem.Click += messagesToolStripMenuItem_Click; + // + // backupToolStripMenuItem + // + backupToolStripMenuItem.Name = "backupToolStripMenuItem"; + backupToolStripMenuItem.Size = new Size(122, 24); + backupToolStripMenuItem.Text = "Создать бэкап"; + backupToolStripMenuItem.Click += backupToolStripMenuItem_Click; + // // dataGridView // dataGridView.AllowUserToAddRows = false; dataGridView.AllowUserToDeleteRows = false; + dataGridView.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.Location = new Point(11, 31); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(977, 381); + dataGridView.Size = new Size(1149, 381); dataGridView.TabIndex = 1; // // buttonCreateOrder // - buttonCreateOrder.Location = new Point(1026, 71); + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.Location = new Point(1183, 71); buttonCreateOrder.Name = "buttonCreateOrder"; buttonCreateOrder.Size = new Size(247, 29); buttonCreateOrder.TabIndex = 2; @@ -154,7 +171,8 @@ // // buttonIssuedOrder // - buttonIssuedOrder.Location = new Point(1026, 127); + buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonIssuedOrder.Location = new Point(1183, 127); buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Size = new Size(247, 29); buttonIssuedOrder.TabIndex = 5; @@ -164,7 +182,8 @@ // // buttonRef // - buttonRef.Location = new Point(1026, 181); + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.Location = new Point(1183, 181); buttonRef.Name = "buttonRef"; buttonRef.Size = new Size(247, 29); buttonRef.TabIndex = 6; @@ -172,18 +191,11 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click; // - // messagesToolStripMenuItem - // - messagesToolStripMenuItem.Name = "messagesToolStripMenuItem"; - messagesToolStripMenuItem.Size = new Size(77, 24); - messagesToolStripMenuItem.Text = "Письма"; - messagesToolStripMenuItem.Click += messagesToolStripMenuItem_Click; - // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1313, 425); + ClientSize = new Size(1470, 425); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); Controls.Add(buttonCreateOrder); @@ -218,5 +230,6 @@ private ToolStripMenuItem implemntersToolStripMenuItem; private ToolStripMenuItem workToolStripMenuItem; private ToolStripMenuItem messagesToolStripMenuItem; + private ToolStripMenuItem backupToolStripMenuItem; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs index b43eade..8505659 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMain.cs @@ -13,6 +13,8 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopDataModels.Models; using BlacksmithWorkshopDataModels.Enums; +using BlacksmithWorkshopContracts.DI; +using BlacksmithWorkshopBusinessLogic.BusinessLogics; namespace BlacksmithWorkshopView { @@ -22,13 +24,15 @@ namespace BlacksmithWorkshopView private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + private readonly IBackUpLogic _backUpLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) { @@ -38,15 +42,7 @@ namespace BlacksmithWorkshopView { try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ManufactureId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["DateImplement"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -57,36 +53,24 @@ namespace BlacksmithWorkshopView } 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 GoodsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormManufacturies)); - if (service is FormManufacturies form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private void ButtonIssuedOrder_Click(object sender, EventArgs e) { @@ -129,39 +113,51 @@ namespace BlacksmithWorkshopView } private void ComponentManufacturesToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportManufactureComponents)); - if (service is FormReportManufactureComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void OrderListToolStripMenuItem_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 ImplemntersToolStripMenuItem_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 WorkStartToolStripMenuItem_Click(object sender, EventArgs e) { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + _workProcess.DoWork((DependencyManager.Instance.Resolve() as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void messagesToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMessages)); - if (service is FormMessages form) + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void backupToolStripMenuItem_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/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs index 57c591d..c34afb7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacture.cs @@ -1,5 +1,6 @@ using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; using BlacksmithWorkshopContracts.SearchModels; using BlacksmithWorkshopDataModels.Models; using Microsoft.Extensions.Logging; @@ -21,58 +22,56 @@ namespace BlacksmithWorkshopView _logic = logic; _ManufactureComponents = new Dictionary(); } - private void FormManufacture_Load(object sender, EventArgs e) - { - if (_id.HasValue) + private void FormManufacture_Load(object sender, EventArgs e) { - _logger.LogInformation("Загрузка изделия"); + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); + try + { + var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxName.Text = view.ManufactureName; + textBoxPrice.Text = view.Price.ToString(); + _ManufactureComponents = view.ManufactureComponents ?? new + Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void LoadData() + { + _logger.LogInformation("Загрузка компонент изделия"); try { - var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value }); - if (view != null) + if (_ManufactureComponents != null) { - textBoxName.Text = view.ManufactureName; - textBoxPrice.Text = view.Price.ToString(); - _ManufactureComponents = view.ManufactureComponents ?? new - Dictionary(); - LoadData(); + dataGridView.Rows.Clear(); + foreach (var pc in _ManufactureComponents) + { + dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 }); + } + textBoxPrice.Text = CalcPrice().ToString(); } } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки изделия"); + _logger.LogError(ex, "Ошибка загрузки компонент изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - } - private void LoadData() - { - _logger.LogInformation("Загрузка компонент изделия"); - try - { - if (_ManufactureComponents != null) - { - dataGridView.Rows.Clear(); - foreach (var pc in _ManufactureComponents) - { - 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(FormManufactureComponent)); - if (service is FormManufactureComponent form) + private void ButtonAdd_Click(object sender, EventArgs e) { + var form = DependencyManager.Instance.Resolve(); if (form.ShowDialog() == DialogResult.OK) { if (form.ComponentModel == null) @@ -91,14 +90,11 @@ namespace BlacksmithWorkshopView LoadData(); } } - } - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) + private void ButtonUpd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormManufactureComponent)); - if (service is FormManufactureComponent form) + 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 = _ManufactureComponents[id].Item2; @@ -114,87 +110,86 @@ namespace BlacksmithWorkshopView } } } - } - private void ButtonDel_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) + private void ButtonDel_Click(object sender, EventArgs e) { - if (MessageBox.Show("Удалить запись?", "Вопрос", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (dataGridView.SelectedRows.Count == 1) { - try + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _logger.LogInformation("Удаление компонента: {ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); - _ManufactureComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + try + { + _logger.LogInformation("Удаление компонента: {ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _ManufactureComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - LoadData(); } } - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void ButtonSave_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxName.Text)) + private void ButtonRef_Click(object sender, EventArgs e) { - MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + LoadData(); } - if (string.IsNullOrEmpty(textBoxPrice.Text)) + private void ButtonSave_Click(object sender, EventArgs e) { - MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (_ManufactureComponents == null || _ManufactureComponents.Count == 0) - { - MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Сохранение изделия"); - try - { - var model = new ManufactureBindingModel + if (string.IsNullOrEmpty(textBoxName.Text)) { - Id = _id ?? 0, - ManufactureName = textBoxName.Text, - Price = Convert.ToDouble(textBoxPrice.Text), - ManufactureComponents = _ManufactureComponents - }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (_ManufactureComponents == null || _ManufactureComponents.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение изделия"); + try + { + var model = new ManufactureBindingModel + { + Id = _id ?? 0, + ManufactureName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + ManufactureComponents = _ManufactureComponents + }; + 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 ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; Close(); } - catch (Exception ex) + private double CalcPrice() { - _logger.LogError(ex, "Ошибка сохранения изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + double price = 0; + foreach (var elem in _ManufactureComponents) + { + 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 _ManufactureComponents) - { - price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); - } - return Math.Round(price * 1.1, 2); - } -} } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacturies.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacturies.cs index be146f1..2d98cf0 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacturies.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormManufacturies.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using Microsoft.Extensions.Logging; using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.DI; namespace BlacksmithWorkshopView { @@ -31,15 +32,7 @@ namespace BlacksmithWorkshopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ManufactureComponents"].Visible = false; - dataGridView.Columns["ManufactureName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка изделий"); } catch (Exception ex) @@ -50,27 +43,21 @@ namespace BlacksmithWorkshopView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); - if (service is FormManufacture form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormManufacture)); - if (service is FormManufacture 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/BlacksmithWorkshop/BlacksmithWorkshopView/FormMessages.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMessages.cs index 8bc5944..776afa9 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/FormMessages.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/FormMessages.cs @@ -30,14 +30,7 @@ namespace BlacksmithWorkshopView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка сообщений"); } catch (Exception ex) diff --git a/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs index f954cf5..c18cd9c 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopView/Program.cs @@ -10,13 +10,12 @@ using NLog.Extensions.Logging; using ManufactureCompanyBusinessLogic.BusinessLogics; using BlacksmithWorkshopBusinessLogic.MailWorker; using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.DI; namespace BlacksmithWorkshopView { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -26,13 +25,11 @@ namespace BlacksmithWorkshopView // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); - try + InitDependency(); + try { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, @@ -46,52 +43,51 @@ namespace BlacksmithWorkshopView } catch (Exception ex) { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, "Ошибка работы с почтой"); + var logger = DependencyManager.Instance.Resolve(); + logger?.LogError(ex, "Ошибка работы с почтой"); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); - } + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); + } } \ No newline at end of file