Compare commits

...

2 Commits

Author SHA1 Message Date
3bb2a7548c L8 to LC8 2024-05-16 08:40:19 +04:00
ef0cfadde9 8laba 2024-05-16 00:34:01 +04:00
58 changed files with 1506 additions and 909 deletions

View File

@ -17,9 +17,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomobilePlantFileImplemen
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomobilePlantDatabaseImplement", "AutomobilePlantDatabaseImplement\AutomobilePlantDatabaseImplement.csproj", "{D727258B-7717-45AF-B438-B3BE3105E207}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomobilePlantDatabaseImplement", "AutomobilePlantDatabaseImplement\AutomobilePlantDatabaseImplement.csproj", "{D727258B-7717-45AF-B438-B3BE3105E207}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutomobilePlantRestApi", "AutomobilePlantRestApi\AutomobilePlantRestApi.csproj", "{C4C82240-E531-4C99-B519-74DDDBD79326}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomobilePlantRestApi", "AutomobilePlantRestApi\AutomobilePlantRestApi.csproj", "{C4C82240-E531-4C99-B519-74DDDBD79326}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutomobilePlantClientApp", "AutomobilePlantClientApp\AutomobilePlantClientApp.csproj", "{E72BF12B-595D-42B8-B994-B9740A392B02}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomobilePlantClientApp", "AutomobilePlantClientApp\AutomobilePlantClientApp.csproj", "{E72BF12B-595D-42B8-B994-B9740A392B02}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutomobilePlantShopApp", "AutomobilePlantShopApp\AutomobilePlantShopApp.csproj", "{0FC4B81C-8B2D-466F-AE81-8740C6B39817}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutomobilePlantShopApp", "AutomobilePlantShopApp\AutomobilePlantShopApp.csproj", "{0FC4B81C-8B2D-466F-AE81-8740C6B39817}"
EndProject EndProject

View File

@ -0,0 +1,95 @@
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDataModels;
using Microsoft.Extensions.Logging;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace AutomobilePlantBusinessLogic.BusinessLogics
{
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

@ -0,0 +1,20 @@
namespace AutomobilePlantContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
}
}

View File

@ -0,0 +1,14 @@
namespace AutomobilePlantContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

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

View File

@ -0,0 +1,7 @@
namespace AutomobilePlantContracts.BindingModels
{
public class BackUpSaveBinidngModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -18,4 +18,7 @@ namespace AutomobilePlantContracts.BindingModels
public bool IsReaded { get; set; } public bool IsReaded { get; set; }
public string? Reply { get; set; } public string? Reply { get; set; }
} }
public int Id => throw new NotImplementedException();
}
} }

View File

@ -0,0 +1,9 @@
using AutomobilePlantContracts.BindingModels;
namespace AutomobilePlantContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBinidngModel model);
}
}

View File

@ -0,0 +1,63 @@
using Microsoft.Extensions.Logging;
namespace AutomobilePlantContracts.DI
{
/// <summary>
/// Менеджер для работы с зависимостями
/// </summary>
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new UnityDependencyContainer();
}
public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } }
/// <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>
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,38 @@
using Microsoft.Extensions.Logging;
namespace AutomobilePlantContracts.DI
{
/// <summary>
/// Интерфейс установки зависмости между элементами
/// </summary>
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,14 @@
namespace AutomobilePlantContracts.DI
{
/// <summary>
/// Интерфейс для регистрации зависимостей в модулях
/// </summary>
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 AutomobilePlantContracts.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,53 @@
using System.Reflection;
namespace AutomobilePlantContracts.DI
{
/// <summary>
/// Загрузчик данных
/// </summary>
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,38 @@
using Microsoft.Extensions.Logging;
using Unity;
using Unity.Microsoft.Logging;
namespace AutomobilePlantContracts.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

@ -0,0 +1,8 @@
namespace AutomobilePlantContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@ -1,25 +1,18 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantContracts.Attributes;
using System; using AutomobilePlantDataModels.Models;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class CarViewModel : ICarModel public class CarViewModel : ICarModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Car's name")] public int Id { get; set; }
public string CarName { get; set; } = string.Empty; [Column("Car's name", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Price")] public string CarName { get; set; } = string.Empty;
public double Price { get; set; } [Column("Price", width: 100)]
public Dictionary<int, (IComponentModel, int)> CarComponents public double Price { get; set; }
{ [Column(visible: false)]
get; public Dictionary<int, (IComponentModel, int)> CarComponents { get; set; } = new();
set; }
} = new();
}
} }

View File

@ -1,16 +1,17 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantContracts.Attributes;
using System.ComponentModel; using AutomobilePlantDataModels.Models;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class ClientViewModel : IClientModel public class ClientViewModel : IClientModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Client's FIO")] public int Id { get; set; }
public string ClientFIO { get; set; } = string.Empty; [Column(title: "Client's FIO", width: 150)]
[DisplayName("Login (Email)")] public string ClientFIO { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty; [Column(title: "Login (Email)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Password")] public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; [Column(title: "Password", width: 150)]
} public string Password { get; set; } = string.Empty;
}
} }

View File

@ -1,19 +1,15 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantContracts.Attributes;
using System; using AutomobilePlantDataModels.Models;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class ComponentViewModel : IComponentModel public class ComponentViewModel : IComponentModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Component's name")] public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty; [Column("Component's name", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Cost")] public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; } [Column("Cost", width: 100)]
} public double Cost { get; set; }
}
} }

View File

@ -1,22 +1,23 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantContracts.Attributes;
using System.ComponentModel; using AutomobilePlantDataModels.Models;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class ImplementerViewModel : IImplementerModel public class ImplementerViewModel : IImplementerModel
{ {
public int Id { get; set; } [Column(visible: false)]
public int Id { get; set; }
[DisplayName("FIO")] [Column("FIO", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Password")] [Column("Password", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[DisplayName("Work expirience")] [Column("Work expirience", width: 150)]
public int WorkExperience { get; set; } public int WorkExperience { get; set; }
[DisplayName("Qualification")] [Column("Qualification", width: 150)]
public int Qualification { get; set; } public int Qualification { get; set; }
} }
} }

View File

