From 5b47a8d77807f55d74f438fdacea73771fdbf44f Mon Sep 17 00:00:00 2001 From: m1aksim1 Date: Mon, 8 May 2023 01:13:26 +0400 Subject: [PATCH] =?UTF-8?q?=D1=83=20=D0=BC=D0=B5=D0=BD=D1=8F=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B4=D0=B5=D0=B6=D1=80=D0=BA=D0=B0=20=D0=B2=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B7=D0=B2=D0=B8=D1=82=D0=B8=D0=B8(8=20=D0=B1=D0=B0?= =?UTF-8?q?=D0=B7=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + .../BackUpInfo.cs | 34 ++ .../Client.cs | 18 +- .../Component.cs | 13 +- .../FileImplementationExtension.cs | 23 + .../Implementer.cs | 7 + .../MessageInfo.cs | 12 +- .../Order.cs | 27 +- .../Package.cs | 16 +- .../SoftwareInstallationFileImplement.csproj | 4 + .../BusinessLogic/BackUpLogic.cs | 103 +++++ .../BusinessLogic/ReportLogic.cs | 12 +- .../Attributes/ColumnAttribute.cs | 31 ++ .../Attributes/GridViewAutoSize.cs | 27 ++ .../BindingModels/BackUpSaveBinidngModel.cs | 13 + .../BindingModels/MessageInfoBindingModel.cs | 2 + .../BusinessLogicsContracts/IBackUpLogic.cs | 14 + .../BusinessLogicsContracts/IReportLogic.cs | 2 +- .../DI/DependencyManager.cs | 66 +++ .../DI/IDependencyContainer.cs | 35 ++ .../DI/IImplementationExtension.cs | 17 + .../DI/ServiceDependencyContainer.cs | 57 +++ .../DI/ServiceProviderLoader.cs | 55 +++ .../DI/UnityDependencyContainer.cs | 40 ++ .../SoftwareInstallationContracts.csproj | 8 + .../StoragesContracts/IBackUpInfo.cs | 14 + .../ViewModels/ClientViewModel.cs | 16 +- .../ViewModels/ComponentViewModel.cs | 12 +- .../ViewModels/ImplementerViewModel.cs | 11 +- .../ViewModels/MessageInfoViewModel.cs | 16 +- .../ViewModels/OrderViewModel.cs | 42 +- .../ViewModels/PackageViewModel.cs | 15 +- .../IMessageInfoModel.cs | 2 +- .../BackUpInfo.cs | 31 ++ .../Client.cs | 16 +- .../Component.cs | 13 +- .../DatabaseImplementationExtension.cs | 23 + .../Implementer.cs | 7 + .../MessageInfo.cs | 5 +- .../Order.cs | 28 +- .../Package.cs | 16 +- ...ftwareInstallationDatabaseImplement.csproj | 4 + .../BackUpInfo.cs | 22 + .../ListImplementationExtension.cs | 28 ++ .../MessageInfo.cs | 5 +- .../SoftwareInstallationListImplement.csproj | 4 + .../DataGridViewExtension.cs | 46 ++ .../FormComponents.cs | 52 +-- .../FormMain.Designer.cs | 433 +++++++++--------- .../SoftwareInstallationView/FormMain.cs | 398 ++++++++-------- .../SoftwareInstallationView/FormPackage.cs | 81 ++-- .../SoftwareInstallationView/FormPackages.cs | 122 +++-- .../FormViewClients.cs | 10 +- .../FormViewImplementers.cs | 29 +- .../SoftwareInstallationView/FormViewMail.cs | 9 +- .../SoftwareInstallationView/Program.cs | 169 ++++--- 56 files changed, 1541 insertions(+), 777 deletions(-) create mode 100644 SoftwareInstallation/SoftWareInstallationFileImplement/BackUpInfo.cs create mode 100644 SoftwareInstallation/SoftWareInstallationFileImplement/FileImplementationExtension.cs create mode 100644 SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/BackUpLogic.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/Attributes/ColumnAttribute.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/Attributes/GridViewAutoSize.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BindingModels/BackUpSaveBinidngModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/DependencyManager.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/IDependencyContainer.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/IImplementationExtension.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceDependencyContainer.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceProviderLoader.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/DI/UnityDependencyContainer.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/BackUpInfo.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/DatabaseImplementationExtension.cs create mode 100644 SoftwareInstallation/SoftwareInstallationListImplement/BackUpInfo.cs create mode 100644 SoftwareInstallation/SoftwareInstallationListImplement/ListImplementationExtension.cs create mode 100644 SoftwareInstallation/SoftwareInstallationView/DataGridViewExtension.cs diff --git a/.gitignore b/.gitignore index ca1c7a3..52737dc 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,9 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll файлы +*.dll + # Mono auto generated files mono_crash.* diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/BackUpInfo.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/BackUpInfo.cs new file mode 100644 index 0000000..0347150 --- /dev/null +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/BackUpInfo.cs @@ -0,0 +1,34 @@ +using SoftwareInstallationContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationFileImplement +{ + 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/SoftwareInstallation/SoftWareInstallationFileImplement/Client.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/Client.cs index 621515c..d297593 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/Client.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/Client.cs @@ -1,19 +1,25 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; +using System.Runtime.Serialization; using SoftwareInstallationDataModels.Models; using System.Xml.Linq; namespace SoftwareInstallationFileImplement { - public class Client : IClientModel - { - public string ClientFIO { get; private set; } = string.Empty; + [DataContract] + public class Client : IClientModel + { + [DataMember] + public string ClientFIO { get; private set; } = string.Empty; - public string Email { get; private set; } = string.Empty; + [DataMember] + public string Email { get; private set; } = string.Empty; - public string Password { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } public static Client? Create(ClientBindingModel model) { diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/Component.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/Component.cs index d115c27..4aedde9 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/Component.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/Component.cs @@ -2,14 +2,19 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace SoftwareInstallationFileImplement.Models { - public class Component : IComponentModel + [DataContract] + public class Component : IComponentModel { - public int Id { get; private set; } - public string ComponentName { get; private set; } = string.Empty; - public double Cost { get; set; } + [DataMember] + public int Id { get; private set; } + [DataMember] + public string ComponentName { get; private set; } = string.Empty; + [DataMember] + public double Cost { get; set; } public static Component? Create(ComponentBindingModel? model) { if (model == null) diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/FileImplementationExtension.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..3e44bf5 --- /dev/null +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/FileImplementationExtension.cs @@ -0,0 +1,23 @@ +using SoftwareInstallationContracts.DI; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationFileImplement.Implements; + +namespace SoftwareInstallationFileImplement +{ + 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/SoftwareInstallation/SoftWareInstallationFileImplement/Implementer.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/Implementer.cs index a565848..51c7562 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/Implementer.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/Implementer.cs @@ -2,19 +2,26 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using System.Xml.Linq; +using System.Runtime.Serialization; namespace SoftwareInstallationFileImplement { + [DataContract] public class Implementer : IImplementerModel { + [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(XElement element) diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/MessageInfo.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/MessageInfo.cs index 39a6107..321aa87 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/MessageInfo.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/MessageInfo.cs @@ -7,22 +7,30 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; +using System.Runtime.Serialization; namespace SoftwareInstallationFileImplement.Models { // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма + [DataContract] public class MessageInfo : IMessageInfoModel { + [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) @@ -77,6 +85,6 @@ namespace SoftwareInstallationFileImplement.Models new XAttribute("SenderName", SenderName), new XAttribute("DateDelivery", DateDelivery) ); + public int Id => throw new NotImplementedException(); } - -} +} \ No newline at end of file diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/Order.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/Order.cs index f6414ef..f162611 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/Order.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/Order.cs @@ -3,28 +3,39 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Enums; using System.Xml.Linq; +using System.Runtime.Serialization; namespace SoftwareInstallationFileImplement.Models { - public class Order : IOrderModel + [DataContract] + public class Order : IOrderModel { - public int PackageId { get; private set; } + [DataMember] + public int PackageId { get; private set; } - public int ClientId { get; set; } + [DataMember] + public int ClientId { get; set; } + [DataMember] public int? ImplementerId { get; set; } + [DataMember] public int Count { get; private set; } - public double Sum { get; private set; } + [DataMember] + public double Sum { get; private set; } - public OrderStatus Status { get; private set; } + [DataMember] + public OrderStatus Status { get; private set; } - public DateTime DateCreate { get; private set; } + [DataMember] + public DateTime DateCreate { get; private set; } - public DateTime? DateImplement { get; private set; } + [DataMember] + public DateTime? DateImplement { get; private set; } - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } public static Order? Create(OrderBindingModel? model) { diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/Package.cs b/SoftwareInstallation/SoftWareInstallationFileImplement/Package.cs index 82982dd..5ff0f0b 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/Package.cs +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/Package.cs @@ -1,19 +1,25 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; +using System.Runtime.Serialization; using System.Xml.Linq; namespace SoftwareInstallationFileImplement.Models { - public class Package : IPackageModel + [DataContract] + public class Package : IPackageModel { - public int Id { get; private set; } - public string PackageName { get; private set; } = string.Empty; - public double Price { get; private set; } + [DataMember] + public int Id { get; private set; } + [DataMember] + public string PackageName { get; private set; } = string.Empty; + [DataMember] + public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _packageComponents = null; - public Dictionary PackageComponents + [DataMember] + public Dictionary PackageComponents { get { diff --git a/SoftwareInstallation/SoftWareInstallationFileImplement/SoftwareInstallationFileImplement.csproj b/SoftwareInstallation/SoftWareInstallationFileImplement/SoftwareInstallationFileImplement.csproj index 3a28f9a..8b9f1ce 100644 --- a/SoftwareInstallation/SoftWareInstallationFileImplement/SoftwareInstallationFileImplement.csproj +++ b/SoftwareInstallation/SoftWareInstallationFileImplement/SoftwareInstallationFileImplement.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/BackUpLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..e7e7b77 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/BackUpLogic.cs @@ -0,0 +1,103 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationDataModels; +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 SoftwareInstallationBusinessLogic +{ + 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/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/ReportLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/ReportLogic.cs index 7d20cf9..072780c 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/ReportLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogic/ReportLogic.cs @@ -73,7 +73,7 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics /// Сохранение изделий в файл-Word /// /// - public void SaveComponentsToWordFile(ReportBindingModel model) + public void SavePackagesToWordFile(ReportBindingModel model) { _saveToWord.CreateDoc(new WordInfo { @@ -95,11 +95,11 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics PackageComponents = GetPackageComponent() }); } - /// - /// Сохранение заказов в файл-Pdf - /// - /// - public void SaveOrdersToPdfFile(ReportBindingModel model) + /// + /// Сохранение заказов в файл-Pdf + /// + /// + public void SaveOrdersToPdfFile(ReportBindingModel model) { _saveToPdf.CreateDoc(new PdfInfo { diff --git a/SoftwareInstallation/SoftwareInstallationContracts/Attributes/ColumnAttribute.cs b/SoftwareInstallation/SoftwareInstallationContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..9d74b58 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationContracts/Attributes/GridViewAutoSize.cs b/SoftwareInstallation/SoftwareInstallationContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..240b556 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/BackUpSaveBinidngModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..adaea29 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs index 8d47bc3..72962a3 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs @@ -20,5 +20,7 @@ namespace SoftwareInstallationContracts.BindingModels public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } + + public int Id => throw new NotImplementedException(); } } diff --git a/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IBackUpLogic.cs b/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..fd13048 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using SoftwareInstallationContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IReportLogic.cs b/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IReportLogic.cs index f86c8a6..c4a0916 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicsContracts/IReportLogic.cs @@ -20,7 +20,7 @@ namespace SoftwareInstallationContracts.BusinessLogicsContracts /// Сохранение компонент в файл-Word /// /// - void SaveComponentsToWordFile(ReportBindingModel model); + void SavePackagesToWordFile(ReportBindingModel model); /// /// Сохранение компонент с указаеним продуктов в файл-Excel /// diff --git a/SoftwareInstallation/SoftwareInstallationContracts/DI/DependencyManager.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..8fcd73c --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/DependencyManager.cs @@ -0,0 +1,66 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new ServiceDependencyContainer(); + } + + public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } } + + /// + /// Иницализация библиотек, в которых идут установки зависомстей + /// + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + // регистрируем зависимости + ext.RegisterServices(); + } + + /// + /// Регистрация логгера + /// + /// + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Добавление зависимости + /// + /// + /// + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + /// + /// Получение класса со всеми зависмостями + /// + /// + /// + public T Resolve() => _dependencyManager.Resolve(); + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/DI/IDependencyContainer.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..05b7175 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/IDependencyContainer.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Logging; + +namespace SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationContracts/DI/IImplementationExtension.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..65d94a3 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceDependencyContainer.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..f846fc0 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,57 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceProviderLoader.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..0fb722a --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationContracts/DI/UnityDependencyContainer.cs b/SoftwareInstallation/SoftwareInstallationContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..308ebe4 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,40 @@ +using Microsoft.Extensions.Logging; +using System.ComponentModel; +using Unity; +using Unity.Lifetime; +using Unity.Microsoft.Logging; + +namespace SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationContracts/SoftwareInstallationContracts.csproj b/SoftwareInstallation/SoftwareInstallationContracts/SoftwareInstallationContracts.csproj index 5e550d4..d914990 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/SoftwareInstallationContracts.csproj +++ b/SoftwareInstallation/SoftwareInstallationContracts/SoftwareInstallationContracts.csproj @@ -6,6 +6,14 @@ enable + + + + + + + + diff --git a/SoftwareInstallation/SoftwareInstallationContracts/StoragesContracts/IBackUpInfo.cs b/SoftwareInstallation/SoftwareInstallationContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..2507ca9 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ClientViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ClientViewModel.cs index ada9cf3..e404c7a 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ClientViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ClientViewModel.cs @@ -1,16 +1,18 @@ using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.Attributes; using System.ComponentModel; namespace SoftwareInstallationContracts.ViewModels { public class ClientViewModel : IClientModel { - public int Id { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] - public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(visible: false)] + public int Id { get; set; } + [Column("ФИО клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ClientFIO { get; set; } = string.Empty; + [Column("Логин (эл. почта)", width: 150)] + public string Email { get; set; } = string.Empty; + [Column("Пароль", width: 150)] + public string Password { get; set; } = string.Empty; } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs index 4deb00f..345d49a 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs @@ -1,14 +1,16 @@ using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.Attributes; using System.ComponentModel; namespace SoftwareInstallationContracts.ViewModels { public class ComponentViewModel : IComponentModel { - public int Id { get; set; } - [DisplayName("Название компонента")] - public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Cost { get; set; } + [Column(visible: false)] + public int Id { get; set; } + [Column("Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ComponentName { get; set; } = string.Empty; + [Column("Цена", width: 80)] + public double Cost { get; set; } } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ImplementerViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ImplementerViewModel.cs index 6675473..a637230 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ImplementerViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/ImplementerViewModel.cs @@ -1,5 +1,7 @@ using SoftwareInstallationDataModels.Models; +using SoftwareInstallationDataModels; using System.ComponentModel; +using SoftwareInstallationContracts.Attributes; namespace SoftwareInstallationContracts.ViewModels { @@ -8,18 +10,19 @@ namespace SoftwareInstallationContracts.ViewModels /// public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column("Пароль", width: 150)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] + [Column("Стаж работы", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column("Квалификация", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] public int Qualification { get; set; } } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs index 12aa517..00b55cd 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ using SoftwareInstallationDataModels; +using SoftwareInstallationContracts.Attributes; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace SoftwareInstallationContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; - + + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] + [Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата письма")] + [Column("Дата письма", width: 100)] public DateTime DateDelivery { get; set; } - [DisplayName("Заголовок")] + [Column("Заголовок", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Body { get; set; } = string.Empty; + + [Column(visible: false)] + public int Id => throw new NotImplementedException(); } } diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs index 89db922..692620e 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs @@ -1,5 +1,6 @@ using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.Attributes; using System.ComponentModel; @@ -7,26 +8,29 @@ namespace SoftwareInstallationContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] - public int Id { get; set; } - public int PackageId { get; set; } - public int ClientId { get; set; } + [Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] + public int Id { get; set; } + [Column(visible: false)] + public int PackageId { get; set; } + [Column(visible: false)] + public int ClientId { get; set; } + [Column(visible: false)] public int? ImplementerId { get; set; } - [DisplayName("Фамилия клиента")] - public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Фамилия исполнителя")] + [Column("Фамилия клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string ClientFIO { get; set; } = string.Empty; + [Column("Фамилия исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Изделие")] - public string PackageName { get; set; } = string.Empty; - [DisplayName("Количество")] - public int Count { get; set; } - [DisplayName("Сумма")] - public double Sum { get; set; } - [DisplayName("Статус")] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] - public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] - public DateTime? DateImplement { get; set; } + [Column("Изделие", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] + public string PackageName { get; set; } = string.Empty; + [Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] + public int Count { get; set; } + [Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] + public double Sum { get; set; } + [Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [Column("Дата создания", width: 100)] + public DateTime DateCreate { get; set; } = DateTime.Now; + [Column("Дата выполнения", width: 100)] + public DateTime? DateImplement { get; set; } } } diff --git a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs index ac62c88..2ad2061 100644 --- a/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs +++ b/SoftwareInstallation/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs @@ -1,16 +1,19 @@ using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.Attributes; using System.ComponentModel; namespace SoftwareInstallationContracts.ViewModels { public class PackageViewModel : IPackageModel { - public int Id { get; set; } - [DisplayName("Название изделия")] - public string PackageName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Price { get; set; } - public Dictionary PackageComponents + [Column(visible: false)] + public int Id { get; set; } + [Column("Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string PackageName { get; set; } = string.Empty; + [Column("Цена", width: 100)] + public double Price { get; set; } + [Column(visible: false)] + public Dictionary PackageComponents { get; set; diff --git a/SoftwareInstallation/SoftwareInstallationDataModels/IMessageInfoModel.cs b/SoftwareInstallation/SoftwareInstallationDataModels/IMessageInfoModel.cs index 46a8d89..636034d 100644 --- a/SoftwareInstallation/SoftwareInstallationDataModels/IMessageInfoModel.cs +++ b/SoftwareInstallation/SoftwareInstallationDataModels/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace SoftwareInstallationDataModels { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/BackUpInfo.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/BackUpInfo.cs new file mode 100644 index 0000000..f48af10 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/BackUpInfo.cs @@ -0,0 +1,31 @@ +using SoftwareInstallationContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationDatabaseImplement +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new SoftwareInstallationDatabase(); + 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/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Client.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Client.cs index 670e66b..a7cfd10 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Client.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Client.cs @@ -3,22 +3,28 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { - public class Client : IClientModel + [DataContract] + public class Client : IClientModel { [Required] - public string ClientFIO { get; private set; } = string.Empty; + [DataMember] + public string ClientFIO { get; private set; } = string.Empty; [Required] - public string Email { get; private set; } = string.Empty; + [DataMember] + public string Email { get; private set; } = string.Empty; [Required] - public string Password { get; private set; } = string.Empty; + [DataMember] + public string Password { get; private set; } = string.Empty; - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Component.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Component.cs index 7096a80..6fe9a47 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Component.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Component.cs @@ -3,16 +3,21 @@ using SoftwareInstallationDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SoftwareInstallationContracts.ViewModels; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { - public class Component : IComponentModel + [DataContract] + public class Component : IComponentModel { - public int Id { get; private set; } + [DataMember] + public int Id { get; private set; } [Required] - public string ComponentName { get; private set; } = string.Empty; + [DataMember] + public string ComponentName { get; private set; } = string.Empty; [Required] - public double Cost { get; set; } + [DataMember] + public double Cost { get; set; } [ForeignKey("ComponentId")] public virtual List PackageComponents { get; set; } = new(); diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/DatabaseImplementationExtension.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/DatabaseImplementationExtension.cs new file mode 100644 index 0000000..a5bf253 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/DatabaseImplementationExtension.cs @@ -0,0 +1,23 @@ +using SoftwareInstallationContracts.DI; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationDatabaseImplement.Implements; + +namespace SoftwareInstallationDatabaseImplement +{ + 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/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Implementer.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Implementer.cs index 022de2a..65d8519 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Implementer.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Implementer.cs @@ -2,19 +2,26 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [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; } [ForeignKey("ImplementerId")] diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/MessageInfo.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/MessageInfo.cs index ce71a3f..e370ada 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/MessageInfo.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/MessageInfo.cs @@ -2,13 +2,16 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма + [DataContract] public class MessageInfo : IMessageInfoModel { [Key] + [DataMember] public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } @@ -49,7 +52,7 @@ namespace SoftwareInstallationDatabaseImplement.Models SenderName = SenderName, DateDelivery = DateDelivery, }; - + public int Id => throw new NotImplementedException(); } } diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Order.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Order.cs index fdff054..434545f 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Order.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Order.cs @@ -3,34 +3,44 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Models; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { - public class Order : IOrderModel + [DataContract] + public class Order : IOrderModel { public int Id { get; private set; } [Required] - public int PackageId { get; private set; } + [DataMember] + public int PackageId { get; private set; } [Required] - public int ClientId { get; private set; } - + [DataMember] + public int ClientId { get; private set; } + + [DataMember] public int? ImplementerId { get; private set; } [Required] - public int Count { get; private set; } + [DataMember] + public int Count { get; private set; } [Required] - public double Sum { get; private set; } + [DataMember] + public double Sum { get; private set; } [Required] - public OrderStatus Status { get; private set; } + [DataMember] + public OrderStatus Status { get; private set; } [Required] - public DateTime DateCreate { get; private set; } + [DataMember] + public DateTime DateCreate { get; private set; } - public DateTime? DateImplement { get; private set; } + [DataMember] + public DateTime? DateImplement { get; private set; } public Package Package { get; private set; } diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Package.cs b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Package.cs index 604fde6..29edfe3 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Package.cs +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/Package.cs @@ -3,20 +3,26 @@ using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; +using System.Runtime.Serialization; namespace SoftwareInstallationDatabaseImplement.Models { - public class Package : IPackageModel + [DataContract] + public class Package : IPackageModel { - public int Id { get; set; } + [DataMember] + public int Id { get; set; } [Required] - public string PackageName { get; set; } = string.Empty; + [DataMember] + public string PackageName { get; set; } = string.Empty; [Required] - public double Price { get; set; } + [DataMember] + public double Price { get; set; } private Dictionary? _packageComponents = null; [NotMapped] - public Dictionary PackageComponents + [DataMember] + public Dictionary PackageComponents { get { diff --git a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/SoftwareInstallationDatabaseImplement.csproj b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/SoftwareInstallationDatabaseImplement.csproj index 2893da0..48b5df7 100644 --- a/SoftwareInstallation/SoftwareInstallationDatabaseImplement/SoftwareInstallationDatabaseImplement.csproj +++ b/SoftwareInstallation/SoftwareInstallationDatabaseImplement/SoftwareInstallationDatabaseImplement.csproj @@ -25,4 +25,8 @@ + + + + diff --git a/SoftwareInstallation/SoftwareInstallationListImplement/BackUpInfo.cs b/SoftwareInstallation/SoftwareInstallationListImplement/BackUpInfo.cs new file mode 100644 index 0000000..c71e556 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationListImplement/BackUpInfo.cs @@ -0,0 +1,22 @@ +using SoftwareInstallationContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement +{ + 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/SoftwareInstallation/SoftwareInstallationListImplement/ListImplementationExtension.cs b/SoftwareInstallation/SoftwareInstallationListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..62d357b --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationListImplement/ListImplementationExtension.cs @@ -0,0 +1,28 @@ +using SoftwareInstallationContracts.DI; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement +{ + 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/SoftwareInstallation/SoftwareInstallationListImplement/MessageInfo.cs b/SoftwareInstallation/SoftwareInstallationListImplement/MessageInfo.cs index d3e5994..ff58c46 100644 --- a/SoftwareInstallation/SoftwareInstallationListImplement/MessageInfo.cs +++ b/SoftwareInstallation/SoftwareInstallationListImplement/MessageInfo.cs @@ -50,7 +50,6 @@ namespace SoftwareInstallationListImplement.Models SenderName = SenderName, DateDelivery = DateDelivery, }; - + public int Id => throw new NotImplementedException(); } - -} +} \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationListImplement/SoftwareInstallationListImplement.csproj b/SoftwareInstallation/SoftwareInstallationListImplement/SoftwareInstallationListImplement.csproj index 3a28f9a..8b9f1ce 100644 --- a/SoftwareInstallation/SoftwareInstallationListImplement/SoftwareInstallationListImplement.csproj +++ b/SoftwareInstallation/SoftwareInstallationListImplement/SoftwareInstallationListImplement.csproj @@ -11,4 +11,8 @@ + + + + diff --git a/SoftwareInstallation/SoftwareInstallationView/DataGridViewExtension.cs b/SoftwareInstallation/SoftwareInstallationView/DataGridViewExtension.cs new file mode 100644 index 0000000..58f9952 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationView/DataGridViewExtension.cs @@ -0,0 +1,46 @@ +using SoftwareInstallationContracts.Attributes; + +namespace SoftwareInstallationView +{ + 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/SoftwareInstallation/SoftwareInstallationView/FormComponents.cs b/SoftwareInstallation/SoftwareInstallationView/FormComponents.cs index eb05670..5e9b115 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormComponents.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormComponents.cs @@ -1,5 +1,6 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.DI; using Microsoft.Extensions.Logging; @@ -24,14 +25,8 @@ namespace SoftwareInstallationView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка компонентов"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) { @@ -41,33 +36,24 @@ namespace SoftwareInstallationView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } private void ButtonUpd_Click(object sender, EventArgs e) { - if (dataGridView.SelectedRows.Count == 1) - { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/SoftwareInstallation/SoftwareInstallationView/FormMain.Designer.cs b/SoftwareInstallation/SoftwareInstallationView/FormMain.Designer.cs index 0ddc7b4..8f8af9e 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormMain.Designer.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormMain.Designer.cs @@ -1,220 +1,229 @@ namespace SoftwareInstallationView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip1 = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - packageToolStripMenuItem = new ToolStripMenuItem(); - componentToolStripMenuItem = new ToolStripMenuItem(); - ImplementersToolStripMenuItem = new ToolStripMenuItem(); - ClientsToolStripMenuItem = new ToolStripMenuItem(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - DoWorkToolStripMenuItem = new ToolStripMenuItem(); - ButtonRef = new Button(); - ButtonIssuedOrder = new Button(); - buttonCreateOrder = new Button(); - dataGridView = new DataGridView(); - mailToolStripMenuItem = new ToolStripMenuItem(); - menuStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip1 - // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem }); - menuStrip1.Location = new Point(0, 0); - menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(1125, 24); - menuStrip1.TabIndex = 1; - menuStrip1.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { packageToolStripMenuItem, componentToolStripMenuItem, ImplementersToolStripMenuItem, ClientsToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(94, 20); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // packageToolStripMenuItem - // - packageToolStripMenuItem.Name = "packageToolStripMenuItem"; - packageToolStripMenuItem.Size = new Size(149, 22); - packageToolStripMenuItem.Text = "Изделия"; - packageToolStripMenuItem.Click += PackagesToolStripMenuItem_Click; - // - // componentToolStripMenuItem - // - componentToolStripMenuItem.Name = "componentToolStripMenuItem"; - componentToolStripMenuItem.Size = new Size(149, 22); - componentToolStripMenuItem.Text = "Компоненты"; - componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // ImplementersToolStripMenuItem - // - ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem"; - ImplementersToolStripMenuItem.Size = new Size(149, 22); - ImplementersToolStripMenuItem.Text = "Исполнители"; - ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; - // - // ClientsToolStripMenuItem - // - ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem"; - ClientsToolStripMenuItem.Size = new Size(149, 22); - ClientsToolStripMenuItem.Text = "Клиенты"; - ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(60, 20); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокКомпонентовToolStripMenuItem - // - списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - списокКомпонентовToolStripMenuItem.Size = new Size(218, 22); - списокКомпонентовToolStripMenuItem.Text = "Список изделий"; - списокКомпонентовToolStripMenuItem.Click += ComponentsReportToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += ComponentPackagesToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(218, 22); - списокЗаказовToolStripMenuItem.Text = "Список Заказов"; - списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // DoWorkToolStripMenuItem - // - DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; - DoWorkToolStripMenuItem.Size = new Size(92, 20); - DoWorkToolStripMenuItem.Text = "Запуск работ"; - DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click; - // - // ButtonRef - // - ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonRef.Location = new Point(966, 149); - ButtonRef.Name = "ButtonRef"; - ButtonRef.Size = new Size(147, 55); - ButtonRef.TabIndex = 12; - ButtonRef.Text = "Обновить список"; - ButtonRef.UseVisualStyleBackColor = true; - ButtonRef.Click += ButtonRef_Click; - // - // ButtonIssuedOrder - // - ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonIssuedOrder.Location = new Point(966, 88); - ButtonIssuedOrder.Name = "ButtonIssuedOrder"; - ButtonIssuedOrder.Size = new Size(147, 55); - ButtonIssuedOrder.TabIndex = 11; - ButtonIssuedOrder.Text = "Заказ выдан"; - ButtonIssuedOrder.UseVisualStyleBackColor = true; - ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonCreateOrder - // - buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonCreateOrder.Location = new Point(966, 27); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(147, 55); - buttonCreateOrder.TabIndex = 8; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 27); - dataGridView.Name = "dataGridView"; - dataGridView.RowTemplate.Height = 25; - dataGridView.Size = new Size(948, 402); - dataGridView.TabIndex = 7; - // - // mailToolStripMenuItem - // - mailToolStripMenuItem.Name = "mailToolStripMenuItem"; - mailToolStripMenuItem.Size = new Size(62, 20); - mailToolStripMenuItem.Text = "Письма"; - mailToolStripMenuItem.Click += mailToolStripMenuItem_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1125, 441); - Controls.Add(ButtonRef); - Controls.Add(ButtonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip1); - Name = "FormMain"; - Text = "Установка ПО"; - Load += FormMain_Load; - menuStrip1.ResumeLayout(false); - menuStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip1 = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + packageToolStripMenuItem = new ToolStripMenuItem(); + componentToolStripMenuItem = new ToolStripMenuItem(); + ImplementersToolStripMenuItem = new ToolStripMenuItem(); + ClientsToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + DoWorkToolStripMenuItem = new ToolStripMenuItem(); + mailToolStripMenuItem = new ToolStripMenuItem(); + ButtonRef = new Button(); + ButtonIssuedOrder = new Button(); + buttonCreateOrder = new Button(); + dataGridView = new DataGridView(); + createBackupToolStripMenuItem = new ToolStripMenuItem(); + menuStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem, createBackupToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(1125, 24); + menuStrip1.TabIndex = 1; + menuStrip1.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { packageToolStripMenuItem, componentToolStripMenuItem, ImplementersToolStripMenuItem, ClientsToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // packageToolStripMenuItem + // + packageToolStripMenuItem.Name = "packageToolStripMenuItem"; + packageToolStripMenuItem.Size = new Size(149, 22); + packageToolStripMenuItem.Text = "Изделия"; + packageToolStripMenuItem.Click += PackagesToolStripMenuItem_Click; + // + // componentToolStripMenuItem + // + componentToolStripMenuItem.Name = "componentToolStripMenuItem"; + componentToolStripMenuItem.Size = new Size(149, 22); + componentToolStripMenuItem.Text = "Компоненты"; + componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // ImplementersToolStripMenuItem + // + ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem"; + ImplementersToolStripMenuItem.Size = new Size(149, 22); + ImplementersToolStripMenuItem.Text = "Исполнители"; + ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; + // + // ClientsToolStripMenuItem + // + ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem"; + ClientsToolStripMenuItem.Size = new Size(149, 22); + ClientsToolStripMenuItem.Text = "Клиенты"; + ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(60, 20); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // списокКомпонентовToolStripMenuItem + // + списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; + списокКомпонентовToolStripMenuItem.Size = new Size(218, 22); + списокКомпонентовToolStripMenuItem.Text = "Список изделий"; + списокКомпонентовToolStripMenuItem.Click += ComponentsReportToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); + компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; + компонентыПоИзделиямToolStripMenuItem.Click += ComponentPackagesToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(218, 22); + списокЗаказовToolStripMenuItem.Text = "Список Заказов"; + списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // DoWorkToolStripMenuItem + // + DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; + DoWorkToolStripMenuItem.Size = new Size(92, 20); + DoWorkToolStripMenuItem.Text = "Запуск работ"; + DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click; + // + // mailToolStripMenuItem + // + mailToolStripMenuItem.Name = "mailToolStripMenuItem"; + mailToolStripMenuItem.Size = new Size(62, 20); + mailToolStripMenuItem.Text = "Письма"; + mailToolStripMenuItem.Click += mailToolStripMenuItem_Click; + // + // ButtonRef + // + ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + ButtonRef.Location = new Point(966, 149); + ButtonRef.Name = "ButtonRef"; + ButtonRef.Size = new Size(147, 55); + ButtonRef.TabIndex = 12; + ButtonRef.Text = "Обновить список"; + ButtonRef.UseVisualStyleBackColor = true; + ButtonRef.Click += ButtonRef_Click; + // + // ButtonIssuedOrder + // + ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + ButtonIssuedOrder.Location = new Point(966, 88); + ButtonIssuedOrder.Name = "ButtonIssuedOrder"; + ButtonIssuedOrder.Size = new Size(147, 55); + ButtonIssuedOrder.TabIndex = 11; + ButtonIssuedOrder.Text = "Заказ выдан"; + ButtonIssuedOrder.UseVisualStyleBackColor = true; + ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.Location = new Point(966, 27); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(147, 55); + buttonCreateOrder.TabIndex = 8; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 27); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(948, 402); + dataGridView.TabIndex = 7; + // + // createBackupToolStripMenuItem + // + createBackupToolStripMenuItem.Name = "createBackupToolStripMenuItem"; + createBackupToolStripMenuItem.Size = new Size(97, 20); + createBackupToolStripMenuItem.Text = "Создать бекап"; + createBackupToolStripMenuItem.Click += createBackupToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1125, 441); + Controls.Add(ButtonRef); + Controls.Add(ButtonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + Name = "FormMain"; + Text = "Установка ПО"; + Load += FormMain_Load; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip1; - private ToolStripMenuItem справочникиToolStripMenuItem; - private ToolStripMenuItem packageToolStripMenuItem; - private ToolStripMenuItem componentToolStripMenuItem; - private Button ButtonRef; - private Button ButtonIssuedOrder; - private Button buttonCreateOrder; - private DataGridView dataGridView; - private ToolStripMenuItem отчётыToolStripMenuItem; - private ToolStripMenuItem списокКомпонентовToolStripMenuItem; - private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem ClientsToolStripMenuItem; - private ToolStripMenuItem DoWorkToolStripMenuItem; - private ToolStripMenuItem ImplementersToolStripMenuItem; - private ToolStripMenuItem mailToolStripMenuItem; - } + private MenuStrip menuStrip1; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem packageToolStripMenuItem; + private ToolStripMenuItem componentToolStripMenuItem; + private Button ButtonRef; + private Button ButtonIssuedOrder; + private Button buttonCreateOrder; + private DataGridView dataGridView; + private ToolStripMenuItem отчётыToolStripMenuItem; + private ToolStripMenuItem списокКомпонентовToolStripMenuItem; + private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem ClientsToolStripMenuItem; + private ToolStripMenuItem DoWorkToolStripMenuItem; + private ToolStripMenuItem ImplementersToolStripMenuItem; + private ToolStripMenuItem mailToolStripMenuItem; + private ToolStripMenuItem createBackupToolStripMenuItem; + } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationView/FormMain.cs b/SoftwareInstallation/SoftwareInstallationView/FormMain.cs index 0d66992..e9f44e0 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormMain.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormMain.cs @@ -1,209 +1,217 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.DI; using SoftwareInstallationBusinessLogic.BusinessLogics; +using SoftwareInstallationBusinessLogic; +using SoftwareInstallationDataModels.Enums; namespace SoftwareInstallationView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + private readonly IBackUpLogic _backUpLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].HeaderText = "Номер заказа"; - dataGridView.Columns["PackageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["PackageName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void PackagesToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPackages)); - if (service is FormPackages form) - { - 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(); - } - } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении.Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении.Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void ComponentsReportToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + _backUpLogic = backUpLogic; + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void PackagesToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; if (dialog.ShowDialog() == DialogResult.OK) { - _reportLogic.SaveComponentsToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + _reportLogic.SavePackagesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Âûïîëíåíî", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information); } - } - private void ComponentPackagesToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportPackageComponents)); - if (service is FormReportPackageComponents form) - { - form.ShowDialog(); - } - } - private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); + } + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà ' ðàáîòå'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Îøèáêà ïåðåäà÷è çàêàçà â ðàáîòó"); + MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + OrderStatus orderStatus = (OrderStatus)dataGridView.SelectedRows[0].Cells["Status"].Value; + _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Ãîòîâ'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id, + Status = orderStatus + }); + if (!operationResult) + { + throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Îøèáêà îòìåòêè î ãîòîâíîñòè çàêàçà"); + MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Âûäàí'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new + OrderBindingModel + { Id = id }); + if (!operationResult) + { + throw new Exception("Îøèáêà ïðè ñîõðàíåíèè.Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); + } + _logger.LogInformation("Çàêàç No{id} âûäàí", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Îøèáêà îòìåòêè î âûäà÷è çàêàçà"); + MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + private void ComponentsReportToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SavePackagesToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + private void ComponentPackagesToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); - private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewClients)); - if (service is FormViewClients form) - { - form.ShowDialog(); - } - } - private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewImplementers)); - if (service is FormViewImplementers form) - { - form.ShowDialog(); - } - } - private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } + } - private void mailToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); - if (service is FormViewMail form) - { - form.ShowDialog(); - } - } - } + private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(DependencyManager.Instance.Resolve(), _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void mailToolStripMenuItem_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + + private void createBackupToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + 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); + } + } + } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationView/FormPackage.cs b/SoftwareInstallation/SoftwareInstallationView/FormPackage.cs index cdafca3..e0034f6 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormPackage.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormPackage.cs @@ -1,5 +1,6 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.DI; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationDataModels.Models; using Microsoft.Extensions.Logging; @@ -69,52 +70,46 @@ namespace SoftwareInstallationView } } private void ButtonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPackageComponent)); - if (service is FormPackageComponent form) - { - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - if (_packageComponents.ContainsKey(form.Id)) - { - _packageComponents[form.Id] = (form.ComponentModel, form.Count); - } - else - { - _packageComponents.Add(form.Id, (form.ComponentModel, form.Count)); - } - LoadData(); - } - } + { + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Добавление нового компонента: { ComponentName}- { Count}", form.ComponentModel.ComponentName, form.Count); + if (_packageComponents.ContainsKey(form.Id)) + { + _packageComponents[form.Id] = (form.ComponentModel, form.Count); + } + else + { + _packageComponents.Add(form.Id, (form.ComponentModel, form.Count)); + } + LoadData(); + } } private void ButtonUpd_Click(object sender, EventArgs e) { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPackageComponent)); - if (service is FormPackageComponent form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _packageComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _packageComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); - } - } - } - } + 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 = _packageComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) + { + if (form.ComponentModel == null) + { + return; + } + _logger.LogInformation("Изменение компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count); + _packageComponents[id] = (form.ComponentModel, form.Count); + LoadData(); + } + } + } private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/SoftwareInstallation/SoftwareInstallationView/FormPackages.cs b/SoftwareInstallation/SoftwareInstallationView/FormPackages.cs index fa95cfc..8a028cc 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormPackages.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormPackages.cs @@ -1,5 +1,6 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.DI; using Microsoft.Extensions.Logging; namespace SoftwareInstallationView @@ -21,77 +22,68 @@ namespace SoftwareInstallationView } private void LoadData() { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["PackageComponents"].Visible = false; - dataGridView.Columns["PackageName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка изделий"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки изделий"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } + try + { + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка изделий"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPackage)); - if (service is FormPackage form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } private void ButtonUpd_Click(object sender, EventArgs e) { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - } - LoadData(); - } - } + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } private void ButtonDel_Click(object sender, EventArgs e) { - if (dataGridView.SelectedRows.Count == 1) - { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление изделия"); - try - { - if (!_logic.Delete(new PackageBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление изделия"); + try + { + if (!_logic.Delete(new PackageBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления изделия"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); diff --git a/SoftwareInstallation/SoftwareInstallationView/FormViewClients.cs b/SoftwareInstallation/SoftwareInstallationView/FormViewClients.cs index 8cfe0c0..45fe0fc 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormViewClients.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormViewClients.cs @@ -22,14 +22,8 @@ namespace SoftwareInstallationView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка клиентов"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) { diff --git a/SoftwareInstallation/SoftwareInstallationView/FormViewImplementers.cs b/SoftwareInstallation/SoftwareInstallationView/FormViewImplementers.cs index 80f16d2..c1eccbc 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormViewImplementers.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormViewImplementers.cs @@ -1,6 +1,7 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.DI; using System; using System.Collections.Generic; using System.ComponentModel; @@ -31,13 +32,7 @@ namespace SoftwareInstallationView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) @@ -49,27 +44,21 @@ namespace SoftwareInstallationView } 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/SoftwareInstallation/SoftwareInstallationView/FormViewMail.cs b/SoftwareInstallation/SoftwareInstallationView/FormViewMail.cs index e037b96..9a3b78d 100644 --- a/SoftwareInstallation/SoftwareInstallationView/FormViewMail.cs +++ b/SoftwareInstallation/SoftwareInstallationView/FormViewMail.cs @@ -29,14 +29,7 @@ namespace SoftwareInstallationView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка списка писем"); } catch (Exception ex) diff --git a/SoftwareInstallation/SoftwareInstallationView/Program.cs b/SoftwareInstallation/SoftwareInstallationView/Program.cs index 3801b7b..2140663 100644 --- a/SoftwareInstallation/SoftwareInstallationView/Program.cs +++ b/SoftwareInstallation/SoftwareInstallationView/Program.cs @@ -1,100 +1,95 @@ -using SoftwareInstallationContracts.BusinessLogicsContracts; -using SoftwareInstallationContracts.StoragesContracts; -using SoftwareInstallationDatabaseImplement.Implements; -using Microsoft.Extensions.DependencyInjection; +using NLog.Extensions.Logging; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; using SoftwareInstallationBusinessLogic.BusinessLogics; +using SoftwareInstallationBusinessLogic.MailWorker; using SoftwareInstallationBusinessLogic.OfficePackage.Implements; using SoftwareInstallationBusinessLogic.OfficePackage; using SoftwareInstallationBusinessLogic; -using SoftwareInstallationBusinessLogic.MailWorker; using SoftwareInstallationContracts.BindingModels; -using SoftwareInstallationDatabaseImplement; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.DI; using SoftwareInstallationView; -namespace SoftwareInstallationView +namespace ConfectioneryView { - internal static class Program - { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // 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 - { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPIsettings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + InitDependency(); - // ñîçäàåì òàéìåð - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); - } - catch (Exception ex) - { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); - } - Application.Run(_serviceProvider.GetRequiredService()); - } - private static void ConfigureServices(ServiceCollection services) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + try + { + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + // создаем таймер + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = DependencyManager.Instance.Resolve(); + logger?.LogError(ex, "Ошибка работы с почтой"); + } - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); - } + Application.Run(DependencyManager.Instance.Resolve()); + } + private static void InitDependency() + { + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(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(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } + + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); + } } \ No newline at end of file -- 2.25.1