Compare commits

..

No commits in common. "Lab5" and "main" have entirely different histories.
Lab5 ... main

113 changed files with 53 additions and 8142 deletions

View File

@ -3,19 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.6.33717.318
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantView", "MotorPlantView\MotorPlantView.csproj", "{1DB20ED5-3ACF-48ED-BF42-EB6441C629A1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantBusinessLogic", "MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{2B9E81A3-D3D1-4841-85F3-B3E297C3C5BD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantContracts", "MotorPlantContracts\MotorPlantContracts.csproj", "{229D0908-68AF-444D-8806-D7FE493A31AD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantDataModels", "MotorPlantDataModels\MotorPlantDataModels.csproj", "{9C84451B-E004-48E0-8AC4-6ACD203F7265}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantListImplement", "MotorPlantListImplement\MotorPlantListImplement.csproj", "{1DCC8C64-6BF5-4B3F-8B61-C4017E20922C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantFileImplement", "MotorPlantFileImplement\MotorPlantFileImplement.csproj", "{3A225D5B-D720-49CA-83B6-096A0B24A073}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantDatabaseImplement", "MotorPlantDatabaseImplement\MotorPlantDatabaseImplement.csproj", "{6BEADB18-FCD6-4C9A-B1C7-32D4420E7A2D}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantView", "MotorPlantView\MotorPlantView.csproj", "{1DB20ED5-3ACF-48ED-BF42-EB6441C629A1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -27,30 +15,6 @@ Global
{1DB20ED5-3ACF-48ED-BF42-EB6441C629A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DB20ED5-3ACF-48ED-BF42-EB6441C629A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DB20ED5-3ACF-48ED-BF42-EB6441C629A1}.Release|Any CPU.Build.0 = Release|Any CPU
{2B9E81A3-D3D1-4841-85F3-B3E297C3C5BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B9E81A3-D3D1-4841-85F3-B3E297C3C5BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B9E81A3-D3D1-4841-85F3-B3E297C3C5BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B9E81A3-D3D1-4841-85F3-B3E297C3C5BD}.Release|Any CPU.Build.0 = Release|Any CPU
{229D0908-68AF-444D-8806-D7FE493A31AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{229D0908-68AF-444D-8806-D7FE493A31AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{229D0908-68AF-444D-8806-D7FE493A31AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{229D0908-68AF-444D-8806-D7FE493A31AD}.Release|Any CPU.Build.0 = Release|Any CPU
{9C84451B-E004-48E0-8AC4-6ACD203F7265}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9C84451B-E004-48E0-8AC4-6ACD203F7265}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C84451B-E004-48E0-8AC4-6ACD203F7265}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C84451B-E004-48E0-8AC4-6ACD203F7265}.Release|Any CPU.Build.0 = Release|Any CPU
{1DCC8C64-6BF5-4B3F-8B61-C4017E20922C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DCC8C64-6BF5-4B3F-8B61-C4017E20922C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DCC8C64-6BF5-4B3F-8B61-C4017E20922C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DCC8C64-6BF5-4B3F-8B61-C4017E20922C}.Release|Any CPU.Build.0 = Release|Any CPU
{3A225D5B-D720-49CA-83B6-096A0B24A073}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3A225D5B-D720-49CA-83B6-096A0B24A073}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A225D5B-D720-49CA-83B6-096A0B24A073}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A225D5B-D720-49CA-83B6-096A0B24A073}.Release|Any CPU.Build.0 = Release|Any CPU
{6BEADB18-FCD6-4C9A-B1C7-32D4420E7A2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6BEADB18-FCD6-4C9A-B1C7-32D4420E7A2D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6BEADB18-FCD6-4C9A-B1C7-32D4420E7A2D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6BEADB18-FCD6-4C9A-B1C7-32D4420E7A2D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,109 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace MotorPlantBusinessLogic.BusinessLogics
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> logger, IComponentStorage componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{ Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentSearchModel 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);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_componentStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ComponentName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ComponentName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}.Cost:{ Cost}. Id: { Id}", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = model.ComponentName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -1,112 +0,0 @@
using MotorPlantContracts.BindingModels;
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 IEngineStorage _EngineStorage;
public EngineLogic(ILogger<EngineLogic> logger, IEngineStorage EngineStorage)
{
_logger = logger;
_EngineStorage = EngineStorage;
}
public List<EngineViewModel>? ReadList(EngineSearchModel? 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");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public EngineViewModel? ReadElement(EngineSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(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");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(EngineBindingModel model)
{
CheckModel(model);
if (_EngineStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(EngineBindingModel model)
{
CheckModel(model);
if (_EngineStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(EngineBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_EngineStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(EngineBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.EngineName))
{
throw new ArgumentNullException("Нет названия изделия", nameof(model.EngineName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Engine. EngineName:{EngineName}.Price:{Cost}. Id: {Id}", model.EngineName, model.Price, model.Id);
var element = _EngineStorage.GetElement(new EngineSearchModel
{
EngineName = model.EngineName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}
}

View File

@ -1,25 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<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="MigraDocCore.DocumentObjectModel" Version="1.3.63" />
<PackageReference Include="MigraDocCore.Rendering" Version="1.3.63" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantContracts\MotorPlantContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -1,83 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.EngineComponents)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.EngineName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var Engine in pc.Components)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Engine.Item1,
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Engine.Item2.ToString(),
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfo info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters
excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -1,58 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с{info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "4cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Сумма", "Статус" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.EngineName, order.Sum.ToString(), order.Status },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -1,48 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new
WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var component in info.Engines)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
(component.EngineName, new WordTextProperties { Size = "24", Bold = true}),
("\t" + component.Price.ToString(), new WordTextProperties { Size = "24"}),
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Right
}
}

View File

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -1,18 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class ExcelCellParameters
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -1,21 +0,0 @@
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportEngineComponentViewModel> EngineComponents
{
get;
set;
} = new();
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -1,18 +0,0 @@
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<EngineViewModel> Engines { get; set; } = new();
}
}

View File

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -1,337 +0,0 @@

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new
DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style =
BorderStyleValues.Thin
};
bottomBorder.Append(new
DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId =
0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal =
HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new
DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats()
{ Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle =
"TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri =
"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14",
"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle =
"SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri =
"{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15",
"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName,
SpreadsheetDocumentType.Workbook);
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
_shareStringPart =
_spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
?
_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
:
_spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
var sheets =
_spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
_spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters
excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).First();
}
else
{
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value,
excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference =
excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
_shareStringPart.SharedStringTable.AppendChild(new
SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new
CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count(
) - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells,
_worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells,
_worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -1,107 +0,0 @@

using MigraDocCore.DocumentObjectModel;
using MigraDocCore.DocumentObjectModel.Tables;
using MigraDocCore.Rendering;
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment
GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment =
GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment =
GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -1,103 +0,0 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using MotorPlantBusinessLogic.OfficePackage.HelperEnums;
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
}
}

