у меня задежрка в развитии(8 базовая лаба)

This commit is contained in:
m1aksim1 2023-05-08 01:13:26 +04:00
parent e7e0729e0e
commit 5b47a8d778
56 changed files with 1541 additions and 777 deletions

3
.gitignore vendored
View File

@ -14,6 +14,9 @@
# User-specific files (MonoDevelop/Xamarin Studio) # User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs *.userprefs
# dll файлы
*.dll
# Mono auto generated files # Mono auto generated files
mono_crash.* mono_crash.*

View File

@ -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<T>? GetList<T>() where T : class, new()
{
// Получаем значения из singleton-объекта универсального свойства содержащее тип T
var source = DataFileSingleton.GetInstance();
return (List<T>?)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;
}
}
}

View File

@ -1,19 +1,25 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using System.Runtime.Serialization;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.Xml.Linq; using System.Xml.Linq;
namespace SoftwareInstallationFileImplement namespace SoftwareInstallationFileImplement
{ {
public class Client : IClientModel [DataContract]
{ public class Client : IClientModel
public string ClientFIO { get; private set; } = string.Empty; {
[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) public static Client? Create(ClientBindingModel model)
{ {

View File

@ -2,14 +2,19 @@
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.Xml.Linq; using System.Xml.Linq;
using System.Runtime.Serialization;
namespace SoftwareInstallationFileImplement.Models namespace SoftwareInstallationFileImplement.Models
{ {
public class Component : IComponentModel [DataContract]
public class Component : IComponentModel
{ {
public int Id { get; private set; } [DataMember]
public string ComponentName { get; private set; } = string.Empty; public int Id { get; private set; }
public double Cost { get; set; } [DataMember]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model) public static Component? Create(ComponentBindingModel? model)
{ {
if (model == null) if (model == null)

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IPackageStorage, PackageStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -2,19 +2,26 @@
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.Xml.Linq; using System.Xml.Linq;
using System.Runtime.Serialization;
namespace SoftwareInstallationFileImplement namespace SoftwareInstallationFileImplement
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; } public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; } public int Qualification { get; private set; }
public static Implementer? Create(XElement element) public static Implementer? Create(XElement element)

View File

@ -7,22 +7,30 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
using System.Runtime.Serialization;
namespace SoftwareInstallationFileImplement.Models namespace SoftwareInstallationFileImplement.Models
{ {
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
[DataMember]
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty; public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now; public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty; public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
@ -77,6 +85,6 @@ namespace SoftwareInstallationFileImplement.Models
new XAttribute("SenderName", SenderName), new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery) new XAttribute("DateDelivery", DateDelivery)
); );
public int Id => throw new NotImplementedException();
} }
}
}

View File

@ -3,28 +3,39 @@ using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Enums;
using System.Xml.Linq; using System.Xml.Linq;
using System.Runtime.Serialization;
namespace SoftwareInstallationFileImplement.Models 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; } public int? ImplementerId { get; set; }
[DataMember]
public int Count { get; private set; } 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) public static Order? Create(OrderBindingModel? model)
{ {

View File

@ -1,19 +1,25 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace SoftwareInstallationFileImplement.Models namespace SoftwareInstallationFileImplement.Models
{ {
public class Package : IPackageModel [DataContract]
public class Package : IPackageModel
{ {
public int Id { get; private set; } [DataMember]
public string PackageName { get; private set; } = string.Empty; public int Id { get; private set; }
public double Price { get; private set; } [DataMember]
public string PackageName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new(); public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _packageComponents = null; private Dictionary<int, (IComponentModel, int)>? _packageComponents = null;
public Dictionary<int, (IComponentModel, int)> PackageComponents [DataMember]
public Dictionary<int, (IComponentModel, int)> PackageComponents
{ {
get get
{ {

View File

@ -11,4 +11,8 @@
<ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" /> <ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(targetDir)*.dll&quot; &quot;$(solutionDir)ImplementationExtensions\*.dll" />
</Target>
</Project> </Project>

View File

@ -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<BackUpLogic> 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<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@ -73,7 +73,7 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics
/// Сохранение изделий в файл-Word /// Сохранение изделий в файл-Word
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
public void SaveComponentsToWordFile(ReportBindingModel model) public void SavePackagesToWordFile(ReportBindingModel model)
{ {
_saveToWord.CreateDoc(new WordInfo _saveToWord.CreateDoc(new WordInfo
{ {
@ -95,11 +95,11 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics
PackageComponents = GetPackageComponent() PackageComponents = GetPackageComponent()
}); });
} }
/// <summary> /// <summary>
/// Сохранение заказов в файл-Pdf /// Сохранение заказов в файл-Pdf
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
public void SaveOrdersToPdfFile(ReportBindingModel model) public void SaveOrdersToPdfFile(ReportBindingModel model)
{ {
_saveToPdf.CreateDoc(new PdfInfo _saveToPdf.CreateDoc(new PdfInfo
{ {

View File

@ -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;
}
}
}

View File

@ -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
}
}

View File

@ -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;
}
}

View File

@ -20,5 +20,7 @@ namespace SoftwareInstallationContracts.BindingModels
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -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);
}
}

View File

@ -20,7 +20,7 @@ namespace SoftwareInstallationContracts.BusinessLogicsContracts
/// Сохранение компонент в файл-Word /// Сохранение компонент в файл-Word
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
void SaveComponentsToWordFile(ReportBindingModel model); void SavePackagesToWordFile(ReportBindingModel model);
/// <summary> /// <summary>
/// Сохранение компонент с указаеним продуктов в файл-Excel /// Сохранение компонент с указаеним продуктов в файл-Excel
/// </summary> /// </summary>

View File

@ -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; } }
/// <summary>
/// Иницализация библиотек, в которых идут установки зависомстей
/// </summary>
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.Extensions.Logging;
namespace SoftwareInstallationContracts.DI
{
public interface IDependencyContainer
{
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
void AddLogging(Action<ILoggingBuilder> configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T, U>(bool isSingle) where U : class, T where T : class;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T>(bool isSingle) where T : class;
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@ -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; }
/// <summary>
/// Регистрация сервисов
/// </summary>
public void RegisterServices();
}
}

View File

@ -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<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@ -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
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
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";
}
}
}

View File

@ -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<ILoggingBuilder> configure)
{
var factory = LoggerFactory.Create(configure);
_container.AddExtension(new LoggingExtension(factory));
}
public void RegisterType<T>(bool isSingle) where T : class
{
_container.RegisterType<T>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
void IDependencyContainer.RegisterType<T, U>(bool isSingle)
{
_container.RegisterType<T, U>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
}
}

View File

@ -6,6 +6,14 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog" Version="5.1.4" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" /> <ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -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<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@ -1,16 +1,18 @@
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationContracts.Attributes;
using System.ComponentModel; using System.ComponentModel;
namespace SoftwareInstallationContracts.ViewModels namespace SoftwareInstallationContracts.ViewModels
{ {
public class ClientViewModel : IClientModel public class ClientViewModel : IClientModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("ФИО клиента")] public int Id { get; set; }
public string ClientFIO { get; set; } = string.Empty; [Column("ФИО клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Логин (эл. почта)")] public string ClientFIO { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty; [Column("Логин (эл. почта)", width: 150)]
[DisplayName("Пароль")] public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; [Column("Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
} }
} }

View File

@ -1,14 +1,16 @@
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationContracts.Attributes;
using System.ComponentModel; using System.ComponentModel;
namespace SoftwareInstallationContracts.ViewModels namespace SoftwareInstallationContracts.ViewModels
{ {
public class ComponentViewModel : IComponentModel public class ComponentViewModel : IComponentModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Название компонента")] public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty; [Column("Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Цена")] public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; } [Column("Цена", width: 80)]
public double Cost { get; set; }
} }
} }