@ -1,24 +1,29 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantContracts.Attributes;
using System.ComponentModel; using AutomobilePlantDataModels.Models;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class MessageInfoViewModel : IMessageInfoModel public class MessageInfoViewModel : IMessageInfoModel
{ {
public string MessageId { get; set; } = string.Empty; [Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; }
[Column("Sender", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty;
[Column("Delivery Date", width: 100)]
public DateTime DateDelivery { get; set; }
[Column("Subject", width: 150)]
public string Subject { get; set; } = string.Empty;
[Column("Body", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
public int? ClientId { get; set; } [Column(visible: false)]
[DisplayName("Sender")] public int Id => throw new NotImplementedException();
public string SenderName { get; set; } = string.Empty;
[DisplayName("Delivery Date")] [Column("Readed", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public DateTime DateDelivery { get; set; } public bool IsReaded { get; set; }
[DisplayName("Subject")] [Column("Reply", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string Subject { get; set; } = string.Empty; public string? Reply { get; set; }
[DisplayName("Body")]
public string Body { get; set; } = string.Empty;
[DisplayName("Readed")]
public bool IsReaded { get; set; }
[DisplayName("Reply")]
public string? Reply { get; set; }
} }
} }

View File

@ -1,36 +1,34 @@
using AutomobilePlantDataModels.Enums; using AutomobilePlantContracts.Attributes;
using AutomobilePlantDataModels.Enums;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantContracts.ViewModels namespace AutomobilePlantContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Number")] [Column("Number", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Id { get; set; } public int Id { get; set; }
public int CarId { get; set; } [Column(visible: false)]
[DisplayName("Car's name")] public int CarId { get; set; }
public string CarName { get; set; } = string.Empty; [Column("Car's name", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int ClientId { get; set; } public string CarName { get; set; } = string.Empty;
[DisplayName("Client's FIO")] [Column(visible: false)]
public string ClientFIO { get; set; } = string.Empty; public int ClientId { get; set; }
public int? ImplementerId { get; set; } [Column("Client's FIO", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
[DisplayName("Implementer's FIO")] public string ClientFIO { get; set; } = string.Empty;
public string ImplementerFIO { get; set; } = string.Empty; [Column(visible: false)]
[DisplayName("Count")] public int? ImplementerId { get; set; }
public int Count { get; set; } [Column("Implementer's FIO", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
[DisplayName("Sum")] public string ImplementerFIO { get; set; } = string.Empty;
public double Sum { get; set; } [Column("Count", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
[DisplayName("Status")] public int Count { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; [Column("Sum", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
[DisplayName("Date of creation")] public double Sum { get; set; }
public DateTime DateCreate { get; set; } = DateTime.Now; [Column("Status", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
[DisplayName("Date of completion")] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime? DateImplement { get; set; } [Column("Date of creation", width: 100)]
} public DateTime DateCreate { get; set; } = DateTime.Now;
[Column("Date of completion", width: 100)]
public DateTime? DateImplement { get; set; }
}
} }

View File

@ -1,7 +1,7 @@
namespace AutomobilePlantDataModels.Models namespace AutomobilePlantDataModels.Models
{ {
public interface IMessageInfoModel public interface IMessageInfoModel : IId
{ {
string MessageId { get; } string MessageId { get; }
int? ClientId { get; } int? ClientId { get; }
string SenderName { get; } string SenderName { get; }

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
@ -20,4 +20,8 @@
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,22 @@
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantDatabaseImplement.Implements;
namespace AutomobilePlantDatabaseImplement
{
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<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,27 @@
using AutomobilePlantContracts.StoragesContracts;
namespace AutomobilePlantDatabaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new AutomobilePlantDatabase();
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,20 +3,26 @@ using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace AutomobilePlantDatabaseImplement.Models namespace AutomobilePlantDatabaseImplement.Models
{ {
public class Car : ICarModel [DataContract]
{ public class Car : ICarModel
public int Id { get; private set; } {
[DataMember]
public int Id { get; private set; }
[Required] [Required]
public string CarName { get; private set; } = string.Empty; [DataMember]
public string CarName { get; private set; } = string.Empty;
[Required] [Required]
public double Price { get; private set; } [DataMember]
public double Price { get; private set; }
private Dictionary<int, (IComponentModel, int)>? _carComponents = null; private Dictionary<int, (IComponentModel, int)>? _carComponents = null;
[NotMapped] [NotMapped]
public Dictionary<int, (IComponentModel, int)> CarComponents [DataMember]
public Dictionary<int, (IComponentModel, int)> CarComponents
{ {
get get
{ {

View File

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

View File

@ -3,17 +3,22 @@ using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace AutomobilePlantDatabaseImplement.Models namespace AutomobilePlantDatabaseImplement.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<CarComponent> CarComponents { get; set; } = new(); public virtual List<CarComponent> CarComponents { get; set; } = new();

View File

@ -2,22 +2,25 @@
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace AutomobilePlantDatabaseImplement.Models namespace AutomobilePlantDatabaseImplement.Models
{ {
public class Implementer : IImplementerModel [DataContract]
{ public class Implementer : IImplementerModel
public int Id { get; private set; } {
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty; [ForeignKey("ImplementerId")]
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; private set; } = new(); public virtual List<Order> Orders { get; private set; } = new();
public static Implementer? Create(ImplementerBindingModel model) public static Implementer? Create(ImplementerBindingModel model)

View File

@ -2,25 +2,37 @@
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace AutomobilePlantDatabaseImplement.Models namespace AutomobilePlantDatabaseImplement.Models
{ {
public class MessageInfo : IMessageInfoModel [DataContract]
public class MessageInfo : IMessageInfoModel
{ {
[Key] [Key]
public string MessageId { get; private set; } = string.Empty; [DataMember]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } [DataMember]
public int? ClientId { get; private set; }
public string SenderName { get; private set; } = string.Empty; [DataMember]
public string SenderName { get; private set; } = string.Empty;
public DateTime DateDelivery { get; private set; } = DateTime.Now; [DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public string Subject { get; private set; } = string.Empty; [DataMember]
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty; [DataMember]
public bool IsReaded { get; private set; } public string Body { get; private set; } = string.Empty;
public string? Reply { get; private set; }
[DataMember]
public bool IsReaded { get; private set; }
[DataMember]
public string? Reply { get; private set; }
public virtual Client? Client { get; private set; } public virtual Client? Client { get; private set; }
@ -64,5 +76,7 @@ namespace AutomobilePlantDatabaseImplement.Models
Reply = Reply, Reply = Reply,
IsReaded = IsReaded, IsReaded = IsReaded,
}; };
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -7,29 +7,40 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Runtime.ConstrainedExecution; using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AutomobilePlantDatabaseImplement.Models namespace AutomobilePlantDatabaseImplement.Models
{ {
public class Order : IOrderModel [DataContract]
{ public class Order : IOrderModel
public int Id { get; private set; } {
[DataMember]
public int Id { get; private set; }
[Required] [Required]
public int CarId { get; private set; } [DataMember]
public int CarId { get; private set; }
[Required] [Required]
public int ClientId { get; private set; } [DataMember]
public int? ImplementerId { get; private set; } public int ClientId { get; private set; }
[DataMember]
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; } = OrderStatus.Неизвестен; [DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required] [Required]
public DateTime DateCreate { get; private set; } = DateTime.Now; [DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; } [DataMember]
public DateTime? DateImplement { get; private set; }
public virtual Car Car { get; private set; } public virtual Car Car { get; private set; }
public virtual Client Client { get; set; } public virtual Client Client { get; set; }
public Implementer? Implementer { get; private set; } public Implementer? Implementer { get; private set; }

View File

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

View File

@ -0,0 +1,22 @@
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantFileImplement.Implements;
namespace AutomobilePlantFileImplement
{
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<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,28 @@
using AutomobilePlantContracts.StoragesContracts;
namespace AutomobilePlantFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
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,27 +1,28 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System; using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class Car : ICarModel [DataContract]
{ public class Car : ICarModel
public string CarName { get; private set; } = string.Empty; {
[DataMember]
public string CarName { get; private set; } = string.Empty;
public double Price { get; private set; } [DataMember]
public double Price { get; private set; }
public int Id { get; private set; } [DataMember]
public int Id { 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)>? _carComponents = null; private Dictionary<int, (IComponentModel, int)>? _carComponents = null;
public Dictionary<int, (IComponentModel, int)> CarComponents [DataMember]
public Dictionary<int, (IComponentModel, int)> CarComponents
{ {
get get
{ {

View File

@ -1,19 +1,25 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class Client : IClientModel [DataContract]
{ public class Client : IClientModel
public int Id { get; private set; } {
[DataMember]
public int Id { get; private set; }
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 static Client? Create(ClientBindingModel model) public static Client? Create(ClientBindingModel model)
{ {

View File

@ -1,20 +1,20 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System; using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class Component : IComponentModel [DataContract]
{ public class Component : IComponentModel
public int Id { get; private set; } {
public string ComponentName { get; private set; } = String.Empty; [DataMember]
public double Cost { get; set; } public int Id { get; private set; }
[DataMember]
public string ComponentName { get; private set; } = String.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model) public static Component? Create(ComponentBindingModel? model)
{ {

View File

@ -1,21 +1,28 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class Implementer : IImplementerModel [DataContract]
{ public class Implementer : IImplementerModel
public int Id { get; private set; } {
[DataMember]
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty; [DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty; [DataMember]
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; } [DataMember]
public int WorkExperience { get; private set; }
public int Qualification { get; private set; } [DataMember]
public int Qualification { get; private set; }
public static Implementer? Create(XElement element) public static Implementer? Create(XElement element)
{ {

View File

@ -1,23 +1,31 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class MessageInfo : IMessageInfoModel [DataContract]
{ public class MessageInfo : IMessageInfoModel
public string MessageId { get; private set; } = string.Empty; {
[DataMember]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } [DataMember]
public int? ClientId { get; private set; }
public string SenderName { get; private set; } = string.Empty; [DataMember]
public string SenderName { get; private set; } = string.Empty;
public DateTime DateDelivery { get; private set; } = DateTime.Now; [DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public string Subject { get; private set; } = string.Empty; [DataMember]
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty; [DataMember]
public string Body { get; private set; } = string.Empty;
public bool IsReaded { get; private set; } public bool IsReaded { get; private set; }
@ -93,5 +101,7 @@ namespace AutomobilePlantFileImplement.Models
new XAttribute("Reply", Reply), new XAttribute("Reply", Reply),
new XAttribute("HasRead", IsReaded) new XAttribute("HasRead", IsReaded)
); );
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -2,26 +2,32 @@
using AutomobilePlantContracts.ViewModels; using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Enums; using AutomobilePlantDataModels.Enums;
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using System; using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models namespace AutomobilePlantFileImplement.Models
{ {
public class Order : IOrderModel [DataContract]
{ public class Order : IOrderModel
public int Id { get; private set; } {
public int CarId { get; private set; } [DataMember]
public int ClientId { get; set; } public int Id { get; private set; }
public int? ImplementerId { get; set; } [DataMember]
public int Count { get; private set; } public int CarId { get; private set; }
public double Sum { get; private set; } [DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public int ClientId { get; set; }
public DateTime DateCreate { get; private set; } = DateTime.Now; [DataMember]
public DateTime? DateImplement { get; private set; } public int? ImplementerId { get; set; }
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
@ -11,4 +11,8 @@
<ProjectReference Include="..\AutomobilePlantDataModels\AutomobilePlantDataModels.csproj" /> <ProjectReference Include="..\AutomobilePlantDataModels\AutomobilePlantDataModels.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,17 @@
using AutomobilePlantContracts.StoragesContracts;
namespace AutomobilePlantListImplement.Implements
{
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,22 @@
using AutomobilePlantContracts.DI;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantListImplement.Implements;
namespace AutomobilePlantListImplement
{
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<ICarStorage, CarStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -62,5 +62,7 @@ namespace AutomobilePlantListImplement.Models
Reply = Reply, Reply = Reply,
IsReaded = IsReaded, IsReaded = IsReaded,
}; };
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -0,0 +1,45 @@
using AutomobilePlantContracts.Attributes;
namespace AutomobilePlantView
{
public 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,17 +1,9 @@
using AutomobilePlantDataModels.Models; using AutomobilePlantDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutomobilePlantContracts.BusinessLogicsContracts; using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.SearchModels; using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.DI;
namespace AutomobilePlantView namespace AutomobilePlantView
{ {
@ -80,48 +72,42 @@ namespace AutomobilePlantView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCarComponent)); var form = DependencyManager.Instance.Resolve<FormCarComponent>();
if (service is FormCarComponent 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 (_carComponents.ContainsKey(form.Id))
{
_carComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_carComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
} }
_logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
if (_carComponents.ContainsKey(form.Id))
{
_carComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_carComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
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(FormCarComponent)); var form = DependencyManager.Instance.Resolve<FormCarComponent>();
if (service is FormCarComponent form) int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _carComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); if (form.ComponentModel == null)
form.Id = id;
form.Count = _carComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ComponentModel == null) return;
{
return;
}
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
_carComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
} }
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
_carComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
} }
} }
} }

View File

@ -1,16 +1,7 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts; using AutomobilePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging; using AutomobilePlantContracts.DI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutomobilePlantView namespace AutomobilePlantView
{ {
@ -33,16 +24,9 @@ namespace AutomobilePlantView
{ {
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["CarName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["CarComponents"].Visible = false;
}
_logger.LogInformation("Загрузка машин");
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки Машин"); _logger.LogError(ex, "Ошибка загрузки Машин");
@ -51,27 +35,21 @@ namespace AutomobilePlantView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCar)); var form = DependencyManager.Instance.Resolve<FormCar>();
if (service is FormCar 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(FormCar)); var form = DependencyManager.Instance.Resolve<FormCar>();
if (service is FormCar 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

@ -24,15 +24,9 @@ namespace AutomobilePlantView
{ {
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)
{ {
_logger.LogError(ex, "Ошибка загрузки клиентов"); _logger.LogError(ex, "Ошибка загрузки клиентов");

View File

@ -1,5 +1,6 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts; using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace AutomobilePlantView namespace AutomobilePlantView
@ -22,15 +23,9 @@ namespace AutomobilePlantView
{ {
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)
{ {
_logger.LogError(ex, "Ошибка загрузки компонентов"); _logger.LogError(ex, "Ошибка загрузки компонентов");
@ -39,27 +34,21 @@ namespace AutomobilePlantView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); var form = DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent 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<FormComponent>();
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();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
} }
} }
} }

View File

@ -1,15 +1,7 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts; using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutomobilePlantView namespace AutomobilePlantView
{ {
@ -32,15 +24,9 @@ namespace AutomobilePlantView
{ {
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["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки исполнителей"); _logger.LogError(ex, "Ошибка загрузки исполнителей");
@ -50,29 +36,23 @@ namespace AutomobilePlantView
} }
private void buttonCreate_Click(object sender, EventArgs e) private void buttonCreate_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 buttonUpdate_Click(object sender, EventArgs e) private void buttonUpdate_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

@ -19,24 +19,13 @@ namespace AutomobilePlantView
{ {
try try
{ {
var list = _logic.ReadList(new() dataGridView.FillAndConfigGrid(_logic.ReadList(null));
{
Page = ((int)numericUpDownPage.Value),
PageSize = ((int)numericUpDownPageSize.Value),
});
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)
{ {
_logger.LogError(ex, "Ошибка загрузки писем"); _logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBox.Show(ex.Message, "Eror", MessageBoxButtons.OK,
MessageBoxIcon.Error); MessageBoxIcon.Error);
} }
} }

View File

@ -20,234 +20,238 @@
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();
toolStripMenuItemCatalogs = new ToolStripMenuItem(); toolStripMenuItemCatalogs = new ToolStripMenuItem();
toolStripMenuItemComponents = new ToolStripMenuItem(); toolStripMenuItemComponents = new ToolStripMenuItem();
toolStripMenuItemCars = new ToolStripMenuItem(); toolStripMenuItemCars = new ToolStripMenuItem();
shopsToolStripMenuItem = new ToolStripMenuItem(); shopsToolStripMenuItem = new ToolStripMenuItem();
shopsSupplyToolStripMenuItem = new ToolStripMenuItem(); shopsSupplyToolStripMenuItem = new ToolStripMenuItem();
sellCarsToolStripMenuItem = new ToolStripMenuItem(); sellCarsToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem();
implementersToolStripMenuItem = new ToolStripMenuItem(); implementersToolStripMenuItem = new ToolStripMenuItem();
reportsToolStripMenuItem = new ToolStripMenuItem(); mailsToolStripMenuItem = new ToolStripMenuItem();
carsListToolStripMenuItem = new ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem();
componentsByCarsToolStripMenuItem = new ToolStripMenuItem(); carsListToolStripMenuItem = new ToolStripMenuItem();
ordersListToolStripMenuItem = new ToolStripMenuItem(); componentsByCarsToolStripMenuItem = new ToolStripMenuItem();
startWorkingsToolStripMenuItem = new ToolStripMenuItem(); ordersListToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); startWorkingsToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); shopsListToolStripMenuItem = new ToolStripMenuItem();
buttonIssuedOrder = new Button(); storeCongestionToolStripMenuItem = new ToolStripMenuItem();
buttonRefresh = new Button(); listOdOrdersByDatesToolStripMenuItem = new ToolStripMenuItem();
shopsListToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView();
storeCongestionToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button();
listOdOrdersByDatesToolStripMenuItem = new ToolStripMenuItem(); buttonIssuedOrder = new Button();
clientsToolStripMenuItem = new ToolStripMenuItem(); buttonRefresh = new Button();
startWorkingsToolStripMenuItem = new ToolStripMenuItem(); createBackupToolStripMenuItem = new ToolStripMenuItem();
mailsToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout();
menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout();
SuspendLayout(); //
// // menuStrip1
// menuStrip1 //
// menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItemCatalogs, reportsToolStripMenuItem, startWorkingsToolStripMenuItem, createBackupToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItemCatalogs, reportsToolStripMenuItem, startWorkingsToolStripMenuItem }); menuStrip1.Location = new Point(0, 0);
menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1";
menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(800, 24);
menuStrip1.Size = new Size(800, 24); menuStrip1.TabIndex = 0;
menuStrip1.TabIndex = 0; menuStrip1.Text = "menuStrip1";
menuStrip1.Text = "menuStrip1"; //
// // shopsToolStripMenuItem
// toolStripMenuItemCatalogs //
// shopsToolStripMenuItem.Name = "shopsToolStripMenuItem";
toolStripMenuItemCatalogs.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItemComponents, toolStripMenuItemCars, clientsToolStripMenuItem, shopsToolStripMenuItem, shopsSupplyToolStripMenuItem, sellCarsToolStripMenuItem, implementersToolStripMenuItem, mailsToolStripMenuItem }); shopsToolStripMenuItem.Size = new Size(147, 22);
toolStripMenuItemCatalogs.Name = "toolStripMenuItemCatalogs"; shopsToolStripMenuItem.Text = "Shops";
toolStripMenuItemCatalogs.Size = new Size(65, 20); shopsToolStripMenuItem.Click += shopsToolStripMenuItem_Click;
toolStripMenuItemCatalogs.Text = "Catalogs"; //
// // shopsSupplyToolStripMenuItem
// toolStripMenuItemComponents //
// shopsSupplyToolStripMenuItem.Name = "shopsSupplyToolStripMenuItem";
toolStripMenuItemComponents.Name = "toolStripMenuItemComponents"; shopsSupplyToolStripMenuItem.Size = new Size(147, 22);
toolStripMenuItemComponents.Size = new Size(180, 22); shopsSupplyToolStripMenuItem.Text = "Shop's supply";
toolStripMenuItemComponents.Text = "Components"; shopsSupplyToolStripMenuItem.Click += shopsSupplyToolStripMenuItem_Click;
toolStripMenuItemComponents.Click += ComponentsToolStripMenuItem_Click; //
// // sellCarsToolStripMenuItem
// toolStripMenuItemCars //
// sellCarsToolStripMenuItem.Name = "sellCarsToolStripMenuItem";
toolStripMenuItemCars.Name = "toolStripMenuItemCars"; sellCarsToolStripMenuItem.Size = new Size(147, 22);
toolStripMenuItemCars.Size = new Size(180, 22); sellCarsToolStripMenuItem.Text = "Sell Cars";
toolStripMenuItemCars.Text = "Cars"; sellCarsToolStripMenuItem.Click += sellCarsToolStripMenuItem_Click;
toolStripMenuItemCars.Click += CarsToolStripMenuItem_Click; //
// // toolStripMenuItemCatalogs
// shopsToolStripMenuItem //
// toolStripMenuItemCatalogs.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItemComponents, toolStripMenuItemCars, clientsToolStripMenuItem, implementersToolStripMenuItem, mailsToolStripMenuItem });
shopsToolStripMenuItem.Name = "shopsToolStripMenuItem"; toolStripMenuItemCatalogs.Name = "toolStripMenuItemCatalogs";
shopsToolStripMenuItem.Size = new Size(147, 22); toolStripMenuItemCatalogs.Size = new Size(65, 20);
shopsToolStripMenuItem.Text = "Shops"; toolStripMenuItemCatalogs.Text = "Catalogs";
shopsToolStripMenuItem.Click += shopsToolStripMenuItem_Click; //
// // toolStripMenuItemComponents
// shopsSupplyToolStripMenuItem //
// toolStripMenuItemComponents.Name = "toolStripMenuItemComponents";
shopsSupplyToolStripMenuItem.Name = "shopsSupplyToolStripMenuItem"; toolStripMenuItemComponents.Size = new Size(147, 22);
shopsSupplyToolStripMenuItem.Size = new Size(147, 22); toolStripMenuItemComponents.Text = "Components";
shopsSupplyToolStripMenuItem.Text = "Shop's supply"; toolStripMenuItemComponents.Click += ComponentsToolStripMenuItem_Click;
shopsSupplyToolStripMenuItem.Click += shopsSupplyToolStripMenuItem_Click; //
// // toolStripMenuItemCars
// sellCarsToolStripMenuItem //
// toolStripMenuItemCars.Name = "toolStripMenuItemCars";
sellCarsToolStripMenuItem.Name = "sellCarsToolStripMenuItem"; toolStripMenuItemCars.Size = new Size(147, 22);
sellCarsToolStripMenuItem.Size = new Size(147, 22); toolStripMenuItemCars.Text = "Cars";
sellCarsToolStripMenuItem.Text = "Sell Cars"; toolStripMenuItemCars.Click += CarsToolStripMenuItem_Click;
sellCarsToolStripMenuItem.Click += sellCarsToolStripMenuItem_Click; //
// // clientsToolStripMenuItem
// clientsToolStripMenuItem //
// clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; clientsToolStripMenuItem.Size = new Size(147, 22);
clientsToolStripMenuItem.Size = new Size(180, 22); clientsToolStripMenuItem.Text = "Clients";
clientsToolStripMenuItem.Text = "Clients"; clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click;
clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click; //
// // implementersToolStripMenuItem
// implementersToolStripMenuItem //
// implementersToolStripMenuItem.Name = "implementersToolStripMenuItem";
implementersToolStripMenuItem.Name = "implementersToolStripMenuItem"; implementersToolStripMenuItem.Size = new Size(147, 22);
implementersToolStripMenuItem.Size = new Size(180, 22); implementersToolStripMenuItem.Text = "Implementers";
implementersToolStripMenuItem.Text = "Implementers"; implementersToolStripMenuItem.Click += implementersToolStripMenuItem_Click;
implementersToolStripMenuItem.Click += implementersToolStripMenuItem_Click; //
// // mailsToolStripMenuItem
// reportsToolStripMenuItem //
// mailsToolStripMenuItem.Name = "mailsToolStripMenuItem";
reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { carsListToolStripMenuItem, componentsByCarsToolStripMenuItem, ordersListToolStripMenuItem, shopsListToolStripMenuItem, storeCongestionToolStripMenuItem, listOdOrdersByDatesToolStripMenuItem }); mailsToolStripMenuItem.Size = new Size(147, 22);
reportsToolStripMenuItem.Name = "reportsToolStripMenuItem"; mailsToolStripMenuItem.Text = "mails";
reportsToolStripMenuItem.Size = new Size(59, 20); mailsToolStripMenuItem.Click += mailsToolStripMenuItem_Click;
reportsToolStripMenuItem.Text = "Reports"; //
// // reportsToolStripMenuItem
// carsListToolStripMenuItem //
// reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { carsListToolStripMenuItem, componentsByCarsToolStripMenuItem, ordersListToolStripMenuItem });
carsListToolStripMenuItem.Name = "carsListToolStripMenuItem"; reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
carsListToolStripMenuItem.Size = new Size(186, 22); reportsToolStripMenuItem.Size = new Size(59, 20);
carsListToolStripMenuItem.Text = "Cars' list"; reportsToolStripMenuItem.Text = "Reports";
carsListToolStripMenuItem.Click += carsListToolStripMenuItem_Click; //
// // carsListToolStripMenuItem
// componentsByCarsToolStripMenuItem //
// carsListToolStripMenuItem.Name = "carsListToolStripMenuItem";
componentsByCarsToolStripMenuItem.Name = "componentsByCarsToolStripMenuItem"; carsListToolStripMenuItem.Size = new Size(186, 22);
componentsByCarsToolStripMenuItem.Size = new Size(186, 22); carsListToolStripMenuItem.Text = "Cars' list";
componentsByCarsToolStripMenuItem.Text = "Components' by cars"; carsListToolStripMenuItem.Click += carsListToolStripMenuItem_Click;
componentsByCarsToolStripMenuItem.Click += componentsByCarsToolStripMenuItem_Click; //
// // componentsByCarsToolStripMenuItem
// ordersListToolStripMenuItem //
// componentsByCarsToolStripMenuItem.Name = "componentsByCarsToolStripMenuItem";
ordersListToolStripMenuItem.Name = "ordersListToolStripMenuItem"; componentsByCarsToolStripMenuItem.Size = new Size(186, 22);
ordersListToolStripMenuItem.Size = new Size(186, 22); componentsByCarsToolStripMenuItem.Text = "Components' by cars";
ordersListToolStripMenuItem.Text = "Orders' list"; componentsByCarsToolStripMenuItem.Click += componentsByCarsToolStripMenuItem_Click;
ordersListToolStripMenuItem.Click += ordersListToolStripMenuItem_Click; //
// // ordersListToolStripMenuItem
// startWorkingsToolStripMenuItem //
// ordersListToolStripMenuItem.Name = "ordersListToolStripMenuItem";
startWorkingsToolStripMenuItem.Name = "startWorkingsToolStripMenuItem"; ordersListToolStripMenuItem.Size = new Size(186, 22);
startWorkingsToolStripMenuItem.Size = new Size(94, 20); ordersListToolStripMenuItem.Text = "Orders' list";
startWorkingsToolStripMenuItem.Text = "Start workings"; ordersListToolStripMenuItem.Click += ordersListToolStripMenuItem_Click;
startWorkingsToolStripMenuItem.Click += startWorkingsToolStripMenuItem_Click; //
// // startWorkingsToolStripMenuItem
// dataGridView //
// startWorkingsToolStripMenuItem.Name = "startWorkingsToolStripMenuItem";
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; startWorkingsToolStripMenuItem.Size = new Size(94, 20);
dataGridView.Location = new Point(12, 27); startWorkingsToolStripMenuItem.Text = "Start workings";
dataGridView.Name = "dataGridView"; startWorkingsToolStripMenuItem.Click += startWorkingsToolStripMenuItem_Click;
dataGridView.RowTemplate.Height = 25; //
dataGridView.Size = new Size(659, 411); // dataGridView
dataGridView.TabIndex = 1; //
// dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// buttonCreateOrder dataGridView.Location = new Point(12, 27);
// dataGridView.Name = "dataGridView";
buttonCreateOrder.Location = new Point(677, 27); dataGridView.RowTemplate.Height = 25;
buttonCreateOrder.Name = "buttonCreateOrder"; dataGridView.Size = new Size(659, 411);
buttonCreateOrder.Size = new Size(111, 23); dataGridView.TabIndex = 1;
buttonCreateOrder.TabIndex = 2; //
buttonCreateOrder.Text = "Create order"; // buttonCreateOrder
buttonCreateOrder.UseVisualStyleBackColor = true; //
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Location = new Point(677, 27);
// buttonCreateOrder.Name = "buttonCreateOrder";
// buttonIssuedOrder buttonCreateOrder.Size = new Size(111, 23);
// buttonCreateOrder.TabIndex = 2;
buttonIssuedOrder.Location = new Point(677, 56); buttonCreateOrder.Text = "Create order";
buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Size = new Size(111, 23); buttonCreateOrder.Click += ButtonCreateOrder_Click;
buttonIssuedOrder.TabIndex = 5; //
buttonIssuedOrder.Text = "Order is issued"; // buttonIssuedOrder
buttonIssuedOrder.UseVisualStyleBackColor = true; //
buttonIssuedOrder.Click += ButtonIssuedOrder_Click; buttonIssuedOrder.Location = new Point(677, 56);
// buttonIssuedOrder.Name = "buttonIssuedOrder";
// buttonRefresh buttonIssuedOrder.Size = new Size(111, 23);
// buttonIssuedOrder.TabIndex = 5;
buttonRefresh.Location = new Point(677, 85); buttonIssuedOrder.Text = "Order is issued";
buttonRefresh.Name = "buttonRefresh"; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonRefresh.Size = new Size(111, 23); buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
buttonRefresh.TabIndex = 6; //
buttonRefresh.Text = "Refresh"; // buttonRefresh
buttonRefresh.UseVisualStyleBackColor = true; //
buttonRefresh.Click += ButtonRef_Click; buttonRefresh.Location = new Point(677, 85);
// buttonRefresh.Name = "buttonRefresh";
// shopsListToolStripMenuItem buttonRefresh.Size = new Size(111, 23);
// buttonRefresh.TabIndex = 6;
shopsListToolStripMenuItem.Name = "shopsListToolStripMenuItem"; buttonRefresh.Text = "Refresh";
shopsListToolStripMenuItem.Size = new Size(192, 22); buttonRefresh.UseVisualStyleBackColor = true;
shopsListToolStripMenuItem.Text = "Shops' list"; buttonRefresh.Click += ButtonRef_Click;
shopsListToolStripMenuItem.Click += shopsListToolStripMenuItem_Click; //
// // shopsListToolStripMenuItem
// storeCongestionToolStripMenuItem //
// shopsListToolStripMenuItem.Name = "shopsListToolStripMenuItem";
storeCongestionToolStripMenuItem.Name = "storeCongestionToolStripMenuItem"; shopsListToolStripMenuItem.Size = new Size(192, 22);
storeCongestionToolStripMenuItem.Size = new Size(192, 22); shopsListToolStripMenuItem.Text = "Shops' list";
storeCongestionToolStripMenuItem.Text = "Store congestion"; shopsListToolStripMenuItem.Click += shopsListToolStripMenuItem_Click;
storeCongestionToolStripMenuItem.Click += storeCongestionToolStripMenuItem_Click; //
// // storeCongestionToolStripMenuItem
// listOdOrdersByDatesToolStripMenuItem //
// storeCongestionToolStripMenuItem.Name = "storeCongestionToolStripMenuItem";
listOdOrdersByDatesToolStripMenuItem.Name = "listOdOrdersByDatesToolStripMenuItem"; storeCongestionToolStripMenuItem.Size = new Size(192, 22);
listOdOrdersByDatesToolStripMenuItem.Size = new Size(192, 22); storeCongestionToolStripMenuItem.Text = "Store congestion";
listOdOrdersByDatesToolStripMenuItem.Text = "List od orders by dates"; storeCongestionToolStripMenuItem.Click += storeCongestionToolStripMenuItem_Click;
listOdOrdersByDatesToolStripMenuItem.Click += listOdOrdersByDatesToolStripMenuItem_Click; //
// // listOdOrdersByDatesToolStripMenuItem
// clientsToolStripMenuItem //
// startWorkingsToolStripMenuItem listOdOrdersByDatesToolStripMenuItem.Name = "listOdOrdersByDatesToolStripMenuItem";
// mailsToolStripMenuItem listOdOrdersByDatesToolStripMenuItem.Size = new Size(192, 22);
// listOdOrdersByDatesToolStripMenuItem.Text = "List od orders by dates";
mailsToolStripMenuItem.Name = "mailsToolStripMenuItem"; listOdOrdersByDatesToolStripMenuItem.Click += listOdOrdersByDatesToolStripMenuItem_Click;
mailsToolStripMenuItem.Size = new Size(180, 22); //
mailsToolStripMenuItem.Text = "mails"; // createBackupToolStripMenuItem
mailsToolStripMenuItem.Click += mailsToolStripMenuItem_Click; //
// createBackupToolStripMenuItem.Name = "createBackupToolStripMenuItem";
// FormMain createBackupToolStripMenuItem.Size = new Size(95, 20);
// createBackupToolStripMenuItem.Text = "Create backup";
AutoScaleDimensions = new SizeF(7F, 15F); createBackupToolStripMenuItem.Click += createBackupToolStripMenuItem_Click;
AutoScaleMode = AutoScaleMode.Font; //
ClientSize = new Size(800, 450); // FormMain
Controls.Add(buttonRefresh); //
Controls.Add(buttonIssuedOrder); AutoScaleDimensions = new SizeF(7F, 15F);
Controls.Add(buttonCreateOrder); AutoScaleMode = AutoScaleMode.Font;
Controls.Add(dataGridView); ClientSize = new Size(800, 450);
Controls.Add(menuStrip1); Controls.Add(buttonRefresh);
Name = "FormMain"; Controls.Add(buttonIssuedOrder);
Text = "Automobile plant"; Controls.Add(buttonCreateOrder);
Load += FormMain_Load; Controls.Add(dataGridView);
menuStrip1.ResumeLayout(false); Controls.Add(menuStrip1);
menuStrip1.PerformLayout(); Name = "FormMain";
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); Text = "Automobile plant";
ResumeLayout(false); Load += FormMain_Load;
PerformLayout(); menuStrip1.ResumeLayout(false);
} menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private MenuStrip menuStrip1; private MenuStrip menuStrip1;
private ToolStripMenuItem toolStripMenuItemCatalogs; private ToolStripMenuItem toolStripMenuItemCatalogs;
private ToolStripMenuItem toolStripMenuItemComponents; private ToolStripMenuItem toolStripMenuItemComponents;
private ToolStripMenuItem toolStripMenuItemCars; private ToolStripMenuItem toolStripMenuItemCars;
@ -269,5 +273,6 @@
private ToolStripMenuItem implementersToolStripMenuItem; private ToolStripMenuItem implementersToolStripMenuItem;
private ToolStripMenuItem startWorkingsToolStripMenuItem; private ToolStripMenuItem startWorkingsToolStripMenuItem;
private ToolStripMenuItem mailsToolStripMenuItem; private ToolStripMenuItem mailsToolStripMenuItem;
} private ToolStripMenuItem createBackupToolStripMenuItem;
}
} }

View File

@ -1,284 +1,276 @@
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.BusinessLogicsContracts; using AutomobilePlantContracts.BusinessLogicsContracts;
using AutomobilePlantContracts.DI;
using AutomobilePlantDataModels.Enums; using AutomobilePlantDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace AutomobilePlantView namespace AutomobilePlantView
{ {
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;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) private readonly IBackUpLogic _backUpLogic;
{ public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
InitializeComponent(); {
_logger = logger; InitializeComponent();
_orderLogic = orderLogic; _logger = logger;
_reportLogic = reportLogic; _orderLogic = orderLogic;
_workProcess = workProcess; _reportLogic = reportLogic;
} _workProcess = workProcess;
private void FormMain_Load(object sender, EventArgs e) _backUpLogic = backUpLogic;
{ }
LoadData(); private void FormMain_Load(object sender, EventArgs e)
} {
private void LoadData() LoadData();
{ }
_logger.LogInformation("Загрузка заказов"); private void LoadData()
try {
{ _logger.LogInformation("Загрузка заказов");
var list = _orderLogic.ReadList(null); try
if (list != null) {
{ dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
dataGridView.DataSource = list; _logger.LogInformation("Загрузка заказов");
dataGridView.Columns["CarId"].Visible = false; }
dataGridView.Columns["ClientId"].Visible = false; catch (Exception ex)
dataGridView.Columns["ImplementerId"].Visible = false; {
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormComponents>();
form.ShowDialog();
}
private void CarsToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormCars>();
form.ShowDialog();
}
} private void shopsToolStripMenuItem_Click(object sender, EventArgs e)
_logger.LogInformation("Загрузка заказов"); {
} var service = Program.ServiceProvider?.GetService(typeof(FormShops));
catch (Exception ex) if (service is FormShops form)
{ {
_logger.LogError(ex, "Ошибка загрузки заказов"); form.ShowDialog();
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); }
} }
}
// управление менюшкой private void shopsSupplyToolStripMenuItem_Click(object sender, EventArgs e)
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) {
{ var service = Program.ServiceProvider?.GetService(typeof(FormShopSupply));
var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); if (service is FormShopSupply form)
if (service is FormComponents form) {
{ form.ShowDialog();
form.ShowDialog(); }
} }
}
private void CarsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCars));
if (service is FormCars form)
{
form.ShowDialog();
}
}
private void shopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void shopsSupplyToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSupply));
if (service is FormShopSupply form)
{
form.ShowDialog();
}
}
private void clientsToolStripMenuItem_Click(object sender, EventArgs e) private void clientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormClients)); var form = DependencyManager.Instance.Resolve<FormClients>();
if (service is FormClients form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void implementersToolStripMenuItem_Click(object sender, EventArgs e) private void implementersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); var form = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormImplementers form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void mailsToolStripMenuItem_Click(object sender, EventArgs e) private void mailsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormMails)); var form = DependencyManager.Instance.Resolve<FormMails>();
if (service is FormMails form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void carsListToolStripMenuItem_Click(object sender, EventArgs e) private void carsListToolStripMenuItem_Click(object sender, EventArgs e)
{ {
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK) if (dialog.ShowDialog() == DialogResult.OK)
{ {
_reportLogic.SaveCarsToWordFile(new ReportBindingModel _reportLogic.SaveCarsToWordFile(new ReportBindingModel
{ {
FileName = dialog.FileName FileName = dialog.FileName
}); });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
} }
private void componentsByCarsToolStripMenuItem_Click(object sender, EventArgs e) private void componentsByCarsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportCarComponents)); var form = DependencyManager.Instance.Resolve<FormReportCarComponents>();
if (service is FormReportCarComponents form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void ordersListToolStripMenuItem_Click(object sender, EventArgs e) private void ordersListToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var form = DependencyManager.Instance.Resolve<FormReportOrders>();
if (service is FormReportOrders form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void sellCarsToolStripMenuItem_Click(object sender, EventArgs e) private void sellCarsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormShopSell)); var service = Program.ServiceProvider?.GetService(typeof(FormShopSell));
if (service is FormShopSell form) if (service is FormShopSell form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void shopsListToolStripMenuItem_Click(object sender, EventArgs e) private void shopsListToolStripMenuItem_Click(object sender, EventArgs e)
{ {
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK) if (dialog.ShowDialog() == DialogResult.OK)
{ {
_reportLogic.SaveShopsToWordFile(new ReportBindingModel _reportLogic.SaveShopsToWordFile(new ReportBindingModel
{ {
FileName = dialog.FileName FileName = dialog.FileName
}); });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
} }
private void storeCongestionToolStripMenuItem_Click(object sender, EventArgs e) private void storeCongestionToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopCars)); var service = Program.ServiceProvider?.GetService(typeof(FormReportShopCars));
if (service is FormReportShopCars form) if (service is FormReportShopCars form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void startWorkingsToolStripMenuItem_Click(object sender, EventArgs e) private void startWorkingsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); _workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(), _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
private void listOdOrdersByDatesToolStripMenuItem_Click(object sender, EventArgs e) private void listOdOrdersByDatesToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportDateOrders)); var service = Program.ServiceProvider?.GetService(typeof(FormReportDateOrders));
if (service is FormReportDateOrders form) if (service is FormReportDateOrders form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
// управление заказами private void createBackupToolStripMenuItem_Click(object sender, EventArgs e)
private void ButtonCreateOrder_Click(object sender, EventArgs e) {
{ try
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); {
if (service is FormCreateOrder form) if (_backUpLogic != null)
{ {
form.ShowDialog(); var fbd = new FolderBrowserDialog();
LoadData(); if (fbd.ShowDialog() == DialogResult.OK)
} {
} _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel
private OrderBindingModel CreateBindingModel(int id) {
{ FolderName = fbd.SelectedPath
return new OrderBindingModel });
{ MessageBox.Show("Backup created", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Id = id, }
CarId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["CarId"].Value), }
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), }
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), catch (Exception ex)
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), {
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}; }
} }
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(CreateBindingModel(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(CreateBindingModel(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(CreateBindingModel(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 ButtonCreateOrder_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
form.ShowDialog();
LoadData();
}
private OrderBindingModel CreateBindingModel(int id)
{
return new OrderBindingModel
{
Id = id,
CarId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["CarId"].Value),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
};
}
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(CreateBindingModel(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(CreateBindingModel(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(CreateBindingModel(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();
}
}
} }

View File

@ -9,13 +9,12 @@ using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using AutomobilePlantBusinessLogic.MailWorker; using AutomobilePlantBusinessLogic.MailWorker;
using AutomobilePlantContracts.BindingModels; using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.DI;
namespace AutomobilePlantView namespace AutomobilePlantView
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
@ -25,14 +24,12 @@ namespace AutomobilePlantView
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
var services = new ServiceCollection(); InitDependency();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
try try
{ {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>(); var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel mailSender?.MailConfig(new MailConfigBindingModel
{ {
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
@ -45,61 +42,57 @@ namespace AutomobilePlantView
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
} }
catch (Exception ex) catch (Exception ex)
{ {
var logger = _serviceProvider.GetService<ILogger>(); var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Ошибка работы с почтой"); logger?.LogError(ex, "Ошибка работы с почтой");
} }
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); Application.Run(DependencyManager.Instance.Resolve<FormMain>());
} }
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck(); private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
private static void ConfigureServices(ServiceCollection services) private static void InitDependency()
{ {
services.AddLogging(option => DependencyManager.InitDependency();
{
option.SetMinimumLevel(LogLevel.Information); DependencyManager.Instance.AddLogging(option =>
option.AddNLog("nlog.config"); {
}); option.SetMinimumLevel(LogLevel.Information);
services.AddTransient<IComponentStorage, ComponentStorage>(); option.AddNLog("nlog.config");
services.AddTransient<IOrderStorage, OrderStorage>(); });
services.AddTransient<ICarStorage, CarStorage>(); DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
services.AddTransient<IClientStorage, ClientStorage>(); DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); DependencyManager.Instance.RegisterType<ICarLogic, CarLogic>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>(); DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>(); DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<ICarLogic, CarLogic>(); DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
services.AddTransient<IImplementerLogic, ImplementerLogic>(); DependencyManager.Instance.RegisterType<IShopLogic, ShopLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
services.AddTransient<IShopStorage, ShopStorage>(); DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>();
services.AddTransient<IShopLogic, ShopLogic>(); DependencyManager.Instance.RegisterType<FormMain>();
services.AddTransient<IWorkProcess, WorkModeling>(); DependencyManager.Instance.RegisterType<FormComponent>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>(); DependencyManager.Instance.RegisterType<FormComponents>();
services.AddTransient<FormMain>(); DependencyManager.Instance.RegisterType<FormCreateOrder>();
services.AddTransient<FormComponent>(); DependencyManager.Instance.RegisterType<FormCar>();
services.AddTransient<FormComponents>(); DependencyManager.Instance.RegisterType<FormCarComponent>();
services.AddTransient<FormCreateOrder>(); DependencyManager.Instance.RegisterType<FormCars>();
services.AddTransient<FormCar>(); DependencyManager.Instance.RegisterType<FormReportCarComponents>();
services.AddTransient<FormCarComponent>(); DependencyManager.Instance.RegisterType<FormReportOrders>();
services.AddTransient<FormCars>(); DependencyManager.Instance.RegisterType<FormReportShopCars>();
services.AddTransient<FormReportCarComponents>(); DependencyManager.Instance.RegisterType<FormReportDateOrders>();
services.AddTransient<FormReportOrders>(); DependencyManager.Instance.RegisterType<FormClients>();
services.AddTransient<FormReportShopCars>(); DependencyManager.Instance.RegisterType<FormImplementers>();
services.AddTransient<FormReportDateOrders>(); DependencyManager.Instance.RegisterType<FormImplementer>();
services.AddTransient<FormShop>(); DependencyManager.Instance.RegisterType<FormMails>();
services.AddTransient<FormShops>(); DependencyManager.Instance.RegisterType<FormShop>();
services.AddTransient<FormShopSupply>(); DependencyManager.Instance.RegisterType<FormShops>();
services.AddTransient<FormShopSell>(); DependencyManager.Instance.RegisterType<FormShopSupply>();
services.AddTransient<FormClients>(); DependencyManager.Instance.RegisterType<FormShopSell>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormMails>();
services.AddTransient<FormMail>();
} }
} }
} }