Лаба 1 - надо доделать

This commit is contained in:
[USERNAME] 2024-02-09 02:29:42 +04:00
parent c840d50df7
commit 82e02eea35
31 changed files with 2135 additions and 79 deletions

View File

@ -5,11 +5,13 @@ VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantView", "MotorPlantView\MotorPlantView.csproj", "{CEF9F4E9-71DB-4076-B8D5-3E27B49939BE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantDataModels", "MotorPlantDataModels\MotorPlantDataModels.csproj", "{4D502066-1BDE-4B18-9E3E-7FDBEF2540F1}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantDataModels", "MotorPlantDataModels\MotorPlantDataModels.csproj", "{4D502066-1BDE-4B18-9E3E-7FDBEF2540F1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantContracts", "MotorPlantContracts\MotorPlantContracts.csproj", "{1017E6F5-EB0E-41FC-8F8B-2E166CA6AF18}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantContracts", "MotorPlantContracts\MotorPlantContracts.csproj", "{1017E6F5-EB0E-41FC-8F8B-2E166CA6AF18}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantBusinessLogic", "MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{EEA707BB-A528-4FC9-866B-5E82B3E5A881}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantBusinessLogic", "MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{EEA707BB-A528-4FC9-866B-5E82B3E5A881}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantListImplement", "MotorPlantListImplement\MotorPlantListImplement.csproj", "{B40FC8FC-D3FB-434C-9A13-F6E1BF88B36D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -33,6 +35,10 @@ Global
{EEA707BB-A528-4FC9-866B-5E82B3E5A881}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEA707BB-A528-4FC9-866B-5E82B3E5A881}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEA707BB-A528-4FC9-866B-5E82B3E5A881}.Release|Any CPU.Build.0 = Release|Any CPU
{B40FC8FC-D3FB-434C-9A13-F6E1BF88B36D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B40FC8FC-D3FB-434C-9A13-F6E1BF88B36D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B40FC8FC-D3FB-434C-9A13-F6E1BF88B36D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B40FC8FC-D3FB-434C-9A13-F6E1BF88B36D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -3,22 +3,23 @@ using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace MotorPlantBusinessLogic.BusinessLogics
{
public class EngineLogic : IEngineLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public EngineLogic(ILogger<ComponentLogic> logger, IComponentStorage componentStorage)
private readonly IEngineStorage _EngineStorage;
public EngineLogic(ILogger<EngineLogic> logger, IEngineStorage EngineStorage)
{
_logger = logger;
_componentStorage = componentStorage;
_EngineStorage = EngineStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
public List<EngineViewModel>? ReadList(EngineSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{ Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
_logger.LogInformation("ReadList. EngineName:{EngineName}.Id:{Id}", model?.EngineName, model?.Id);
var list = model == null ? _EngineStorage.GetFullList() : _EngineStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
@ -27,14 +28,15 @@ namespace MotorPlantBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentSearchModel model)
public EngineViewModel? ReadElement(EngineSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}.Id:{ Id}", model.ComponentName, model.Id);
var element = _componentStorage.GetElement(model);
_logger.LogInformation("ReadElement. EngineName:{EngineName}.Id:{Id}", model.EngineName, model.Id);
var element = _EngineStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
@ -43,39 +45,42 @@ namespace MotorPlantBusinessLogic.BusinessLogics
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ComponentBindingModel model)
public bool Create(EngineBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
if (_EngineStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel model)
public bool Update(EngineBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
if (_EngineStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel model)
public bool Delete(EngineBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_componentStorage.Delete(model) == null)
if (_EngineStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel model, bool withParams =
true)
private void CheckModel(EngineBindingModel model, bool withParams = true)
{
if (model == null)
{
@ -85,23 +90,22 @@ namespace MotorPlantBusinessLogic.BusinessLogics
{
return;
}
if (string.IsNullOrEmpty(model.ComponentName))
if (string.IsNullOrEmpty(model.EngineName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ComponentName));
throw new ArgumentNullException("Нет названия изделия", nameof(model.EngineName));
}
if (model.Cost <= 0)
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}.Cost:{ Cost}. Id: { Id}", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel
_logger.LogInformation("Engine. EngineName:{EngineName}.Price:{Cost}. Id: {Id}", model.EngineName, model.Price, model.Id);
var element = _EngineStorage.GetElement(new EngineSearchModel
{
ComponentName = model.ComponentName
EngineName = model.EngineName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}

View File

@ -6,6 +6,15 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantContracts\MotorPlantContracts.csproj" />
</ItemGroup>

View File

@ -0,0 +1,132 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
using MotorPlantDataModels.Enums;
namespace MotorPlantBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. OrderId:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ToNextStatus(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return ToNextStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ToNextStatus(model, OrderStatus.Выдан);
}
public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel()
{
Id = model.Id
});
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
model.EngineId = element.EngineId;
model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement;
model.Status = element.Status;
model.Count = element.Count;
model.Sum = element.Sum;
if (model.Status != orderStatus - 1)
{
_logger.LogWarning("Status update to " + orderStatus + " operation failed");
return false;
}
model.Status = orderStatus;
if (model.Status == OrderStatus.Выдан)
{
model.DateImplement = DateTime.Now;
}
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Changing status operation faled");
return false;
}
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}");
}
_logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id);
}
}
}