View File

@ -1,132 +0,0 @@
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

@ -1,99 +0,0 @@
using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using MotorPlantBusinessLogic.OfficePackage;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic
{
public class ReportLogic : IReportLogic
{
private readonly IEngineStorage _EngineStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IEngineStorage EngineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_EngineStorage = EngineStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
public List<ReportEngineComponentViewModel> GetEngineComponents()
{
var Engines = _EngineStorage.GetFullList();
var list = new List<ReportEngineComponentViewModel>();
foreach (var Engine in Engines)
{
var record = new ReportEngineComponentViewModel
{
EngineName = Engine.EngineName,
Components = new List<(string Component, int Count)>(),
TotalCount = 0
};
foreach (var component in Engine.EngineComponents)
{
record.Components.Add(new(component.Value.Item1.ComponentName, component.Value.Item2));
record.TotalCount += component.Value.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel
{
DateFrom = model.DateFrom,
DateTo = model.DateTo
})
.Select(x => new ReportOrdersViewModel
{
Id = x.Id,
DateCreate = x.DateCreate,
EngineName = x.EngineName,
Sum = x.Sum,
Status = x.Status.ToString(),
})
.ToList();
}
public void SaveEnginesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список двигателей",
Engines = _EngineStorage.GetFullList()
});
}
public void SaveEngineComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список компонентов",
EngineComponents = GetEngineComponents()
});
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetOrders(model)
});
}
}
}

View File