View File

@ -1,5 +1,7 @@
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationDataModels;
using System.ComponentModel; using System.ComponentModel;
using SoftwareInstallationContracts.Attributes;
namespace SoftwareInstallationContracts.ViewModels namespace SoftwareInstallationContracts.ViewModels
{ {
@ -8,18 +10,19 @@ namespace SoftwareInstallationContracts.ViewModels
/// </summary> /// </summary>
public class ImplementerViewModel : IImplementerModel public class ImplementerViewModel : IImplementerModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("ФИО исполнителя")] [Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column("Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")] [Column("Стаж работы", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int WorkExperience { get; set; } public int WorkExperience { get; set; }
[DisplayName("Квалификация")] [Column("Квалификация", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Qualification { get; set; } public int Qualification { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using SoftwareInstallationDataModels; using SoftwareInstallationDataModels;
using SoftwareInstallationContracts.Attributes;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,20 +11,25 @@ namespace SoftwareInstallationContracts.ViewModels
{ {
public class MessageInfoViewModel : IMessageInfoModel public class MessageInfoViewModel : IMessageInfoModel
{ {
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty; public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; } public int? ClientId { get; set; }
[DisplayName("Отправитель")] [Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата письма")] [Column("Дата письма", width: 100)]
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
[DisplayName("Заголовок")] [Column("Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")] [Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
[Column(visible: false)]
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -1,5 +1,6 @@
using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Enums;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationContracts.Attributes;
using System.ComponentModel; using System.ComponentModel;
@ -7,26 +8,29 @@ namespace SoftwareInstallationContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Id { get; set; } public int Id { get; set; }
public int PackageId { get; set; } [Column(visible: false)]
public int ClientId { get; set; } public int PackageId { get; set; }
[Column(visible: false)]
public int ClientId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; } public int? ImplementerId { get; set; }
[DisplayName("Фамилия клиента")] [Column("Фамилия клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Фамилия исполнителя")] [Column("Фамилия исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Изделие")] [Column("Изделие", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string PackageName { get; set; } = string.Empty; public string PackageName { get; set; } = string.Empty;
[DisplayName("Количество")] [Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public double Sum { get; set; } public double Sum { get; set; }
[DisplayName("Статус")] [Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")] [Column("Дата создания", width: 100)]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")] [Column("Дата выполнения", width: 100)]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
} }
} }

View File

@ -1,16 +1,19 @@
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using SoftwareInstallationContracts.Attributes;
using System.ComponentModel; using System.ComponentModel;
namespace SoftwareInstallationContracts.ViewModels namespace SoftwareInstallationContracts.ViewModels
{ {
public class PackageViewModel : IPackageModel public class PackageViewModel : IPackageModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Название изделия")] public int Id { get; set; }
public string PackageName { get; set; } = string.Empty; [Column("Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Цена")] public string PackageName { get; set; } = string.Empty;
public double Price { get; set; } [Column("Цена", width: 100)]
public Dictionary<int, (IComponentModel, int)> PackageComponents public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> PackageComponents
{ {
get; get;
set; set;

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace SoftwareInstallationDataModels namespace SoftwareInstallationDataModels
{ {
public interface IMessageInfoModel public interface IMessageInfoModel : IId
{ {
string MessageId { get; } string MessageId { get; }

View File

@ -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<T>? GetList<T>() where T : class, new()
{
using var context = new SoftwareInstallationDatabase();
return context.Set<T>().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;
}
}
}

View File

@ -3,22 +3,28 @@ using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models namespace SoftwareInstallationDatabaseImplement.Models
{ {
public class Client : IClientModel [DataContract]
public class Client : IClientModel
{ {
[Required] [Required]
public string ClientFIO { get; private set; } = string.Empty; [DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[Required] [Required]
public string Email { get; private set; } = string.Empty; [DataMember]
public string Email { get; private set; } = string.Empty;
[Required] [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")] [ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new(); public virtual List<Order> Orders { get; set; } = new();

View File

@ -3,16 +3,21 @@ using SoftwareInstallationDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models 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] [Required]
public string ComponentName { get; private set; } = string.Empty; [DataMember]
public string ComponentName { get; private set; } = string.Empty;
[Required] [Required]
public double Cost { get; set; } [DataMember]
public double Cost { get; set; }
[ForeignKey("ComponentId")] [ForeignKey("ComponentId")]
public virtual List<PackageComponent> PackageComponents { get; set; } = new(); public virtual List<PackageComponent> PackageComponents { get; set; } = new();

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IPackageStorage, PackageStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -2,19 +2,26 @@
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models namespace SoftwareInstallationDatabaseImplement.Models
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; } public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; } public int Qualification { get; private set; }
[ForeignKey("ImplementerId")] [ForeignKey("ImplementerId")]

View File

@ -2,13 +2,16 @@
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels; using SoftwareInstallationDataModels;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models namespace SoftwareInstallationDatabaseImplement.Models
{ {
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
[Key] [Key]
[DataMember]
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
@ -49,7 +52,7 @@ namespace SoftwareInstallationDatabaseImplement.Models
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -3,34 +3,44 @@ using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Enums;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models namespace SoftwareInstallationDatabaseImplement.Models
{ {
public class Order : IOrderModel [DataContract]
public class Order : IOrderModel
{ {
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
public int PackageId { get; private set; } [DataMember]
public int PackageId { get; private set; }
[Required] [Required]
public int ClientId { get; private set; } [DataMember]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; } public int? ImplementerId { get; private set; }
[Required] [Required]
public int Count { get; private set; } [DataMember]
public int Count { get; private set; }
[Required] [Required]
public double Sum { get; private set; } [DataMember]
public double Sum { get; private set; }
[Required] [Required]
public OrderStatus Status { get; private set; } [DataMember]
public OrderStatus Status { get; private set; }
[Required] [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; } public Package Package { get; private set; }

View File

@ -3,20 +3,26 @@ using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using System.Runtime.Serialization;
namespace SoftwareInstallationDatabaseImplement.Models namespace SoftwareInstallationDatabaseImplement.Models
{ {
public class Package : IPackageModel [DataContract]
public class Package : IPackageModel
{ {
public int Id { get; set; } [DataMember]
public int Id { get; set; }
[Required] [Required]
public string PackageName { get; set; } = string.Empty; [DataMember]
public string PackageName { get; set; } = string.Empty;
[Required] [Required]
public double Price { get; set; } [DataMember]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _packageComponents = null; private Dictionary<int, (IComponentModel, int)>? _packageComponents = null;
[NotMapped] [NotMapped]
public Dictionary<int, (IComponentModel, int)> PackageComponents [DataMember]
public Dictionary<int, (IComponentModel, int)> PackageComponents
{ {
get get
{ {

View File

@ -25,4 +25,8 @@
<Folder Include="Migrations\" /> <Folder Include="Migrations\" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(targetDir)*.dll&quot; &quot;$(solutionDir)ImplementationExtensions\*.dll" />
</Target>
</Project> </Project>

View File

@ -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<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@ -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<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IPackageStorage, PackageStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -50,7 +50,6 @@ namespace SoftwareInstallationListImplement.Models
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
public int Id => throw new NotImplementedException();
} }
}
}

View File

@ -11,4 +11,8 @@
<ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" /> <ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(targetDir)*.dll&quot; &quot;$(solutionDir)ImplementationExtensions\*.dll" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,46 @@
using SoftwareInstallationContracts.Attributes;
namespace SoftwareInstallationView
{
internal static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? 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;
}
}
}
}
}
}

View File

@ -1,5 +1,6 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -24,14 +25,8 @@ namespace SoftwareInstallationView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка компонентов");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -41,33 +36,24 @@ namespace SoftwareInstallationView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = var form = DependencyManager.Instance.Resolve<FormComponent>();
Program.ServiceProvider?.GetService(typeof(FormComponent)); if (form.ShowDialog() == DialogResult.OK)
if (service is FormComponent form) {
{ LoadData();
if (form.ShowDialog() == DialogResult.OK) }
{ }
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = var form = DependencyManager.Instance.Resolve<FormComponent>();
Program.ServiceProvider?.GetService(typeof(FormComponent)); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (service is FormComponent form) if (form.ShowDialog() == DialogResult.OK)
{ {
form.Id = LoadData();
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); }
if (form.ShowDialog() == DialogResult.OK) }
{ }
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -1,220 +1,229 @@
namespace SoftwareInstallationView namespace SoftwareInstallationView
{ {
partial class FormMain partial class FormMain
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
menuStrip1 = new MenuStrip(); menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem(); справочникиToolStripMenuItem = new ToolStripMenuItem();
packageToolStripMenuItem = new ToolStripMenuItem(); packageToolStripMenuItem = new ToolStripMenuItem();
componentToolStripMenuItem = new ToolStripMenuItem(); componentToolStripMenuItem = new ToolStripMenuItem();
ImplementersToolStripMenuItem = new ToolStripMenuItem(); ImplementersToolStripMenuItem = new ToolStripMenuItem();
ClientsToolStripMenuItem = new ToolStripMenuItem(); ClientsToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem();
списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem();
компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
DoWorkToolStripMenuItem = new ToolStripMenuItem(); DoWorkToolStripMenuItem = new ToolStripMenuItem();
ButtonRef = new Button(); mailToolStripMenuItem = new ToolStripMenuItem();
ButtonIssuedOrder = new Button(); ButtonRef = new Button();
buttonCreateOrder = new Button(); ButtonIssuedOrder = new Button();
dataGridView = new DataGridView(); buttonCreateOrder = new Button();
mailToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView();
menuStrip1.SuspendLayout(); createBackupToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout();
SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
// SuspendLayout();
// menuStrip1 //
// // menuStrip1
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem }); //
menuStrip1.Location = new Point(0, 0); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem, createBackupToolStripMenuItem });
menuStrip1.Name = "menuStrip1"; menuStrip1.Location = new Point(0, 0);
menuStrip1.Size = new Size(1125, 24); menuStrip1.Name = "menuStrip1";
menuStrip1.TabIndex = 1; menuStrip1.Size = new Size(1125, 24);
menuStrip1.Text = "menuStrip1"; menuStrip1.TabIndex = 1;
// menuStrip1.Text = "menuStrip1";
// справочникиToolStripMenuItem //
// // справочникиToolStripMenuItem
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { packageToolStripMenuItem, componentToolStripMenuItem, ImplementersToolStripMenuItem, ClientsToolStripMenuItem }); //
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { packageToolStripMenuItem, componentToolStripMenuItem, ImplementersToolStripMenuItem, ClientsToolStripMenuItem });
справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Size = new Size(94, 20);
// справочникиToolStripMenuItem.Text = "Справочники";
// packageToolStripMenuItem //
// // packageToolStripMenuItem
packageToolStripMenuItem.Name = "packageToolStripMenuItem"; //
packageToolStripMenuItem.Size = new Size(149, 22); packageToolStripMenuItem.Name = "packageToolStripMenuItem";
packageToolStripMenuItem.Text = "Изделия"; packageToolStripMenuItem.Size = new Size(149, 22);
packageToolStripMenuItem.Click += PackagesToolStripMenuItem_Click; packageToolStripMenuItem.Text = "Изделия";
// packageToolStripMenuItem.Click += PackagesToolStripMenuItem_Click;
// componentToolStripMenuItem //
// // componentToolStripMenuItem
componentToolStripMenuItem.Name = "componentToolStripMenuItem"; //
componentToolStripMenuItem.Size = new Size(149, 22); componentToolStripMenuItem.Name = "componentToolStripMenuItem";
componentToolStripMenuItem.Text = "Компоненты"; componentToolStripMenuItem.Size = new Size(149, 22);
componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; componentToolStripMenuItem.Text = "Компоненты";
// componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// ImplementersToolStripMenuItem //
// // ImplementersToolStripMenuItem
ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem"; //
ImplementersToolStripMenuItem.Size = new Size(149, 22); ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
ImplementersToolStripMenuItem.Text = "Исполнители"; ImplementersToolStripMenuItem.Size = new Size(149, 22);
ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; ImplementersToolStripMenuItem.Text = "Исполнители";
// ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
// ClientsToolStripMenuItem //
// // ClientsToolStripMenuItem
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem"; //
ClientsToolStripMenuItem.Size = new Size(149, 22); ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
ClientsToolStripMenuItem.Text = "Клиенты"; ClientsToolStripMenuItem.Size = new Size(149, 22);
ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; ClientsToolStripMenuItem.Text = "Клиенты";
// ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// отчётыToolStripMenuItem //
// // отчётыToolStripMenuItem
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); //
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem });
отчётыToolStripMenuItem.Size = new Size(60, 20); отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Text = "Отчёты"; отчётыToolStripMenuItem.Size = new Size(60, 20);
// отчётыToolStripMenuItem.Text = "Отчёты";
// списокКомпонентовToolStripMenuItem //
// // списокКомпонентовToolStripMenuItem
списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; //
списокКомпонентовToolStripMenuItem.Size = new Size(218, 22); списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem";
списокКомпонентовToolStripMenuItem.Text = "Список изделий"; списокКомпонентовToolStripMenuItem.Size = new Size(218, 22);
списокКомпонентовToolStripMenuItem.Click += ComponentsReportToolStripMenuItem_Click; списокКомпонентовToolStripMenuItem.Text = "Список изделий";
// списокКомпонентовToolStripMenuItem.Click += ComponentsReportToolStripMenuItem_Click;
// компонентыПоИзделиямToolStripMenuItem //
// // компонентыПоИзделиямToolStripMenuItem
компонентыПоИзделиямToolStripMenuItem.Name = омпонентыПоИзделиямToolStripMenuItem"; //
компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); компонентыПоИзделиямToolStripMenuItem.Name = омпонентыПоИзделиямToolStripMenuItem";
компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22);
компонентыПоИзделиямToolStripMenuItem.Click += ComponentPackagesToolStripMenuItem_Click; компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям";
// компонентыПоИзделиямToolStripMenuItem.Click += ComponentPackagesToolStripMenuItem_Click;
// списокЗаказовToolStripMenuItem //
// // списокЗаказовToolStripMenuItem
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; //
списокЗаказовToolStripMenuItem.Size = new Size(218, 22); списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Text = "Список Заказов"; списокЗаказовToolStripMenuItem.Size = new Size(218, 22);
списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; списокЗаказовToolStripMenuItem.Text = "Список Заказов";
// списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
// DoWorkToolStripMenuItem //
// // DoWorkToolStripMenuItem
DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; //
DoWorkToolStripMenuItem.Size = new Size(92, 20); DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem";
DoWorkToolStripMenuItem.Text = "Запуск работ"; DoWorkToolStripMenuItem.Size = new Size(92, 20);
DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click; DoWorkToolStripMenuItem.Text = "Запуск работ";
// DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click;
// ButtonRef //
// // mailToolStripMenuItem
ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; //
ButtonRef.Location = new Point(966, 149); mailToolStripMenuItem.Name = "mailToolStripMenuItem";
ButtonRef.Name = "ButtonRef"; mailToolStripMenuItem.Size = new Size(62, 20);
ButtonRef.Size = new Size(147, 55); mailToolStripMenuItem.Text = "Письма";
ButtonRef.TabIndex = 12; mailToolStripMenuItem.Click += mailToolStripMenuItem_Click;
ButtonRef.Text = "Обновить список"; //
ButtonRef.UseVisualStyleBackColor = true; // ButtonRef
ButtonRef.Click += ButtonRef_Click; //
// ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
// ButtonIssuedOrder ButtonRef.Location = new Point(966, 149);
// ButtonRef.Name = "ButtonRef";
ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; ButtonRef.Size = new Size(147, 55);
ButtonIssuedOrder.Location = new Point(966, 88); ButtonRef.TabIndex = 12;
ButtonIssuedOrder.Name = "ButtonIssuedOrder"; ButtonRef.Text = "Обновить список";
ButtonIssuedOrder.Size = new Size(147, 55); ButtonRef.UseVisualStyleBackColor = true;
ButtonIssuedOrder.TabIndex = 11; ButtonRef.Click += ButtonRef_Click;
ButtonIssuedOrder.Text = "Заказ выдан"; //
ButtonIssuedOrder.UseVisualStyleBackColor = true; // ButtonIssuedOrder
ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; //
// ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
// buttonCreateOrder ButtonIssuedOrder.Location = new Point(966, 88);
// ButtonIssuedOrder.Name = "ButtonIssuedOrder";
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; ButtonIssuedOrder.Size = new Size(147, 55);
buttonCreateOrder.Location = new Point(966, 27); ButtonIssuedOrder.TabIndex = 11;
buttonCreateOrder.Name = "buttonCreateOrder"; ButtonIssuedOrder.Text = "Заказ выдан";
buttonCreateOrder.Size = new Size(147, 55); ButtonIssuedOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.TabIndex = 8; ButtonIssuedOrder.Click += ButtonIssuedOrder_Click;
buttonCreateOrder.Text = "Создать заказ"; //
buttonCreateOrder.UseVisualStyleBackColor = true; // buttonCreateOrder
buttonCreateOrder.Click += ButtonCreateOrder_Click; //
// buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
// dataGridView buttonCreateOrder.Location = new Point(966, 27);
// buttonCreateOrder.Name = "buttonCreateOrder";
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; buttonCreateOrder.Size = new Size(147, 55);
dataGridView.BackgroundColor = SystemColors.ButtonHighlight; buttonCreateOrder.TabIndex = 8;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; buttonCreateOrder.Text = "Создать заказ";
dataGridView.Location = new Point(12, 27); buttonCreateOrder.UseVisualStyleBackColor = true;
dataGridView.Name = "dataGridView"; buttonCreateOrder.Click += ButtonCreateOrder_Click;
dataGridView.RowTemplate.Height = 25; //
dataGridView.Size = new Size(948, 402); // dataGridView
dataGridView.TabIndex = 7; //
// dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
// mailToolStripMenuItem dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
// dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
mailToolStripMenuItem.Name = "mailToolStripMenuItem"; dataGridView.Location = new Point(12, 27);
mailToolStripMenuItem.Size = new Size(62, 20); dataGridView.Name = "dataGridView";
mailToolStripMenuItem.Text = "Письма"; dataGridView.RowTemplate.Height = 25;
mailToolStripMenuItem.Click += mailToolStripMenuItem_Click; dataGridView.Size = new Size(948, 402);
// dataGridView.TabIndex = 7;
// FormMain //
// // createBackupToolStripMenuItem
AutoScaleDimensions = new SizeF(7F, 15F); //
AutoScaleMode = AutoScaleMode.Font; createBackupToolStripMenuItem.Name = "createBackupToolStripMenuItem";
ClientSize = new Size(1125, 441); createBackupToolStripMenuItem.Size = new Size(97, 20);
Controls.Add(ButtonRef); createBackupToolStripMenuItem.Text = "Создать бекап";
Controls.Add(ButtonIssuedOrder); createBackupToolStripMenuItem.Click += createBackupToolStripMenuItem_Click;
Controls.Add(buttonCreateOrder); //
Controls.Add(dataGridView); // FormMain
Controls.Add(menuStrip1); //
Name = "FormMain"; AutoScaleDimensions = new SizeF(7F, 15F);
Text = "Установка ПО"; AutoScaleMode = AutoScaleMode.Font;
Load += FormMain_Load; ClientSize = new Size(1125, 441);
menuStrip1.ResumeLayout(false); Controls.Add(ButtonRef);
menuStrip1.PerformLayout(); Controls.Add(ButtonIssuedOrder);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); Controls.Add(buttonCreateOrder);
ResumeLayout(false); Controls.Add(dataGridView);
PerformLayout(); 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 MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem packageToolStripMenuItem; private ToolStripMenuItem packageToolStripMenuItem;
private ToolStripMenuItem componentToolStripMenuItem; private ToolStripMenuItem componentToolStripMenuItem;
private Button ButtonRef; private Button ButtonRef;
private Button ButtonIssuedOrder; private Button ButtonIssuedOrder;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private DataGridView dataGridView; private DataGridView dataGridView;
private ToolStripMenuItem отчётыToolStripMenuItem; private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокКомпонентовToolStripMenuItem; private ToolStripMenuItem списокКомпонентовToolStripMenuItem;
private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem; private ToolStripMenuItem ClientsToolStripMenuItem;
private ToolStripMenuItem DoWorkToolStripMenuItem; private ToolStripMenuItem DoWorkToolStripMenuItem;
private ToolStripMenuItem ImplementersToolStripMenuItem; private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem mailToolStripMenuItem; private ToolStripMenuItem mailToolStripMenuItem;
} private ToolStripMenuItem createBackupToolStripMenuItem;
}
} }

View File

@ -1,209 +1,217 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SoftwareInstallationContracts.DI;
using SoftwareInstallationBusinessLogic.BusinessLogics; using SoftwareInstallationBusinessLogic.BusinessLogics;
using SoftwareInstallationBusinessLogic;
using SoftwareInstallationDataModels.Enums;
namespace SoftwareInstallationView namespace SoftwareInstallationView
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess; private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_workProcess = workProcess; _workProcess = workProcess;
} _backUpLogic = backUpLogic;
private void FormMain_Load(object sender, EventArgs e) }
{ private void FormMain_Load(object sender, EventArgs e)
LoadData(); {
} LoadData();
private void LoadData() }
{ private void LoadData()
try {
{ try
var list = _orderLogic.ReadList(null); {
if (list != null) dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
{ _logger.LogInformation("Загрузка заказов");
dataGridView.DataSource = list; }
dataGridView.Columns["Id"].HeaderText = "Номер заказа"; catch (Exception ex)
dataGridView.Columns["PackageId"].Visible = false; {
dataGridView.Columns["ClientId"].Visible = false; _logger.LogError(ex, "Ошибка загрузки заказов");
dataGridView.Columns["ImplementerId"].Visible = false; MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
dataGridView.Columns["PackageName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; }
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; }
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
} var form = DependencyManager.Instance.Resolve<FormComponents>();
_logger.LogInformation("Загрузка заказов"); form.ShowDialog();
} }
catch (Exception ex) private void PackagesToolStripMenuItem_Click(object sender, EventArgs e)
{ {
_logger.LogError(ex, "Ошибка загрузки заказов"); using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
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" };
if (dialog.ShowDialog() == DialogResult.OK) if (dialog.ShowDialog() == DialogResult.OK)
{ {
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel _reportLogic.SavePackagesToWordFile(new ReportBindingModel { FileName = dialog.FileName });
{ MessageBox.Show("Âûïîëíåíî", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
} }
private void ComponentPackagesToolStripMenuItem_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportPackageComponents)); var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormReportPackageComponents form) form.ShowDialog();
{ LoadData();
form.ShowDialog(); }
} private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
} {
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (service is FormReportOrders form) _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Â ðàáîòå'", id);
{ try
form.ShowDialog(); {
} 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<FormReportPackageComponents>();
form.ShowDialog();
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportOrders>();
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) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); var form = DependencyManager.Instance.Resolve<FormViewClients>();
if (service is FormViewMail form) form.ShowDialog();
{ }
form.ShowDialog(); private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
} {
} var form = DependencyManager.Instance.Resolve<FormViewImplementers>();
} form.ShowDialog();
}
private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(), _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void mailToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormViewMail>();
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);
}
}
}
} }