View File

@ -6,6 +6,15 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantDataModels\MotorPlantDataModels.csproj" />
</ItemGroup>

View File

@ -6,4 +6,13 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,41 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
namespace MotorPlantListImplement
{
public class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,100 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
namespace MotorPlantListImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataListSingleton _source;
public ComponentStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
var result = new List<ComponentViewModel>();
foreach (var component in _source.Components)
{
result.Add(component.GetViewModel);
}
return result;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
var result = new List<ComponentViewModel>();
if (string.IsNullOrEmpty(model.ComponentName))
{
return result;
}
foreach (var component in _source.Components)
{
if (component.ComponentName.Contains(model.ComponentName))
{
result.Add(component.GetViewModel);
}
}
return result;
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
foreach (var component in _source.Components)
{
if ((!string.IsNullOrEmpty(model.ComponentName) && component.ComponentName == model.ComponentName) ||
(model.Id.HasValue && component.Id == model.Id))
{
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = 1;
foreach (var component in _source.Components)
{
if (model.Id <= component.Id)
{
model.Id = component.Id + 1;
}
}
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
_source.Components.Add(newComponent);
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
foreach (var component in _source.Components)
{
if (component.Id == model.Id)
{
component.Update(model);
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
for (int i = 0; i < _source.Components.Count; ++i)
{
if (_source.Components[i].Id == model.Id)
{
var element = _source.Components[i];
_source.Components.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,26 @@
using MotorPlantListImplement.Models;
namespace MotorPlantListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Engine> Engines { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Engines = new List<Engine>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,50 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
namespace MotorPlantListImplement.Models
{
public class Engine : IEngineModel
{
public int Id { get; private set; }
public string EngineName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get;
private set;
} = new Dictionary<int, (IComponentModel, int)>();
public static Engine? Create(EngineBindingModel? model)
{
if (model == null)
{
return null;
}
return new Engine()
{
Id = model.Id,
EngineName = model.EngineName,
Price = model.Price,
EngineComponents = model.EngineComponents
};
}
public void Update(EngineBindingModel? model)
{
if (model == null)
{
return;
}
EngineName = model.EngineName;
Price = model.Price;
EngineComponents = model.EngineComponents;
}
public EngineViewModel GetViewModel => new()
{
Id = Id,
EngineName = EngineName,
Price = Price,
EngineComponents = EngineComponents
};
}
}

View File

@ -0,0 +1,101 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantListImplement.Models;
namespace MotorPlantListImplement.Implements
{
public class EngineStorage : IEngineStorage
{
private readonly DataListSingleton _source;
public EngineStorage()
{
_source = DataListSingleton.GetInstance();
}
public EngineViewModel? Delete(EngineBindingModel model)
{
for (int i = 0; i < _source.Engines.Count; ++i)
{
if (_source.Engines[i].Id == model.Id)
{
var element = _source.Engines[i];
_source.Engines.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public EngineViewModel? GetElement(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName) && !model.Id.HasValue)
{
return null;
}
foreach (var Engine in _source.Engines)
{
if ((!string.IsNullOrEmpty(model.EngineName) && Engine.EngineName == model.EngineName) ||
(model.Id.HasValue && Engine.Id == model.Id))
{
return Engine.GetViewModel;
}
}
return null;
}
public List<EngineViewModel> GetFilteredList(EngineSearchModel model)
{
var result = new List<EngineViewModel>();
if (string.IsNullOrEmpty(model.EngineName))
{
return result;
}
foreach (var Engine in _source.Engines)
{
if (Engine.EngineName.Contains(model.EngineName))
{
result.Add(Engine.GetViewModel);
}
}
return result;
}
public List<EngineViewModel> GetFullList()
{
var result = new List<EngineViewModel>();
foreach (var Engine in _source.Engines)
{
result.Add(Engine.GetViewModel);
}
return result;
}
public EngineViewModel? Insert(EngineBindingModel model)
{
model.Id = 1;
foreach (var Engine in _source.Engines)
{
if (model.Id <= Engine.Id)
{
model.Id = Engine.Id + 1;
}
}
var newEngine = Engine.Create(model);
if (newEngine == null)
{
return null;
}
_source.Engines.Add(newEngine);
return newEngine.GetViewModel;
}
public EngineViewModel? Update(EngineBindingModel model)
{
foreach (var Engine in _source.Engines)
{
if (Engine.Id == model.Id)
{
Engine.Update(model);
return Engine.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantContracts\MotorPlantContracts.csproj" />
<ProjectReference Include="..\MotorPlantDataModels\MotorPlantDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,58 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models;
namespace MotorPlantListImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int EngineId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; }
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
EngineId = model.EngineId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
EngineId = model.EngineId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
EngineId = EngineId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
};
}
}

View File

@ -0,0 +1,112 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantListImplement.Models;
namespace MotorPlantListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AttachEngineName(order.GetViewModel));
}
return result;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AttachEngineName(order.GetViewModel));
}
}
return result;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return AttachEngineName(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
{
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return AttachEngineName(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return AttachEngineName(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return AttachEngineName(element.GetViewModel);
}
}
return null;
}
private OrderViewModel AttachEngineName(OrderViewModel model)
{
foreach (var Engine in _source.Engines)
{
if (Engine.Id == model.EngineId)
{
model.EngineName = Engine.EngineName;
return model;
}
}
return model;
}
}
}

View File

@ -1,39 +0,0 @@
namespace MotorPlantView
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace MotorPlantView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,117 @@
namespace MotorPlantView.Forms
{
partial class FormComponent
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonCancel = new Button();
buttonSave = new Button();
textBoxCost = new TextBox();
label2 = new Label();
label1 = new Label();
textBoxName = new TextBox();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(284, 89);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(86, 26);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(190, 89);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(86, 26);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// textBoxCost
//
textBoxCost.Location = new Point(103, 49);
textBoxCost.Name = "textBoxCost";
textBoxCost.Size = new Size(163, 23);
textBoxCost.TabIndex = 5;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(21, 52);
label2.Name = "label2";
label2.Size = new Size(38, 15);
label2.TabIndex = 3;
label2.Text = "Цена:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(21, 22);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.TabIndex = 2;
label1.Text = "Название:";
//
// textBoxName
//
textBoxName.Location = new Point(103, 20);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(267, 23);
textBoxName.TabIndex = 4;
//
// FormComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(404, 130);
Controls.Add(textBoxCost);
Controls.Add(textBoxName);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormComponent";
Text = "Компонент";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxCost;
private Label label2;
private Label label1;
private TextBox textBoxName;
}
}

View File

@ -0,0 +1,85 @@
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.BindingModels;
using Microsoft.Extensions.Logging;
namespace MotorPlantView.Forms
{
public partial class FormComponent : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormComponent(ILogger<FormComponent> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponent_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ComponentName;
textBoxCost.Text = view.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Ñîõðàíåíèå êîìïîíåíòà");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
MessageBox.Show("Ñîõðàíåíèå ïðîøëî óñïåøíî", "Ñîîáùåíèå", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ñîõðàíåíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,121 @@
namespace MotorPlantView.Forms
{
partial class FormComponents
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonAdd = new Button();
buttonUpd = new Button();
buttonDel = new Button();
buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(-1, -2);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 24;
dataGridView.Size = new Size(499, 568);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(525, 48);
buttonAdd.Margin = new Padding(3, 4, 3, 4);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(125, 35);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(525, 98);
buttonUpd.Margin = new Padding(3, 4, 3, 4);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(125, 35);
buttonUpd.TabIndex = 2;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonDel
//
buttonDel.Location = new Point(525, 150);
buttonDel.Margin = new Padding(3, 4, 3, 4);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(125, 35);
buttonDel.TabIndex = 3;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonRef
//
buttonRef.Location = new Point(525, 201);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(125, 35);
buttonRef.TabIndex = 4;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(676, 562);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Margin = new Padding(3, 4, 3, 4);
Name = "FormComponents";
Text = "Список компонентов";
Load += FormComponents_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDel;
private Button buttonRef;
}
}

View File

@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
namespace MotorPlantView.Forms
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
public FormComponents(ILogger<FormComponents> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponents_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ComponentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,144 @@
namespace MotorPlantView.Forms
{
partial class FormCreateOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
label1 = new Label();
label2 = new Label();
label3 = new Label();
textBoxCount = new TextBox();
comboBoxEngine = new ComboBox();
textBoxSum = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(19, 12);
label1.Name = "label1";
label1.Size = new Size(56, 15);
label1.TabIndex = 0;
label1.Text = "Изделие:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(19, 44);
label2.Name = "label2";
label2.Size = new Size(75, 15);
label2.TabIndex = 1;
label2.Text = "Количество:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(19, 70);
label3.Name = "label3";
label3.Size = new Size(48, 15);
label3.TabIndex = 2;
label3.Text = "Сумма:";
//
// textBoxCount
//
textBoxCount.Location = new Point(103, 41);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(246, 23);
textBoxCount.TabIndex = 3;
textBoxCount.TextChanged += textBoxCount_TextChanged;
//
// comboBoxEngine
//
comboBoxEngine.FormattingEnabled = true;
comboBoxEngine.Location = new Point(103, 10);
comboBoxEngine.Name = "comboBoxEngine";
comboBoxEngine.Size = new Size(246, 23);
comboBoxEngine.TabIndex = 4;
comboBoxEngine.SelectedIndexChanged += ComboBoxEngine_SelectedIndexChanged;
//
// textBoxSum
//
textBoxSum.Location = new Point(103, 70);
textBoxSum.Name = "textBoxSum";
textBoxSum.ReadOnly = true;
textBoxSum.Size = new Size(246, 23);
textBoxSum.TabIndex = 5;
//
// buttonSave
//
buttonSave.Location = new Point(150, 101);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 26);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(249, 101);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 26);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(374, 136);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSum);
Controls.Add(comboBoxEngine);
Controls.Add(textBoxCount);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormCreateOrder";
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private TextBox textBoxCount;
private ComboBox comboBoxEngine;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,114 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.BusinessLogicsContracts;
namespace MotorPlantView.Forms
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IEngineLogic _logicP;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IEngineLogic logicP, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
try
{
var list = _logicP.ReadList(null);
if (list != null)
{
comboBoxEngine.DisplayMember = "EngineName";
comboBoxEngine.ValueMember = "Id";
comboBoxEngine.DataSource = list;
comboBoxEngine.SelectedItem = null;
_logger.LogInformation("Загрузка изделий для заказа");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
}
}
private void CalcSum()
{
if (comboBoxEngine.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxEngine.SelectedValue);
var Engine = _logicP.ReadElement(new EngineSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (Engine?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void textBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void ComboBoxEngine_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxEngine.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,177 @@
namespace MotorPlantView.Forms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
toolStrip1 = new ToolStrip();
toolStripDropDownButton1 = new ToolStripDropDownButton();
компонентыToolStripMenuItem = new ToolStripMenuItem();
ДвигателиToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
dataGridView = new DataGridView();
toolStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// toolStrip1
//
toolStrip1.ImageScalingSize = new Size(20, 20);
toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 });
toolStrip1.Location = new Point(0, 0);
toolStrip1.Name = "toolStrip1";
toolStrip1.Size = new Size(969, 25);
toolStrip1.TabIndex = 0;
toolStrip1.Text = "toolStrip1";
//
// toolStripDropDownButton1
//
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ДвигателиToolStripMenuItem });
toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image");
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(88, 22);
toolStripDropDownButton1.Text = "Справочник";
//
// компонентыToolStripMenuItem
//
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(174, 22);
компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click;
//
// ДвигателиToolStripMenuItem
//
ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem";
ДвигателиToolStripMenuItem.Size = new Size(174, 22);
ДвигателиToolStripMenuItem.Text = "Двигатели Внутреннего Сгорания";
ДвигателиToolStripMenuItem.Click += консервыToolStripMenuItem_Click;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(800, 56);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(141, 24);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += buttonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(800, 100);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(141, 24);
buttonTakeOrderInWork.TabIndex = 2;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(800, 142);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(141, 24);
buttonOrderReady.TabIndex = 3;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += buttonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(800, 181);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(141, 24);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += buttonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(800, 222);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(141, 24);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 26);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 24;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(763, 435);
dataGridView.TabIndex = 6;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(969, 461);
Controls.Add(dataGridView);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(toolStrip1);
Name = "FormMain";
Text = "Моторный завод";
Load += FormMain_Load;
toolStrip1.ResumeLayout(false);
toolStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private ToolStrip toolStrip1;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private DataGridView dataGridView;
private ToolStripDropDownButton toolStripDropDownButton1;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem ДвигателиToolStripMenuItem;
}
}

View File

@ -0,0 +1,146 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
namespace MotorPlantView.Forms
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["EngineId"].Visible = false;
dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
}
}
private void компонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void консервыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngines));
if (service is FormEngines form)
{
form.ShowDialog();
}
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -8,4 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj" />
<ProjectReference Include="..\MotorPlantContracts\MotorPlantContracts.csproj" />
<ProjectReference Include="..\MotorPlantListImplement\MotorPlantListImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -1,7 +1,18 @@
using MotorPlant.Forms;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantBusinessLogic.BusinessLogic;
using MotorPlantContracts.StoragesContracts;
using MotorPlantListImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace MotorPlantView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +22,32 @@ namespace MotorPlantView
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IEngineStorage, EngineStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IEngineLogic, EngineLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormEngine>();
services.AddTransient<FormEngineComponent>();
services.AddTransient<FormEngines>();
}
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="${basedir}/log-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>