@ -1,12 +0,0 @@
using MotorPlantDataModels.Models;
namespace MotorPlantContracts.BindingModels
{
public class ComponentBindingModel : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantDataModels.Models;
namespace MotorPlantContracts.BindingModels
{
public class EngineBindingModel : IEngineModel
{
public int Id { get; set; }
public string EngineName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get;
set;
} = new();
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models;
namespace MotorPlantContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int EngineId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{
List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model);
bool Update(ComponentBindingModel model);
bool Delete(ComponentBindingModel model);
}
}

View File

@ -1,15 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.BusinessLogicsContracts
{
public interface IEngineLogic
{
List<EngineViewModel>? ReadList(EngineSearchModel? model);
EngineViewModel? ReadElement(EngineSearchModel model);
bool Create(EngineBindingModel model);
bool Update(EngineBindingModel model);
bool Delete(EngineBindingModel model);
}
}

View File

@ -1,15 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -1,19 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
List<ReportEngineComponentViewModel> GetEngineComponents();
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
void SaveEnginesToWordFile(ReportBindingModel model);
void SaveEngineComponentToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -1,22 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<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>
</Project>

View File

@ -1,9 +0,0 @@
namespace MotorPlantContracts.SearchModels
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace MotorPlantContracts.SearchModels
{
public class EngineSearchModel
{
public int? Id { get; set; }
public string? EngineName { get; set; }
}
}

View File

@ -1,9 +0,0 @@
namespace MotorPlantContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.StoragesContracts
{
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);
ComponentViewModel? Delete(ComponentBindingModel model);
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.StoragesContracts
{
public interface IEngineStorage
{
List<EngineViewModel> GetFullList();
List<EngineViewModel> GetFilteredList(EngineSearchModel model);
EngineViewModel? GetElement(EngineSearchModel model);
EngineViewModel? Insert(EngineBindingModel model);
EngineViewModel? Update(EngineBindingModel model);
EngineViewModel? Delete(EngineBindingModel model);
}
}

View File

@ -1,16 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.StoragesContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -1,15 +0,0 @@
using MotorPlantDataModels.Models;
using System.ComponentModel;
namespace MotorPlantContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -1,19 +0,0 @@
using MotorPlantDataModels.Models;
using System.ComponentModel;
namespace MotorPlantContracts.ViewModels
{
public class EngineViewModel : IEngineModel
{
public int Id { get; set; }
[DisplayName("Название изделия")]
public string EngineName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get;
set;
} = new();
}
}

View File