View File

@ -1,5 +1,6 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.DI;
using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationDataModels.Models; using SoftwareInstallationDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -69,52 +70,46 @@ namespace SoftwareInstallationView
} }
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPackageComponent)); var form = DependencyManager.Instance.Resolve<FormPackageComponent>();
if (service is FormPackageComponent form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) if (form.ComponentModel == null)
{ {
if (form.ComponentModel == null) return;
{ }
return; _logger.LogInformation("Добавление нового компонента: { ComponentName}- { Count}", form.ComponentModel.ComponentName, form.Count);
} if (_packageComponents.ContainsKey(form.Id))
_logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); {
if (_packageComponents.ContainsKey(form.Id)) _packageComponents[form.Id] = (form.ComponentModel, form.Count);
{ }
_packageComponents[form.Id] = (form.ComponentModel, form.Count); else
} {
else _packageComponents.Add(form.Id, (form.ComponentModel, form.Count));
{ }
_packageComponents.Add(form.Id, (form.ComponentModel, form.Count)); LoadData();
} }
LoadData();
}
}
} }
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPackageComponent)); var form = DependencyManager.Instance.Resolve<FormPackageComponent>();
if (service is FormPackageComponent form) int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
{ form.Id = id;
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Count = _packageComponents[id].Item2;
form.Id = id; if (form.ShowDialog() == DialogResult.OK)
form.Count = _packageComponents[id].Item2; {
if (form.ShowDialog() == DialogResult.OK) if (form.ComponentModel == null)
{ {
if (form.ComponentModel == null) return;
{ }
return; _logger.LogInformation("Изменение компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
} _packageComponents[id] = (form.ComponentModel, form.Count);
_logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); LoadData();
_packageComponents[form.Id] = (form.ComponentModel, form.Count); }
LoadData(); }
} }
}
}
}
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -1,5 +1,6 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace SoftwareInstallationView namespace SoftwareInstallationView
@ -21,77 +22,68 @@ namespace SoftwareInstallationView
} }
private void LoadData() private void LoadData()
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка изделий");
{ }
dataGridView.DataSource = list; catch (Exception ex)
dataGridView.Columns["Id"].Visible = false; {
dataGridView.Columns["PackageComponents"].Visible = false; _logger.LogError(ex, "Ошибка загрузки изделий");
dataGridView.Columns["PackageName"].AutoSizeMode = MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
DataGridViewAutoSizeColumnMode.Fill; MessageBoxIcon.Error);
} }
_logger.LogInformation("Загрузка изделий"); }
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPackage)); var form = DependencyManager.Instance.Resolve<FormPackage>();
if (service is FormPackage form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{ }
LoadData(); }
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); var form = DependencyManager.Instance.Resolve<FormPackage>();
if (service is FormComponent form) 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); {
} LoadData();
LoadData(); }
} }
} }
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show("Удалить запись?", "Вопрос",
{ MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
int id = {
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id =
_logger.LogInformation("Удаление изделия"); Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
try _logger.LogInformation("Удаление изделия");
{ try
if (!_logic.Delete(new PackageBindingModel {
{ if (!_logic.Delete(new PackageBindingModel
Id = id {
})) Id = id
{ }))
throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); {
} throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
LoadData(); }
} LoadData();
catch (Exception ex) }
{ catch (Exception ex)
_logger.LogError(ex, "Ошибка удаления изделия"); {
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError(ex, "Ошибка удаления изделия");
} MessageBox.Show(ex.Message, "Ошибка",
} MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
}
}
private void ButtonRef_Click(object sender, EventArgs e) private void ButtonRef_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();

View File

@ -22,14 +22,8 @@ namespace SoftwareInstallationView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка клиентов");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов");
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -1,6 +1,7 @@
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SoftwareInstallationContracts.DI;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -31,13 +32,7 @@ namespace SoftwareInstallationView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей"); _logger.LogInformation("Загрузка исполнителей");
} }
catch (Exception ex) catch (Exception ex)
@ -49,27 +44,21 @@ namespace SoftwareInstallationView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{
LoadData();
}
} }
} }
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form) 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); LoadData();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
} }
} }
} }