@ -1,26 +0,0 @@
using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models;
using System.ComponentModel;
namespace MotorPlantContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int EngineId { get; set; }
[DisplayName("Изделие")]
public string EngineName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.ViewModels
{
public class ReportEngineComponentViewModel
{
public string EngineName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Component, int Count)> Components { get; set; } = new();
}
}

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.ViewModels
{
public class ReportOrdersViewModel
{
public int Id { get; set; }
public DateTime DateCreate { get; set; }
public string EngineName { get; set; } = string.Empty;
public double Sum { get; set; }
public string Status { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace MotorPlantDataModels.Models
{
public interface IComponentModel : IId
{
string ComponentName { get; }
double Cost { get; }
}
}

View File

@ -1,10 +0,0 @@
namespace MotorPlantDataModels.Models
{
public interface IEngineModel : IId
{
string EngineName { get; }
double Price { get; }
Dictionary<int, (IComponentModel, int)> EngineComponents { get; }
}
}

View File

@ -1,7 +0,0 @@
namespace MotorPlantDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -1,15 +0,0 @@
using MotorPlantDataModels.Enums;
namespace MotorPlantDataModels.Models
{
public interface IOrderModel : IId
{
int EngineId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<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

@ -1,11 +0,0 @@
namespace MotorPlantDataModels.Enums
{
public enum OrderStatus
{
Неизвестен = -1,
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3
}
}

View File

@ -1,84 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new MotorPlantDataBase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new MotorPlantDataBase();
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new MotorPlantDataBase();
return context.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName ==
model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new MotorPlantDataBase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new MotorPlantDataBase();
var component = context.Components.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new MotorPlantDataBase();
var element = context.Components.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -1,104 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace MotorPlantDatabaseImplement.Implements
{
public class EngineStorage : IEngineStorage
{
public List<EngineViewModel> GetFullList()
{
using var context = new MotorPlantDataBase();
return context.Engines
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<EngineViewModel> GetFilteredList(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName))
{
return new();
}
using var context = new MotorPlantDataBase();
return context.Engines.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.EngineName.Contains(model.EngineName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public EngineViewModel? GetElement(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new MotorPlantDataBase();
return context.Engines
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EngineName) &&
x.EngineName == model.EngineName) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public EngineViewModel? Insert(EngineBindingModel model)
{
using var context = new MotorPlantDataBase();
var newEngine = Engine.Create(context, model);
if (newEngine == null)
{
return null;
}
context.Engines.Add(newEngine);
context.SaveChanges();
return newEngine.GetViewModel;
}
public EngineViewModel? Update(EngineBindingModel model)
{
using var context = new MotorPlantDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var Engine = context.Engines.FirstOrDefault(rec =>
rec.Id == model.Id);
if (Engine == null)
{
return null;
}
Engine.Update(model);
context.SaveChanges();
Engine.UpdateComponents(context, model);
transaction.Commit();
return Engine.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public EngineViewModel? Delete(EngineBindingModel model)
{
using var context = new MotorPlantDataBase();
var element = context.Engines
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Engines.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -1,95 +0,0 @@
using Microsoft.EntityFrameworkCore;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new MotorPlantDataBase();
return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.DateFrom.HasValue || !model.DateTo.HasValue)
{
return new();
}
using var context = new MotorPlantDataBase();
if (model.DateFrom.HasValue)
{
return context.Orders.Include(x => x.Engine).Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => x.GetViewModel).ToList();
}
return context.Orders.Where(x => x.Id == model.Id).Include(x => x.Engine)
.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new MotorPlantDataBase();
return context.Orders.Include(x => x.Engine).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new MotorPlantDataBase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders.Include(x => x.Engine).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new MotorPlantDataBase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return context.Orders.Include(x => x.Engine).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new MotorPlantDataBase();
var element = context.Orders.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public static OrderViewModel AccessEngineStorage(OrderViewModel model)
{
if (model == null)
return null;
using var context = new MotorPlantDataBase();
foreach (var Engine in context.Engines)
{
if (Engine.Id == model.EngineId)
{
model.EngineName = Engine.EngineName;
break;
}
}
return model;
}
}
}

View File

@ -1,169 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MotorPlantDatabaseImplement;
#nullable disable
namespace MotorPlantDatabaseImplement.Migrations
{
[DbContext(typeof(MotorPlantDataBase))]
[Migration("20240512181601_InitMigration")]
partial class InitMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("EngineName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Engines");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("EngineId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("EngineId");
b.ToTable("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("EngineId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("EngineId");
b.ToTable("Orders");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component")
.WithMany("EngineComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany("Components")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Engine");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null)
.WithMany("Orders")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,125 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MotorPlantDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Engines",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EngineName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Engines", x => x.Id);
});
migrationBuilder.CreateTable(
name: "EngineComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EngineId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_EngineComponents", x => x.Id);
table.ForeignKey(
name: "FK_EngineComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_EngineComponents_Engines_EngineId",
column: x => x.EngineId,
principalTable: "Engines",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
EngineId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Engines_EngineId",
column: x => x.EngineId,
principalTable: "Engines",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_EngineComponents_ComponentId",
table: "EngineComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_EngineComponents_EngineId",
table: "EngineComponents",
column: "EngineId");
migrationBuilder.CreateIndex(
name: "IX_Orders_EngineId",
table: "Orders",
column: "EngineId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "EngineComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Engines");
}
}
}

View File

@ -1,166 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MotorPlantDatabaseImplement;
#nullable disable
namespace MotorPlantDatabaseImplement.Migrations
{
[DbContext(typeof(MotorPlantDataBase))]
partial class MotorPlantDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("EngineName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Engines");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("EngineId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("EngineId");
b.ToTable("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("EngineId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("EngineId");
b.ToTable("Orders");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component")
.WithMany("EngineComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany("Components")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Engine");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null)
.WithMany("Orders")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,57 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace MotorPlantDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<EngineComponent> EngineComponents { get; set; } =
new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component Create(ComponentViewModel model)
{
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

@ -1,97 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace MotorPlantDatabaseImplement.Models
{
public class Engine : IEngineModel
{
public int Id { get; set; }
[Required]
public string EngineName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _EngineComponents =
null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get
{
if (_EngineComponents == null)
{
_EngineComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _EngineComponents;
}
}
[ForeignKey("EngineId")]
public virtual List<EngineComponent> Components { get; set; } = new();
[ForeignKey("EngineId")]
public virtual List<Order> Orders { get; set; } = new();
public static Engine Create(MotorPlantDataBase context,
EngineBindingModel model)
{
return new Engine()
{
Id = model.Id,
EngineName = model.EngineName,
Price = model.Price,
Components = model.EngineComponents.Select(x => new
EngineComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(EngineBindingModel model)
{
EngineName = model.EngineName;
Price = model.Price;
}
public EngineViewModel GetViewModel => new()
{
Id = Id,
EngineName = EngineName,
Price = Price,
EngineComponents = EngineComponents
};
public void UpdateComponents(MotorPlantDataBase context,
EngineBindingModel model)
{
var EngineComponents = context.EngineComponents.Where(rec =>
rec.EngineId == model.Id).ToList();
if (EngineComponents != null && EngineComponents.Count > 0)
{
context.EngineComponents.RemoveRange(EngineComponents.Where(rec
=> !model.EngineComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in EngineComponents)
{
updateComponent.Count =
model.EngineComponents[updateComponent.ComponentId].Item2;
model.EngineComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var Engine = context.Engines.First(x => x.Id == Id);
foreach (var pc in model.EngineComponents)
{
context.EngineComponents.Add(new EngineComponent
{
Engine = Engine,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_EngineComponents = null;
}
}
}

View File

@ -1,17 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace MotorPlantDatabaseImplement.Models
{
public class EngineComponent
{
public int Id { get; set; }
[Required]
public int EngineId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Engine Engine { get; set; } = new();
}
}

View File

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

View File

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement
{
public class MotorPlantDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=RavilPC\SQLEXPRESS;Initial Catalog=MotorPlantDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Engine> Engines { set; get; }
public virtual DbSet<EngineComponent> EngineComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}
}

View File

@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MotorPlantContracts\MotorPlantContracts.csproj" />
<ProjectReference Include="..\MotorPlantDataModels\MotorPlantDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -1,59 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantDatabaseImplement.Models
{
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 static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
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
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -1,72 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components.Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return source.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
return source.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Components.Remove(element);
source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -1,49 +0,0 @@
using MotorPlantDatabaseImplement.Models;
using System.Xml.Linq;
namespace MotorPlantDatabaseImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string EngineFileName = "Engine.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Engine> Engines { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveEngines() => SaveData(Engines, EngineFileName, "Engines", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -1,89 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantDatabaseImplement.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, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _EngineComponents = null;
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get
{
if (_EngineComponents == null)
{
var source = DataFileSingleton.GetInstance();
_EngineComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _EngineComponents;
}
}
public static Engine? Create(EngineBindingModel model)
{
if (model == null)
{
return null;
}
return new Engine()
{
Id = model.Id,
EngineName = model.EngineName,
Price = model.Price,
Components = model.EngineComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Engine? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Engine()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
EngineName = element.Element("EngineName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("EngineComponents")!.Elements("EngineComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(EngineBindingModel model)
{
if (model == null)
{
return;
}
EngineName = model.EngineName;
Price = model.Price;
Components = model.EngineComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_EngineComponents = null;
}
public EngineViewModel GetViewModel => new()
{
Id = Id,
EngineName = EngineName,
Price = Price,
EngineComponents = EngineComponents
};
public XElement GetXElement => new("Engine",
new XAttribute("Id", Id),
new XElement("EngineName", EngineName),
new XElement("Price", Price.ToString()),
new XElement("EngineComponents", Components.Select(x => new XElement("EngineComponent", new XElement("Key", x.Key), new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -1,71 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class EngineStorage : IEngineStorage
{
private readonly DataFileSingleton source;
public EngineStorage()
{
source = DataFileSingleton.GetInstance();
}
public EngineViewModel? GetElement(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName) && !model.Id.HasValue)
{
return null;
}
return source.Engines.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EngineName) && x.EngineName == model.EngineName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<EngineViewModel> GetFilteredList(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName))
{
return new();
}
return source.Engines.Where(x => x.EngineName.Contains(model.EngineName)).Select(x => x.GetViewModel).ToList();
}
public List<EngineViewModel> GetFullList()
{
return source.Engines.Select(x => x.GetViewModel).ToList();
}
public EngineViewModel? Insert(EngineBindingModel model)
{
model.Id = source.Engines.Count > 0 ? source.Engines.Max(x => x.Id) + 1 : 1;
var newDoc = Engine.Create(model);
if (newDoc == null)
{
return null;
}
source.Engines.Add(newDoc);
source.SaveEngines();
return newDoc.GetViewModel;
}
public EngineViewModel? Update(EngineBindingModel model)
{
var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveEngines();
return document.GetViewModel;
}
public EngineViewModel? Delete(EngineBindingModel model)
{
var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveEngines();
return document.GetViewModel;
}
}
}

View File

@ -1,14 +0,0 @@
<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

@ -1,88 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int EngineId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { 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 static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
EngineId = Convert.ToInt32(element.Element("EngineId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status))
{
return null;
}
order.Status = status;
return order;
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
EngineId = EngineId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("EngineId", EngineId),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
}

View File

@ -1,79 +0,0 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id));
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var engine = source.Engines.FirstOrDefault(x => x.Id == order.EngineId);
viewModel.EngineName = engine?.EngineName;
return viewModel;
}
}
}

View File

@ -1,41 +0,0 @@
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

@ -1,100 +0,0 @@
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

@ -1,26 +0,0 @@
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

@ -1,50 +0,0 @@
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

@ -1,101 +0,0 @@
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

@ -1,14 +0,0 @@
<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

@ -1,54 +0,0 @@
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;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
EngineId = EngineId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
};
}
}

View File

@ -1,112 +0,0 @@
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

@ -0,0 +1,39 @@
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

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

View File

@ -1,117 +0,0 @@
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

@ -1,85 +0,0 @@
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

@ -1,120 +0,0 @@
<?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

@ -1,121 +0,0 @@
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

@ -1,104 +0,0 @@
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

@ -1,144 +0,0 @@
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

@ -1,114 +0,0 @@
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

@ -1,120 +0,0 @@
<?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

@ -1,235 +0,0 @@
namespace MotorPlantView.Forms
{
partial class FormEngine
{
/// <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();
buttonAdd = new Button();
buttonUpd = new Button();
buttonDel = new Button();
buttonRef = new Button();
dataGridView = new DataGridView();
Number = new DataGridViewTextBoxColumn();
Component = new DataGridViewTextBoxColumn();
Count = new DataGridViewTextBoxColumn();
textBoxName = new TextBox();
textBoxPrice = new TextBox();
groupBox1 = new GroupBox();
buttonSave = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
groupBox1.SuspendLayout();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(16, 15);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.TabIndex = 0;
label1.Text = "Название:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(16, 41);
label2.Name = "label2";
label2.Size = new Size(70, 15);
label2.TabIndex = 1;
label2.Text = "Стоимость:";
//
// buttonAdd
//
buttonAdd.Location = new Point(574, 44);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(97, 28);
buttonAdd.TabIndex = 0;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(574, 90);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(97, 28);
buttonUpd.TabIndex = 1;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonDel
//
buttonDel.Location = new Point(574, 134);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(97, 28);
buttonDel.TabIndex = 2;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonRef
//
buttonRef.Location = new Point(574, 173);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(97, 28);
buttonRef.TabIndex = 3;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { Number, Component, Count });
dataGridView.Location = new Point(0, 20);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 24;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.ShowEditingIcon = false;
dataGridView.Size = new Size(549, 332);
dataGridView.TabIndex = 4;
//
// Number
//
Number.HeaderText = "Номер";
Number.MinimumWidth = 6;
Number.Name = "Number";
Number.ReadOnly = true;
Number.Width = 60;
//
// Component
//
Component.HeaderText = "Компонент";
Component.MinimumWidth = 6;
Component.Name = "Component";
Component.ReadOnly = true;
Component.Width = 125;
//
// Count
//
Count.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
Count.HeaderText = "Количество";
Count.MinimumWidth = 6;
Count.Name = "Count";
Count.ReadOnly = true;
//
// textBoxName
//
textBoxName.Location = new Point(94, 14);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(246, 23);
textBoxName.TabIndex = 3;
//
// textBoxPrice
//
textBoxPrice.Location = new Point(94, 39);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.ReadOnly = true;
textBoxPrice.Size = new Size(85, 23);
textBoxPrice.TabIndex = 4;
textBoxPrice.TabStop = false;
//
// groupBox1
//
groupBox1.Controls.Add(buttonRef);
groupBox1.Controls.Add(buttonDel);
groupBox1.Controls.Add(dataGridView);
groupBox1.Controls.Add(buttonUpd);
groupBox1.Controls.Add(buttonAdd);
groupBox1.Location = new Point(14, 71);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(689, 367);
groupBox1.TabIndex = 5;
groupBox1.TabStop = false;
groupBox1.Text = "Компоненты";
//
// buttonSave
//
buttonSave.Location = new Point(397, 454);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(114, 28);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(533, 454);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(114, 28);
buttonCancel.TabIndex = 0;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormEngine
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(711, 497);
Controls.Add(groupBox1);
Controls.Add(textBoxPrice);
Controls.Add(textBoxName);
Controls.Add(label2);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label1);
Name = "FormEngine";
Text = "Двигатель";
Load += FormEngine_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
groupBox1.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBox1;
private DataGridViewTextBoxColumn Number;
private DataGridViewTextBoxColumn Component;
private DataGridViewTextBoxColumn Count;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -1,196 +0,0 @@
using Microsoft.Extensions.Logging;
using MotorPlantDataModels.Models;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.BindingModels;
namespace MotorPlantView.Forms
{
public partial class FormEngine : Form
{
private readonly ILogger _logger;
private readonly IEngineLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _productComponents;
public int Id { set { _id = value; } }
public FormEngine(ILogger<FormEngine> logger, IEngineLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_productComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormEngine_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new EngineSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.EngineName;
textBoxPrice.Text = view.Price.ToString();
_productComponents = view.EngineComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_productComponents != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _productComponents)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент изделия");
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngineComponent));
if (service is FormEngineComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
if (_productComponents.ContainsKey(form.Id))
{
_productComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_productComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngineComponent));
if (service is FormEngineComponent form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _productComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
_productComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: { ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_productComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_productComponents == null || _productComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new EngineBindingModel
{
Id = _id ?? 0,
EngineName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
EngineComponents = _productComponents
};
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();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _productComponents)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -1,120 +0,0 @@
<?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

@ -1,118 +0,0 @@
namespace MotorPlantView.Forms
{
partial class FormEngineComponent
{
/// <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()
{
buttonSave = new Button();
buttonCancel = new Button();
label1 = new Label();
label2 = new Label();
comboBoxComponent = new ComboBox();
textBoxCount = new TextBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Location = new Point(174, 75);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(86, 27);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(270, 75);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(86, 27);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 14);
label1.Name = "label1";
label1.Size = new Size(72, 15);
label1.TabIndex = 2;
label1.Text = "Компонент:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(12, 44);
label2.Name = "label2";
label2.Size = new Size(75, 15);
label2.TabIndex = 3;
label2.Text = "Количество:";
//
// comboBoxComponent
//
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(106, 9);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(250, 23);
comboBoxComponent.TabIndex = 4;
//
// textBoxCount
//
textBoxCount.Location = new Point(106, 44);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(250, 23);
textBoxCount.TabIndex = 5;
//
// FormEngineComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(373, 112);
Controls.Add(textBoxCount);
Controls.Add(comboBoxComponent);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormEngineComponent";
Text = "Компонент двигателя";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private Label label2;
private ComboBox comboBoxComponent;
private TextBox textBoxCount;
}
}

View File

@ -1,80 +0,0 @@
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
namespace MotorPlantView.Forms
{
public partial class FormEngineComponent : Form
{
private readonly List<ComponentViewModel>? _list;
public int Id
{
get
{
return Convert.ToInt32(comboBoxComponent.SelectedValue);
}
set
{
comboBoxComponent.SelectedValue = value;
}
}
public IComponentModel? ComponentModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set { textBoxCount.Text = value.ToString(); }
}
public FormEngineComponent(IComponentLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxComponent.DisplayMember = "ComponentName";
comboBoxComponent.ValueMember = "Id";
comboBoxComponent.DataSource = _list;
comboBoxComponent.SelectedItem = null;
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComponent.SelectedValue == null)
{
MessageBox.Show("Выберите компонент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -1,120 +0,0 @@
<?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

@ -1,116 +0,0 @@
namespace MotorPlantView.Forms
{
partial class FormEngines
{
/// <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()
{
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRef
//
buttonRef.Location = new Point(648, 135);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(112, 26);
buttonRef.TabIndex = 9;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(648, 97);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(112, 26);
buttonDel.TabIndex = 8;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(648, 58);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(112, 26);
buttonUpd.TabIndex = 7;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(648, 20);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(112, 26);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(-1, 0);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 24;
dataGridView.Size = new Size(620, 426);
dataGridView.TabIndex = 5;
//
// FormEngines
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(783, 428);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormEngines";
Text = "Список двигателей";
Load += FormEngines_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -1,105 +0,0 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
namespace MotorPlantView.Forms
{
public partial class FormEngines : Form
{
private readonly ILogger _logger;
private readonly IEngineLogic _logic;
public FormEngines(ILogger<FormEngines> logger, IEngineLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormEngines_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["EngineComponents"].Visible = false;
dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngine));
if (service is FormEngine 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(FormEngine));
if (service is FormEngine 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 EngineBindingModel
{
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

@ -1,120 +0,0 @@
<?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

@ -1,213 +0,0 @@
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()
{
toolStrip1 = new ToolStrip();
toolStripDropDownButton1 = new ToolStripDropDownButton();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
ДвигателиToolStripMenuItem = new ToolStripMenuItem();
toolStripDropDownButton2 = new ToolStripDropDownButton();
списокКомпонентовToolStripMenuItem = new ToolStripMenuItem();
компонентыПоДвигателям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, toolStripDropDownButton2 });
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.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(88, 22);
toolStripDropDownButton1.Text = "Справочник";
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(145, 22);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// ДвигателиToolStripMenuItem
//
ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem";
ДвигателиToolStripMenuItem.Size = new Size(145, 22);
ДвигателиToolStripMenuItem.Text = "Двигатели";
ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
//
// toolStripDropDownButton2
//
toolStripDropDownButton2.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton2.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem });
toolStripDropDownButton2.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton2.Name = "toolStripDropDownButton2";
toolStripDropDownButton2.Size = new Size(59, 22);
toolStripDropDownButton2.Text = "отчеты";
//
// списокКомпонентовToolStripMenuItem
//
списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem";
списокКомпонентовToolStripMenuItem.Size = new Size(228, 22);
списокКомпонентовToolStripMenuItem.Text = "Список компонентов";
списокКомпонентовToolStripMenuItem.Click += списокКомпонентовToolStripMenuItem_Click_1;
//
// компонентыПоДвигателямToolStripMenuItem
//
компонентыПоДвигателямToolStripMenuItem.Name = омпонентыПоДвигателямToolStripMenuItem";
компонентыПоДвигателямToolStripMenuItem.Size = new Size(228, 22);
компонентыПоДвигателямToolStripMenuItem.Text = "Компоненты по двигателям";
компонентыПоДвигателямToolStripMenuItem.Click += компонентыПоДвигателямToolStripMenuItem_Click_1;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(228, 22);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click_1;
//
// 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;
private ToolStripDropDownButton toolStripDropDownButton2;
private ToolStripMenuItem списокКомпонентовToolStripMenuItem;
private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
}
}

View File

@ -1,211 +0,0 @@
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;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
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();
}
private void списокКомпонентовToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveEnginesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void компонентыПоДвигателямToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportEngineComponents));
if (service is FormReportEngineComponents form)
{
form.ShowDialog();
}
}
private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void списокКомпонентовToolStripMenuItem_Click_1(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveEnginesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void компонентыПоДвигателямToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportEngineComponents));
if (service is FormReportEngineComponents form)
{
form.ShowDialog();
}
}
private void списокЗаказовToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More