View File

@ -29,14 +29,7 @@ namespace SoftwareInstallationView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_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;
}
_logger.LogInformation("Загрузка списка писем"); _logger.LogInformation("Загрузка списка писем");
} }
catch (Exception ex) catch (Exception ex)

View File

@ -1,100 +1,95 @@
using SoftwareInstallationContracts.BusinessLogicsContracts; using NLog.Extensions.Logging;
using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SoftwareInstallationBusinessLogic.BusinessLogics; using SoftwareInstallationBusinessLogic.BusinessLogics;
using SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationBusinessLogic.OfficePackage.Implements; using SoftwareInstallationBusinessLogic.OfficePackage.Implements;
using SoftwareInstallationBusinessLogic.OfficePackage; using SoftwareInstallationBusinessLogic.OfficePackage;
using SoftwareInstallationBusinessLogic; using SoftwareInstallationBusinessLogic;
using SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationDatabaseImplement; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.DI;
using SoftwareInstallationView; using SoftwareInstallationView;
namespace SoftwareInstallationView namespace ConfectioneryView
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider; /// <summary>
public static ServiceProvider? ServiceProvider => _serviceProvider; /// The main entry point for the application.
/// <summary> /// </summary>
/// The main entry point for the application. [STAThread]
/// </summary> static void Main()
[STAThread] {
static void Main() // To customize application configuration such as set high DPIsettings or default font,
{ // see https://aka.ms/applicationconfiguration.
// To customize application configuration such as set high DPI settings or default font, ApplicationConfiguration.Initialize();
// see https://aka.ms/applicationconfiguration. InitDependency();
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
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"])
});
// ñîçäàåì òàéìåð try
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); {
} var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
catch (Exception ex) mailSender?.MailConfig(new MailConfigBindingModel
{ {
var logger = _serviceProvider.GetService<ILogger>(); MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
} SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
} PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
private static void ConfigureServices(ServiceCollection services) PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
{ });
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPackageStorage, PackageStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPackageLogic, PackageLogic>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>(); // создаем таймер
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
services.AddTransient<AbstractSaveToWord, SaveToWord>(); }
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); catch (Exception ex)
{
var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Ошибка работы с почтой");
}
services.AddTransient<FormMain>(); Application.Run(DependencyManager.Instance.Resolve<FormMain>());
services.AddTransient<FormComponent>(); }
services.AddTransient<FormComponents>(); private static void InitDependency()
services.AddTransient<FormCreateOrder>(); {
services.AddTransient<FormPackage>(); DependencyManager.InitDependency();
services.AddTransient<FormPackageComponent>();
services.AddTransient<FormPackages>(); DependencyManager.Instance.AddLogging(option =>
services.AddTransient<FormReportOrders>(); {
services.AddTransient<FormReportPackageComponents>(); option.SetMinimumLevel(LogLevel.Information);
services.AddTransient<FormViewClients>(); option.AddNLog("nlog.config");
services.AddTransient<FormViewImplementers>(); });
services.AddTransient<FormImplementer>();
services.AddTransient<FormViewMail>(); DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
} DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck(); DependencyManager.Instance.RegisterType<IPackageLogic, PackageLogic>();
} DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormComponent>();
DependencyManager.Instance.RegisterType<FormComponents>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormPackage>();
DependencyManager.Instance.RegisterType<FormPackageComponent>();
DependencyManager.Instance.RegisterType<FormPackages>();
DependencyManager.Instance.RegisterType<FormReportPackageComponents>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormViewClients>();
DependencyManager.Instance.RegisterType<FormViewImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormViewMail>();
}
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
}
} }