Compare commits

...

4 Commits

Author SHA1 Message Date
Marselchi
7ec7bd5c6b Фулл 4 2024-04-05 10:20:47 +04:00
Marselchi
bb3f6a30f1 Вроде третья фулл 2024-03-24 13:58:43 +04:00
Marselchi
22eda2809c Фулл вторая лаба получается 2024-03-10 21:25:34 +04:00
Marselchi
f94e335f3d Ультракоммит всей лабы 2024-02-25 20:02:29 +04:00
121 changed files with 8054 additions and 82 deletions

View File

@ -3,7 +3,19 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.8.34408.163 VisualStudioVersion = 17.8.34408.163
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shipyard", "Shipyard\Shipyard.csproj", "{0CDFD76A-8254-473F-8285-FF7A15F16F31}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardDataModels", "ShipyardDataModels\ShipyardDataModels.csproj", "{260F4D58-9D03-457C-B522-CE27360CDD31}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardContracts", "ShipyardContracts\ShipyardContracts.csproj", "{C2E0380E-51D2-4B27-A385-459E91DC75CD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardBusinessLogic", "ShipyardBusinessLogic\ShipyardBusinessLogic.csproj", "{652CC6F7-1097-46F4-B516-A010D6D747EA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardListImplement", "ShipyardListImplement\ShipyardListImplement.csproj", "{0F6E8B4C-CD20-4371-8316-E13FDA31AE57}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardView", "ShipyardView\ShipyardView.csproj", "{BE881F13-7D8F-43B7-AA58-18BBE668FA79}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShipyardFileImplement", "ShipyardFileImplement\ShipyardFileImplement.csproj", "{804C4D1B-2098-4653-8CBA-F5931605A28D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShipyardDataBaseImplement", "ShipyardDataBaseImplement\ShipyardDataBaseImplement.csproj", "{1AAB9FB9-BD51-4EF1-BC80-E17FA9B6851E}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,10 +23,34 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0CDFD76A-8254-473F-8285-FF7A15F16F31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {260F4D58-9D03-457C-B522-CE27360CDD31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0CDFD76A-8254-473F-8285-FF7A15F16F31}.Debug|Any CPU.Build.0 = Debug|Any CPU {260F4D58-9D03-457C-B522-CE27360CDD31}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0CDFD76A-8254-473F-8285-FF7A15F16F31}.Release|Any CPU.ActiveCfg = Release|Any CPU {260F4D58-9D03-457C-B522-CE27360CDD31}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0CDFD76A-8254-473F-8285-FF7A15F16F31}.Release|Any CPU.Build.0 = Release|Any CPU {260F4D58-9D03-457C-B522-CE27360CDD31}.Release|Any CPU.Build.0 = Release|Any CPU
{C2E0380E-51D2-4B27-A385-459E91DC75CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2E0380E-51D2-4B27-A385-459E91DC75CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2E0380E-51D2-4B27-A385-459E91DC75CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2E0380E-51D2-4B27-A385-459E91DC75CD}.Release|Any CPU.Build.0 = Release|Any CPU
{652CC6F7-1097-46F4-B516-A010D6D747EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{652CC6F7-1097-46F4-B516-A010D6D747EA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{652CC6F7-1097-46F4-B516-A010D6D747EA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{652CC6F7-1097-46F4-B516-A010D6D747EA}.Release|Any CPU.Build.0 = Release|Any CPU
{0F6E8B4C-CD20-4371-8316-E13FDA31AE57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0F6E8B4C-CD20-4371-8316-E13FDA31AE57}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0F6E8B4C-CD20-4371-8316-E13FDA31AE57}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0F6E8B4C-CD20-4371-8316-E13FDA31AE57}.Release|Any CPU.Build.0 = Release|Any CPU
{BE881F13-7D8F-43B7-AA58-18BBE668FA79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BE881F13-7D8F-43B7-AA58-18BBE668FA79}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BE881F13-7D8F-43B7-AA58-18BBE668FA79}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BE881F13-7D8F-43B7-AA58-18BBE668FA79}.Release|Any CPU.Build.0 = Release|Any CPU
{804C4D1B-2098-4653-8CBA-F5931605A28D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{804C4D1B-2098-4653-8CBA-F5931605A28D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{804C4D1B-2098-4653-8CBA-F5931605A28D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{804C4D1B-2098-4653-8CBA-F5931605A28D}.Release|Any CPU.Build.0 = Release|Any CPU
{1AAB9FB9-BD51-4EF1-BC80-E17FA9B6851E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1AAB9FB9-BD51-4EF1-BC80-E17FA9B6851E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1AAB9FB9-BD51-4EF1-BC80-E17FA9B6851E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1AAB9FB9-BD51-4EF1-BC80-E17FA9B6851E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

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

View File

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

View File

@ -1,17 +0,0 @@
namespace Shipyard
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}

View File

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,108 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace ShipyardBusinessLogic.BusinessLogics
{
public class DetailLogic : IDetailLogic
{
private readonly ILogger _logger;
private readonly IDetailStorage _detailStorage;
public DetailLogic(ILogger<DetailLogic> logger, IDetailStorage detailStorage)
{
_logger = logger;
_detailStorage = detailStorage;
}
public List<DetailViewModel>? ReadList(DetailSearchModel? model)
{
_logger.LogInformation("ReadList. DetailName:{DetailName}. Id:{Id}", model?.DetailName, model?.Id);
var list = model == null ? _detailStorage.GetFullList() : _detailStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public DetailViewModel? ReadElement(DetailSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. DetailName:{DetailName}. Id:{ Id}", model.DetailName, model.Id);
var element = _detailStorage.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(DetailBindingModel model)
{
CheckModel(model);
if (_detailStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(DetailBindingModel model)
{
CheckModel(model);
if (_detailStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(DetailBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_detailStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(DetailBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.DetailName))
{
throw new ArgumentNullException("Нет названия детали",
nameof(model.DetailName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена детали должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Detail. DetailName:{DetailName}. Cost:{ Cost}. Id: { Id}", model.DetailName, model.Cost, model.Id);
var element = _detailStorage.GetElement(new DetailSearchModel
{
DetailName = model.DetailName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Деталь с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,110 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Enums;
namespace ShipyardBusinessLogic.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. Id:{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.Неизвестен)
{
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
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.ShipId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у корабля", nameof(model.ShipId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество кораблей в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. ShipId: { ShipId}", model.Id, model.Sum, model.ShipId);
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel.Status + 1 != newStatus)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect.");
return false;
}
model.Status = newStatus;
if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now;
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
public bool FinishOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Готов);
}
}
}

View File

@ -0,0 +1,109 @@
using ShipyardBusinessLogic.OfficePackage.HelperModels;
using ShipyardBusinessLogic.OfficePackage;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
namespace ShipyardBusinessLogic.BusinessLogics
{
public class ReportLogic : IReportLogic
{
private readonly IDetailStorage _detailStorage;
private readonly IShipStorage _shipStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IShipStorage shipStorage, IDetailStorage detailStorage, IOrderStorage orderStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_shipStorage = shipStorage;
_detailStorage = detailStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
public List<ReportShipDetailViewModel> GetShipDetail()
{
var ships = _shipStorage.GetFullList();
var list = new List<ReportShipDetailViewModel>();
foreach (var ship in ships)
{
var record = new ReportShipDetailViewModel
{
ShipName = ship.ShipName,
Details = new List<(string, int)>(),
TotalCount = 0
};
foreach (var shipDetail in ship.ShipDetails)
{
record.Details.Add(new(shipDetail.Value.Item1.DetailName, shipDetail.Value.Item2));
record.TotalCount += shipDetail.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,
ShipName = x.ShipName,
OrderStatus = x.Status.ToString(),
Sum = x.Sum
})
.ToList();
}
public void SaveComponentsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список кораблей",
Ships = _shipStorage.GetFullList()
});
}
public void SaveProductComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список деталей",
ShipDetails = GetShipDetail()
});
}
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

@ -0,0 +1,108 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
namespace ShipyardBusinessLogic.BusinessLogics
{
public class ShipLogic : IShipLogic
{
private readonly ILogger _logger;
private readonly IShipStorage _shipStorage;
public ShipLogic(ILogger<ShipLogic> logger, IShipStorage shipStorage)
{
_logger = logger;
_shipStorage = shipStorage;
}
public List<ShipViewModel>? ReadList(ShipSearchModel? model)
{
_logger.LogInformation("ReadList. ShipName:{ShipName}. Id:{Id}", model?.ShipName, model?.Id);
var list = model == null ? _shipStorage.GetFullList() : _shipStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ShipViewModel? ReadElement(ShipSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShipName:{ShipName}. Id:{ Id}", model.ShipName, model.Id);
var element = _shipStorage.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(ShipBindingModel model)
{
CheckModel(model);
if (_shipStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShipBindingModel model)
{
CheckModel(model);
if (_shipStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShipBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shipStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShipBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ShipName))
{
throw new ArgumentNullException("Нет названия коробля",
nameof(model.ShipName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена коробля должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Ship. ShipName:{ShipName}. Price:{Price}. Id: {Id}", model.ShipName, model.Price, model.Id);
var element = _shipStorage.GetElement(new ShipSearchModel
{
ShipName = model.ShipName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Корабль с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,83 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
namespace ShipyardBusinessLogic.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.ShipDetails)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.ShipName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Detail, Count) in pc.Details)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Detail,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
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

@ -0,0 +1,42 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
namespace ShipyardBusinessLogic.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", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "ID", "Дата заказа", "Название корабля", "Статус", "Сумма" },
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.ShipName, order.OrderStatus.ToString(), order.Sum.ToString() },
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

@ -0,0 +1,42 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
namespace ShipyardBusinessLogic.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 ship in info.Ships)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (ship.ShipName + " ", new WordTextProperties {Bold=true, Size = "24", }),
(ship.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

@ -0,0 +1,11 @@
namespace ShipyardBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBorder
}
}

View File

@ -0,0 +1,11 @@
namespace ShipyardBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Right
}
}

View File

@ -0,0 +1,9 @@
namespace ShipyardBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,17 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
namespace ShipyardBusinessLogic.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

@ -0,0 +1,13 @@
using ShipyardContracts.ViewModels;
namespace ShipyardBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportShipDetailViewModel> ShipDetails { get; set; } = new();
}
}

View File

@ -0,0 +1,11 @@
namespace ShipyardBusinessLogic.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

@ -0,0 +1,17 @@
using ShipyardContracts.ViewModels;
namespace ShipyardBusinessLogic.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

@ -0,0 +1,13 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
namespace ShipyardBusinessLogic.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

@ -0,0 +1,13 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
namespace ShipyardBusinessLogic.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

@ -0,0 +1,13 @@
using ShipyardContracts.ViewModels;
namespace ShipyardBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ShipViewModel> Ships { get; set; } = new();
}
}

View File

@ -0,0 +1,9 @@
namespace ShipyardBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
namespace ShipyardBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,292 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ShipyardBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
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);
}
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBorder => 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>();
// Создаем SharedStringTable, если его нет
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

@ -0,0 +1,109 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace ShipyardBusinessLogic.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,
};
}
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

@ -0,0 +1,119 @@
using ShipyardBusinessLogic.OfficePackage.HelperEnums;
using ShipyardBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace ShipyardBusinessLogic.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

@ -0,0 +1,19 @@
<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.Logging" Version="8.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ShipyardContracts\ShipyardContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,11 @@
using ShipyardDataModels.Models;
namespace ShipyardContracts.BindingModels
{
public class DetailBindingModel : IDetailModel
{
public int Id { get; set; }
public string DetailName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using ShipyardDataModels.Enums;
using ShipyardDataModels.Models;
namespace ShipyardContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int ShipId { 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

@ -0,0 +1,11 @@
namespace ShipyardContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using ShipyardDataModels.Models;
namespace ShipyardContracts.BindingModels
{
public class ShipBindingModel : IShipModel
{
public int Id { get; set; }
public string ShipName { get; set; } = String.Empty;
public double Price { get; set; }
public Dictionary<int, (IDetailModel, int)> ShipDetails { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.BusinessLogicsContracts
{
public interface IDetailLogic
{
List<DetailViewModel>? ReadList(DetailSearchModel? model);
DetailViewModel? ReadElement(DetailSearchModel model);
bool Create(DetailBindingModel model);
bool Update(DetailBindingModel model);
bool Delete(DetailBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.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

@ -0,0 +1,18 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
List<ReportShipDetailViewModel> GetShipDetail();
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
void SaveComponentsToWordFile(ReportBindingModel model);
void SaveProductComponentToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.BusinessLogicsContracts
{
public interface IShipLogic
{
List<ShipViewModel>? ReadList(ShipSearchModel? model);
ShipViewModel? ReadElement(ShipSearchModel model);
bool Create(ShipBindingModel model);
bool Update(ShipBindingModel model);
bool Delete(ShipBindingModel model);
}
}

View File

@ -0,0 +1,8 @@
namespace ShipyardContracts.SearchModels
{
public class DetailSearchModel
{
public int? Id { get; set; }
public string? DetailName { get; set; }
}
}

View File

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

View File

@ -0,0 +1,8 @@
namespace ShipyardContracts.SearchModels
{
public class ShipSearchModel
{
public int? Id { get; set; }
public string? ShipName { get; set; }
}
}

View File

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

View File

@ -0,0 +1,17 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.StoragesContracts
{
public interface IDetailStorage
{
List<DetailViewModel> GetFullList();
List<DetailViewModel> GetFilteredList(DetailSearchModel model);
DetailViewModel? GetElement(DetailSearchModel model);
DetailViewModel? Insert(DetailBindingModel model);
DetailViewModel? Update(DetailBindingModel model);
DetailViewModel? Delete(DetailBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.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

@ -0,0 +1,16 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.ViewModels;
namespace ShipyardContracts.StoragesContracts
{
public interface IShipStorage
{
List<ShipViewModel> GetFullList();
List<ShipViewModel> GetFilteredList(ShipSearchModel model);
ShipViewModel? GetElement(ShipSearchModel model);
ShipViewModel? Insert(ShipBindingModel model);
ShipViewModel? Update(ShipBindingModel model);
ShipViewModel? Delete(ShipBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ShipyardDataModels.Models;
using System.ComponentModel;
namespace ShipyardContracts.ViewModels
{
public class DetailViewModel : IDetailModel
{
public int Id { get; set; }
[DisplayName("Название детали")]
public string DetailName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using ShipyardDataModels.Enums;
using ShipyardDataModels.Models;
using System.ComponentModel;
namespace ShipyardContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int ShipId { get; set; }
[DisplayName("Название")]
public string ShipName { 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

@ -0,0 +1,14 @@
namespace ShipyardContracts.ViewModels
{
public class ReportOrdersViewModel
{
public int Id { get; set; }
public DateTime DateCreate { get; set; }
public string ShipName { get; set; } = string.Empty;
public string OrderStatus { get; set; } = string.Empty;
public double Sum { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace ShipyardContracts.ViewModels
{
public class ReportShipDetailViewModel
{
public string ShipName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Detail, int Count)> Details { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using ShipyardDataModels.Models;
using System.ComponentModel;
namespace ShipyardContracts.ViewModels
{
public class ShipViewModel : IShipModel
{
public int Id { get; set; }
[DisplayName("Название корабля")]
public string ShipName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IDetailModel, int)> ShipDetails { get; set; } = new();
}
}

View File

@ -0,0 +1,84 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataBaseImplement.Models;
namespace ShipyardDataBaseImplement.Implements
{
public class DetailStorage : IDetailStorage
{
public List<DetailViewModel> GetFullList()
{
using var context = new ShipyardDataBase();
return context.Details
.Select(x => x.GetViewModel)
.ToList();
}
public List<DetailViewModel> GetFilteredList(DetailSearchModel model)
{
if (string.IsNullOrEmpty(model.DetailName))
{
return new();
}
using var context = new ShipyardDataBase();
return context.Details
.Where(x => x.DetailName.Contains(model.DetailName))
.Select(x => x.GetViewModel)
.ToList();
}
public DetailViewModel? GetElement(DetailSearchModel model)
{
if (string.IsNullOrEmpty(model.DetailName) && !model.Id.HasValue)
{
return null;
}
using var context = new ShipyardDataBase();
return context.Details
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.DetailName) && x.DetailName ==
model.DetailName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public DetailViewModel? Insert(DetailBindingModel model)
{
var newDetail = Detail.Create(model);
if (newDetail == null)
{
return null;
}
using var context = new ShipyardDataBase();
context.Details.Add(newDetail);
context.SaveChanges();
return newDetail.GetViewModel;
}
public DetailViewModel? Update(DetailBindingModel model)
{
using var context = new ShipyardDataBase();
var detail = context.Details.FirstOrDefault(x => x.Id ==
model.Id);
if (detail == null)
{
return null;
}
detail.Update(model);
context.SaveChanges();
return detail.GetViewModel;
}
public DetailViewModel? Delete(DetailBindingModel model)
{
using var context = new ShipyardDataBase();
var element = context.Details.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Details.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,106 @@
using Microsoft.EntityFrameworkCore;
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataBaseImplement.Models;
namespace ShipyardDataBaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new ShipyardDataBase();
var element = context.Orders
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
var deletedElement = context.Orders
.Include(x => x.Ship)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
context.Orders.Remove(element);
context.SaveChanges();
return deletedElement;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new ShipyardDataBase();
return context.Orders
.Include(x => x.Ship)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new ShipyardDataBase();
if (!model.Id.HasValue && !model.DateFrom.HasValue)
{
return new();
}
if (model.DateFrom.HasValue)
{
return context.Orders
.Include(x => x.Ship)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Ship)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new ShipyardDataBase();
return context.Orders
.Include(x => x.Ship)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new ShipyardDataBase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders
.Include(x => x.Ship)
.FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new ShipyardDataBase();
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.Ship)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
}
}

View File

@ -0,0 +1,102 @@
using Microsoft.EntityFrameworkCore;
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardDataBaseImplement.Models;
namespace ShipyardDataBaseImplement.Implements
{
public class ShipStorage : IShipStorage
{
public List<ShipViewModel> GetFullList()
{
using var context = new ShipyardDataBase();
return context.Ships.Include(x => x.Details)
.ThenInclude(x => x.Detail)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName))
{
return new();
}
using var context = new ShipyardDataBase();
return context.Ships
.Include(x => x.Details)
.ThenInclude(x => x.Detail)
.Where(x => x.ShipName.Contains(model.ShipName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ShipViewModel? GetElement(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new ShipyardDataBase();
return context.Ships
.Include(x => x.Details)
.ThenInclude(x => x.Detail)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShipName) &&
x.ShipName == model.ShipName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShipViewModel? Insert(ShipBindingModel model)
{
using var context = new ShipyardDataBase();
var newProduct = Ship.Create(context, model);
if (newProduct == null)
{
return null;
}
context.Ships.Add(newProduct);
context.SaveChanges();
return newProduct.GetViewModel;
}
public ShipViewModel? Update(ShipBindingModel model)
{
using var context = new ShipyardDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var product = context.Ships.FirstOrDefault(rec => rec.Id == model.Id);
if (product == null)
{
return null;
}
product.Update(model);
context.SaveChanges();
product.UpdateComponents(context, model);
transaction.Commit();
return product.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShipViewModel? Delete(ShipBindingModel model)
{
using var context = new ShipyardDataBase();
var element = context.Ships
.Include(x => x.Details)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Ships.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,171 @@
// <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 ShipyardDataBaseImplement;
#nullable disable
namespace ShipyardDataBaseImplement.Migrations
{
[DbContext(typeof(ShipyardDataBase))]
[Migration("20240310181644_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Detail", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("DetailName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Details");
});
modelBuilder.Entity("ShipyardDataBaseImplement.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>("ShipId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ShipId");
b.ToTable("Orders");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Ship", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ShipName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Ships");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.ShipDetail", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DetailId")
.HasColumnType("int");
b.Property<int>("ShipId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DetailId");
b.HasIndex("ShipId");
b.ToTable("ShipDetails");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Order", b =>
{
b.HasOne("ShipyardDataBaseImplement.Models.Ship", "Ship")
.WithMany("Orders")
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ship");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.ShipDetail", b =>
{
b.HasOne("ShipyardDataBaseImplement.Models.Detail", "Detail")
.WithMany("ShipDetails")
.HasForeignKey("DetailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShipyardDataBaseImplement.Models.Ship", "Ship")
.WithMany("Details")
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Detail");
b.Navigation("Ship");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Detail", b =>
{
b.Navigation("ShipDetails");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Ship", b =>
{
b.Navigation("Details");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,125 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ShipyardDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Details",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DetailName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Details", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Ships",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShipName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ships", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShipId = table.Column<int>(type: "int", nullable: false),
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)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Ships_ShipId",
column: x => x.ShipId,
principalTable: "Ships",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShipDetails",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShipId = table.Column<int>(type: "int", nullable: false),
DetailId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShipDetails", x => x.Id);
table.ForeignKey(
name: "FK_ShipDetails_Details_DetailId",
column: x => x.DetailId,
principalTable: "Details",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShipDetails_Ships_ShipId",
column: x => x.ShipId,
principalTable: "Ships",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ShipId",
table: "Orders",
column: "ShipId");
migrationBuilder.CreateIndex(
name: "IX_ShipDetails_DetailId",
table: "ShipDetails",
column: "DetailId");
migrationBuilder.CreateIndex(
name: "IX_ShipDetails_ShipId",
table: "ShipDetails",
column: "ShipId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShipDetails");
migrationBuilder.DropTable(
name: "Details");
migrationBuilder.DropTable(
name: "Ships");
}
}
}

View File

@ -0,0 +1,168 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ShipyardDataBaseImplement;
#nullable disable
namespace ShipyardDataBaseImplement.Migrations
{
[DbContext(typeof(ShipyardDataBase))]
partial class ShipyardDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Detail", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("DetailName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Details");
});
modelBuilder.Entity("ShipyardDataBaseImplement.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>("ShipId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ShipId");
b.ToTable("Orders");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Ship", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ShipName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Ships");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.ShipDetail", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DetailId")
.HasColumnType("int");
b.Property<int>("ShipId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DetailId");
b.HasIndex("ShipId");
b.ToTable("ShipDetails");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Order", b =>
{
b.HasOne("ShipyardDataBaseImplement.Models.Ship", "Ship")
.WithMany("Orders")
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ship");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.ShipDetail", b =>
{
b.HasOne("ShipyardDataBaseImplement.Models.Detail", "Detail")
.WithMany("ShipDetails")
.HasForeignKey("DetailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ShipyardDataBaseImplement.Models.Ship", "Ship")
.WithMany("Details")
.HasForeignKey("ShipId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Detail");
b.Navigation("Ship");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Detail", b =>
{
b.Navigation("ShipDetails");
});
modelBuilder.Entity("ShipyardDataBaseImplement.Models.Ship", b =>
{
b.Navigation("Details");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,57 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace ShipyardDataBaseImplement.Models
{
public class Detail : IDetailModel
{
public int Id { get; private set; }
[Required]
public string DetailName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("DetailId")]
public virtual List<ShipDetail> ShipDetails { get; set; } = new();
public static Detail? Create(DetailBindingModel model)
{
if (model == null)
{
return null;
}
return new Detail()
{
Id = model.Id,
DetailName = model.DetailName,
Cost = model.Cost
};
}
public static Detail Create(DetailViewModel model)
{
return new Detail
{
Id = model.Id,
DetailName = model.DetailName,
Cost = model.Cost
};
}
public void Update(DetailBindingModel model)
{
if (model == null)
{
return;
}
DetailName = model.DetailName;
Cost = model.Cost;
}
public DetailViewModel GetViewModel => new()
{
Id = Id,
DetailName = DetailName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,64 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Enums;
using ShipyardDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace ShipyardDataBaseImplement.Models
{
public class Order : IOrderModel
{
[Required]
public int ShipId { get; set; }
[Required]
public int Count { get; set; }
[Required]
public double Sum { get; set; }
[Required]
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int Id { get; set; }
public virtual Ship Ship { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
ShipId = model.ShipId,
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,
ShipId = ShipId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
ShipName = Ship.ShipName
};
}
}

View File

@ -0,0 +1,90 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace ShipyardDataBaseImplement.Models
{
public class Ship : IShipModel
{
public int Id { get; set; }
[Required]
public string ShipName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IDetailModel, int)>? _shipDetails = null;
[NotMapped]
public Dictionary<int, (IDetailModel, int)> ShipDetails
{
get
{
if (_shipDetails == null)
{
_shipDetails = Details.ToDictionary(recPC => recPC.DetailId, recPC =>
(recPC.Detail as IDetailModel, recPC.Count));
}
return _shipDetails;
}
}
[ForeignKey("ShipId")]
public virtual List<ShipDetail> Details { get; set; } = new();
[ForeignKey("ShipId")]
public virtual List<Order> Orders { get; set; } = new();
public static Ship Create(ShipyardDataBase context, ShipBindingModel model)
{
return new Ship()
{
Id = model.Id,
ShipName = model.ShipName,
Price = model.Price,
Details = model.ShipDetails.Select(x => new ShipDetail
{
Detail = context.Details.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShipBindingModel model)
{
ShipName = model.ShipName;
Price = model.Price;
}
public ShipViewModel GetViewModel => new()
{
Id = Id,
ShipName = ShipName,
Price = Price,
ShipDetails = ShipDetails
};
public void UpdateComponents(ShipyardDataBase context,
ShipBindingModel model)
{
var shipDetails = context.ShipDetails.Where(rec => rec.ShipId == model.Id).ToList();
if (shipDetails != null && shipDetails.Count > 0)
{ // удалили те, которых нет в модели
context.ShipDetails.RemoveRange(shipDetails.Where(rec => !model.ShipDetails.ContainsKey(rec.DetailId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateDetail in shipDetails)
{
updateDetail.Count = model.ShipDetails[updateDetail.DetailId].Item2;
model.ShipDetails.Remove(updateDetail.DetailId);
}
context.SaveChanges();
}
var ship = context.Ships.First(x => x.Id == Id);
foreach (var pc in model.ShipDetails)
{
context.ShipDetails.Add(new ShipDetail
{
Ship = ship,
Detail = context.Details.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_shipDetails = null;
}
}
}

View File

@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations;
namespace ShipyardDataBaseImplement.Models
{
public class ShipDetail
{
public int Id { get; set; }
[Required]
public int ShipId { get; set; }
[Required]
public int DetailId { get; set; }
[Required]
public int Count { get; set; }
public virtual Detail Detail { get; set; } = new();
public virtual Ship Ship { get; set; } = new();
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore;
using ShipyardDataBaseImplement.Models;
namespace ShipyardDataBaseImplement
{
public class ShipyardDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-JJTVLCG\SQLEXPRESS02;Initial Catalog=ShipyardDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Detail> Details { set; get; }
public virtual DbSet<Ship> Ships { set; get; }
public virtual DbSet<ShipDetail> ShipDetails { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<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.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ShipyardContracts\ShipyardContracts.csproj" />
<ProjectReference Include="..\ShipyardDataModels\ShipyardDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@

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

View File

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

View File

@ -0,0 +1,8 @@
namespace ShipyardDataModels.Models
{
public interface IDetailModel : IId
{
string DetailName { get; }
double Cost { get; }
}
}

View File

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

View File

@ -0,0 +1,9 @@
namespace ShipyardDataModels.Models
{
public interface IShipModel : IId
{
string ShipName { get; }
double Price { get; }
Dictionary<int, (IDetailModel, int)> ShipDetails { get; }
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,51 @@
using ShipyardFileImplement.Models;
using System.Xml.Linq;
namespace ShipyardFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string DetailFileName = "Detail.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string ShipFileName = "Ship.xml";
public List<Detail> Details { get; private set; }
public List<Order> Orders { get; private set; }
public List<Ship> Ships { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveDetails() => SaveData(Details, DetailFileName, "Details", x => x.GetXElement);
public void SaveShips() => SaveData(Ships, ShipFileName, "Ships", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
private DataFileSingleton()
{
Details = LoadData(DetailFileName, "Detail", x => Detail.Create(x)!)!;
Ships = LoadData(ShipFileName, "Ship", x => Ship.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

@ -0,0 +1,75 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardContracts.SearchModels;
using ShipyardFileImplement.Models;
namespace ShipyardFileImplement.Implements
{
public class DetailStorage : IDetailStorage
{
private readonly DataFileSingleton source;
public DetailStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<DetailViewModel> GetFullList()
{
return source.Details.Select(x => x.GetViewModel).ToList();
}
public List<DetailViewModel> GetFilteredList(DetailSearchModel model)
{
if (string.IsNullOrEmpty(model.DetailName))
{
return new();
}
return source.Details
.Where(x => x.DetailName.Contains(model.DetailName)).Select(x => x.GetViewModel).ToList();
}
public DetailViewModel? GetElement(DetailSearchModel model)
{
if (string.IsNullOrEmpty(model.DetailName) && !model.Id.HasValue)
{
return null;
}
return source.Details
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.DetailName)
&& x.DetailName == model.DetailName)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public DetailViewModel? Insert(DetailBindingModel model)
{
model.Id = source.Details.Count > 0 ? source.Details.Max(x => x.Id) + 1 : 1;
var newComponent = Detail.Create(model);
if (newComponent == null)
{
return null;
}
source.Details.Add(newComponent);
source.SaveDetails();
return newComponent.GetViewModel;
}
public DetailViewModel? Update(DetailBindingModel model)
{
var component = source.Details.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveDetails();
return component.GetViewModel;
}
public DetailViewModel? Delete(DetailBindingModel model)
{
var element = source.Details.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Details.Remove(element);
source.SaveDetails();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,95 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardContracts.SearchModels;
using ShipyardFileImplement.Models;
namespace ShipyardFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue)
{
return new();
}
if (model.DateFrom.HasValue)
{
return source.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
}
return source.Orders.Where(x => x.Id.Equals(model.Id)).Select(x => GetViewModel(x)).ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Orders.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var ship = source.Ships.FirstOrDefault(x => x.Id == order.ShipId);
if (ship != null)
{
viewModel.ShipName = ship.ShipName;
}
return viewModel;
}
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 element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Orders.Remove(element);
source.SaveOrders();
return GetViewModel(element);
}
return null;
}
}
}

View File

@ -0,0 +1,73 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardContracts.SearchModels;
using ShipyardFileImplement.Models;
namespace ShipyardFileImplement.Implements
{
public class ShipStorage : IShipStorage
{
private readonly DataFileSingleton source;
public ShipStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShipViewModel> GetFullList()
{
return source.Ships.Select(x => x.GetViewModel).ToList();
}
public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName))
{
return new();
}
return source.Ships.Where(x => x.ShipName.Contains(model.ShipName)).Select(x => x.GetViewModel).ToList();
}
public ShipViewModel? GetElement(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName) && !model.Id.HasValue)
{
return null;
}
return source.Ships.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShipName) && x.ShipName ==
model.ShipName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShipViewModel? Insert(ShipBindingModel model)
{
model.Id = source.Ships.Count > 0 ? source.Ships.Max(x => x.Id) + 1 : 1;
var newShip = Ship.Create(model);
if (newShip == null)
{
return null;
}
source.Ships.Add(newShip);
source.SaveShips();
return newShip.GetViewModel;
}
public ShipViewModel? Update(ShipBindingModel model)
{
var ship = source.Ships.FirstOrDefault(x => x.Id == model.Id);
if (ship == null)
{
return null;
}
ship.Update(model);
source.SaveShips();
return ship.GetViewModel;
}
public ShipViewModel? Delete(ShipBindingModel model)
{
var element = source.Ships.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Ships.Remove(element);
source.SaveShips();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,60 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System.Xml.Linq;
namespace ShipyardFileImplement.Models
{
public class Detail : IDetailModel
{
public int Id { get; private set; }
public string DetailName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Detail? Create(DetailBindingModel model)
{
if (model == null)
{
return null;
}
return new Detail()
{
Id = model.Id,
DetailName = model.DetailName,
Cost = model.Cost
};
}
public static Detail? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Detail()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
DetailName = element.Element("DetailName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(DetailBindingModel model)
{
if (model == null)
{
return;
}
DetailName = model.DetailName;
Cost = model.Cost;
}
public DetailViewModel GetViewModel => new()
{
Id = Id,
DetailName = DetailName,
Cost = Cost
};
public XElement GetXElement => new("Detail",
new XAttribute("Id", Id),
new XElement("DetailName", DetailName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,91 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Enums;
using ShipyardDataModels.Models;
using System.Xml.Linq;
namespace ShipyardFileImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int ShipId { 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 static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
ShipId = model.ShipId,
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),
ShipId = Convert.ToInt32(element.Element("ShipId")!.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()
{
ShipId = ShipId,
Count = Count,
Sum = Sum,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status,
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("ShipId", ShipId),
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

@ -0,0 +1,80 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System.Xml.Linq;
namespace ShipyardFileImplement.Models
{
public class Ship : IShipModel
{
public int Id { get; private set; }
public string ShipName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Details { get; private set; } = new();
private Dictionary<int, (IDetailModel, int)>? _shipDetails = null;
public Dictionary<int, (IDetailModel, int)> ShipDetails
{
get
{
if (_shipDetails == null)
{
var source = DataFileSingleton.GetInstance();
_shipDetails = Details.ToDictionary(x => x.Key, y => ((source.Details.FirstOrDefault(z => z.Id == y.Key) as IDetailModel)!, y.Value));
}
return _shipDetails;
}
}
public static Ship? Create(ShipBindingModel model)
{
if (model == null)
{
return null;
}
return new Ship()
{
Id = model.Id,
ShipName = model.ShipName,
Price = model.Price,
Details = model.ShipDetails.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Ship? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Ship()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShipName = element.Element("ShipName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Details = element.Element("ShipDetails")!.Elements("ShipDetail").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShipBindingModel model)
{
if (model == null)
{
return;
}
ShipName = model.ShipName;
Price = model.Price;
Details = model.ShipDetails.ToDictionary(x => x.Key, x => x.Value.Item2);
_shipDetails = null;
}
public ShipViewModel GetViewModel => new()
{
Id = Id,
ShipName = ShipName,
Price = Price,
ShipDetails = ShipDetails
};
public XElement GetXElement => new("Ship",
new XAttribute("Id", Id),
new XElement("ShipName", ShipName),
new XElement("Price", Price.ToString()),
new XElement("ShipDetails", ShipDetails.Select(x => new XElement("ShipDetails",
new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}

View File

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

View File

@ -0,0 +1,26 @@
using ShipyardListImplement.Models;
namespace ShipyardListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Detail> Details { get; set; }
public List<Order> Orders { get; set; }
public List<Ship> Ships { get; set; }
private DataListSingleton()
{
Details = new List<Detail>();
Orders = new List<Order>();
Ships = new List<Ship>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,103 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardListImplement.Models;
namespace ShipyardListImplement.Implements
{
public class DetailStorage : IDetailStorage
{
private readonly DataListSingleton _source;
public DetailStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<DetailViewModel> GetFullList()
{
var result = new List<DetailViewModel>();
foreach (var detail in _source.Details)
{
result.Add(detail.GetViewModel);
}
return result;
}
public List<DetailViewModel> GetFilteredList(DetailSearchModel model)
{
var result = new List<DetailViewModel>();
if (string.IsNullOrEmpty(model.DetailName))
{
return result;
}
foreach (var detail in _source.Details)
{
if (detail.DetailName.Contains(model.DetailName))
{
result.Add(detail.GetViewModel);
}
}
return result;
}
public DetailViewModel? GetElement(DetailSearchModel model)
{
if (string.IsNullOrEmpty(model.DetailName) && !model.Id.HasValue)
{
return null;
}
foreach (var detail in _source.Details)
{
if ((!string.IsNullOrEmpty(model.DetailName) &&
detail.DetailName == model.DetailName) ||
(model.Id.HasValue && detail.Id == model.Id))
{
return detail.GetViewModel;
}
}
return null;
}
public DetailViewModel? Insert(DetailBindingModel model)
{
model.Id = 1;
foreach (var component in _source.Details)
{
if (model.Id <= component.Id)
{
model.Id = component.Id + 1;
}
}
var newDetail = Detail.Create(model);
if (newDetail == null)
{
return null;
}
_source.Details.Add(newDetail);
return newDetail.GetViewModel;
}
public DetailViewModel? Update(DetailBindingModel model)
{
foreach (var detail in _source.Details)
{
if (detail.Id == model.Id)
{
detail.Update(model);
return detail.GetViewModel;
}
}
return null;
}
public DetailViewModel? Delete(DetailBindingModel model)
{
for (int i = 0; i < _source.Details.Count; ++i)
{
if (_source.Details[i].Id == model.Id)
{
var element = _source.Details[i];
_source.Details.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,124 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardListImplement.Models;
namespace ShipyardListImplement.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(GetViewModel(order));
}
return result;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue && !model.DateFrom.HasValue)
{
return result;
}
if (model.DateFrom.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo)
{
result.Add(GetViewModel(order));
}
}
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(GetViewModel(order));
}
}
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 GetViewModel(order);
}
}
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 GetViewModel(newOrder);
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return GetViewModel(order);
}
}
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 GetViewModel(element);
}
}
return null;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
foreach (var ship in _source.Ships)
{
if (ship.Id == order.ShipId)
{
viewModel.ShipName = ship.ShipName;
break;
}
}
return viewModel;
}
}
}

View File

@ -0,0 +1,102 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardListImplement.Models;
namespace ShipyardListImplement.Implements
{
public class ShipStorage : IShipStorage
{
private readonly DataListSingleton _source;
public ShipStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShipViewModel> GetFullList()
{
var result = new List<ShipViewModel>();
foreach (var ship in _source.Ships)
{
result.Add(ship.GetViewModel);
}
return result;
}
public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
{
var result = new List<ShipViewModel>();
if (string.IsNullOrEmpty(model.ShipName))
{
return result;
}
foreach (var ship in _source.Ships)
{
if (ship.ShipName.Contains(model.ShipName))
{
result.Add(ship.GetViewModel);
}
}
return result;
}
public ShipViewModel? GetElement(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName) && !model.Id.HasValue)
{
return null;
}
foreach (var ship in _source.Ships)
{
if ((!string.IsNullOrEmpty(model.ShipName) &&
ship.ShipName == model.ShipName) ||
(model.Id.HasValue && ship.Id == model.Id))
{
return ship.GetViewModel;
}
}
return null;
}
public ShipViewModel? Insert(ShipBindingModel model)
{
model.Id = 1;
foreach (var ship in _source.Ships)
{
if (model.Id <= ship.Id)
{
model.Id = ship.Id + 1;
}
}
var newShip = Ship.Create(model);
if (newShip == null)
{
return null;
}
_source.Ships.Add(newShip);
return newShip.GetViewModel;
}
public ShipViewModel? Update(ShipBindingModel model)
{
foreach (var ship in _source.Ships)
{
if (ship.Id == model.Id)
{
ship.Update(model);
return ship.GetViewModel;
}
}
return null;
}
public ShipViewModel? Delete(ShipBindingModel model)
{
for (int i = 0; i < _source.Ships.Count; ++i)
{
if (_source.Ships[i].Id == model.Id)
{
var element = _source.Ships[i];
_source.Ships.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,42 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
namespace ShipyardListImplement.Models
{
public class Detail : IDetailModel
{
public int Id { get; private set; }
public string DetailName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Detail? Create(DetailBindingModel? model)
{
if (model == null)
{
return null;
}
return new Detail()
{
Id = model.Id,
DetailName = model.DetailName,
Cost = model.Cost
};
}
public void Update(DetailBindingModel? model)
{
if (model == null)
{
return;
}
DetailName = model.DetailName;
Cost = model.Cost;
}
public DetailViewModel GetViewModel => new()
{
Id = Id,
DetailName = DetailName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,56 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Enums;
using ShipyardDataModels.Models;
namespace ShipyardListImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int ShipId { 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 static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
ShipId = model.ShipId,
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,
ShipId = ShipId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,46 @@
using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
namespace ShipyardListImplement.Models
{
public class Ship : IShipModel
{
public int Id { get; private set; }
public string ShipName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, (IDetailModel, int)> ShipDetails { get; private set; } = new Dictionary<int, (IDetailModel, int)>();
public static Ship? Create(ShipBindingModel? model)
{
if (model == null)
{
return null;
}
return new Ship()
{
Id = model.Id,
ShipName = model.ShipName,
Price = model.Price,
ShipDetails = model.ShipDetails
};
}
public void Update(ShipBindingModel? model)
{
if (model == null)
{
return;
}
ShipName = model.ShipName;
Price = model.Price;
ShipDetails = model.ShipDetails;
}
public ShipViewModel GetViewModel => new()
{
Id = Id,
ShipName = ShipName,
Price = Price,
ShipDetails = ShipDetails
};
}
}

View File

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

View File

@ -0,0 +1,144 @@
namespace ShipyardView
{
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()
{
labelShip = new Label();
labelCount = new Label();
labelSum = new Label();
comboBoxShips = new ComboBox();
textBoxCount = new TextBox();
textBoxSum = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelShip
//
labelShip.AutoSize = true;
labelShip.Location = new Point(40, 23);
labelShip.Name = "labelShip";
labelShip.Size = new Size(72, 20);
labelShip.TabIndex = 0;
labelShip.Text = "Корабль:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(40, 63);
labelCount.Name = "labelCount";
labelCount.Size = new Size(93, 20);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// labelSum
//
labelSum.AutoSize = true;
labelSum.Location = new Point(40, 105);
labelSum.Name = "labelSum";
labelSum.Size = new Size(58, 20);
labelSum.TabIndex = 2;
labelSum.Text = "Сумма:";
//
// comboBoxShips
//
comboBoxShips.FormattingEnabled = true;
comboBoxShips.Location = new Point(144, 20);
comboBoxShips.Name = "comboBoxShips";
comboBoxShips.Size = new Size(360, 28);
comboBoxShips.TabIndex = 3;
comboBoxShips.SelectedIndexChanged += ComboBoxShips_SelectedIndexChanged;
//
// textBoxCount
//
textBoxCount.Location = new Point(144, 60);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(360, 27);
textBoxCount.TabIndex = 4;
textBoxCount.TextChanged += TextBoxCount_TextChanged;
//
// textBoxSum
//
textBoxSum.Location = new Point(144, 102);
textBoxSum.Name = "textBoxSum";
textBoxSum.ReadOnly = true;
textBoxSum.Size = new Size(360, 27);
textBoxSum.TabIndex = 5;
//
// buttonSave
//
buttonSave.Location = new Point(236, 149);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(111, 40);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(372, 149);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(111, 40);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(540, 201);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSum);
Controls.Add(textBoxCount);
Controls.Add(comboBoxShips);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelShip);
Name = "FormCreateOrder";
Text = "FormCreateOrder";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelShip;
private Label labelCount;
private Label labelSum;
private ComboBox comboBoxShips;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,117 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
namespace ShipyardView
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IShipLogic _logicS;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IShipLogic logicS, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicS = logicS;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка кораблей для заказа");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxShips.DisplayMember = "ShipName";
comboBoxShips.ValueMember = "Id";
comboBoxShips.DataSource = list;
comboBoxShips.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка кораблей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (comboBoxShips.SelectedValue != null &&
!string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxShips.SelectedValue);
var product = _logicS.ReadElement(new ShipSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.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 ComboBoxShips_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 (comboBoxShips.SelectedValue == null)
{
MessageBox.Show("Выберите корабль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ShipId = Convert.ToInt32(comboBoxShips.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,120 @@
namespace ShipyardView
{
partial class FormDetail
{
/// <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()
{
textBoxName = new TextBox();
textBoxCost = new TextBox();
labelName = new Label();
labelCost = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(152, 27);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(342, 27);
textBoxName.TabIndex = 0;
//
// textBoxCost
//
textBoxCost.Location = new Point(152, 60);
textBoxCost.Name = "textBoxCost";
textBoxCost.Size = new Size(142, 27);
textBoxCost.TabIndex = 1;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(49, 30);
labelName.Name = "labelName";
labelName.Size = new Size(80, 20);
labelName.TabIndex = 2;
labelName.Text = "Название:";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(49, 67);
labelCost.Name = "labelCost";
labelCost.Size = new Size(48, 20);
labelCost.TabIndex = 3;
labelCost.Text = "Цена:";
//
// buttonSave
//
buttonSave.BackColor = SystemColors.Control;
buttonSave.Location = new Point(313, 95);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(109, 37);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = false;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.BackColor = SystemColors.Control;
buttonCancel.Location = new Point(428, 95);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(109, 37);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = false;
buttonCancel.Click += ButtonCancel_Click;
//
// FormDetail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(572, 144);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelCost);
Controls.Add(labelName);
Controls.Add(textBoxCost);
Controls.Add(textBoxName);
Name = "FormDetail";
Text = "Деталь";
Load += FormDetail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private TextBox textBoxCost;
private Label labelName;
private Label labelCost;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,88 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using System.Windows.Forms;
namespace ShipyardView
{
public partial class FormDetail : Form
{
private readonly ILogger _logger;
private readonly IDetailLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormDetail(ILogger<FormDetail> logger, IDetailLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormDetail_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение детали");
var view = _logic.ReadElement(new DetailSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.DetailName;
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 DetailBindingModel
{
Id = _id ?? 0,
DetailName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения детали");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,120 @@
namespace ShipyardView
{
partial class FormDetails
{
/// <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();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(-2, -1);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(477, 473);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(499, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(125, 41);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(499, 79);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(125, 41);
buttonUpdate.TabIndex = 2;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(499, 149);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(125, 41);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(499, 221);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(125, 41);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormDetails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(636, 471);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormDetails";
Text = " Детали";
Load += FormDetails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using System.Windows.Forms;
namespace ShipyardView
{
public partial class FormDetails : Form
{
private readonly ILogger _logger;
private readonly IDetailLogic _logic;
public FormDetails(ILogger<FormDetails> logger, IDetailLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormDetails_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["DetailName"].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(FormDetail));
if (service is FormDetail 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(FormDetail));
if (service is FormDetail 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 DetailBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления детали");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

220
Shipyard/ShipyardView/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,220 @@
namespace ShipyardView
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
toolStrip = new ToolStrip();
toolStripMenu = new ToolStripDropDownButton();
деталиToolStripMenuItem = new ToolStripMenuItem();
кораблиToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripDropDownButton();
ShipsToolStripMenuItem = new ToolStripMenuItem();
shipsDetailsToolStripMenuItem = new ToolStripMenuItem();
ordersToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeInWork = new Button();
buttonReady = new Button();
buttonIssue = new Button();
buttonRefresh = new Button();
toolStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// toolStrip
//
toolStrip.ImageScalingSize = new Size(20, 20);
toolStrip.Items.AddRange(new ToolStripItem[] { toolStripMenu, отчетыToolStripMenuItem });
toolStrip.Location = new Point(0, 0);
toolStrip.Name = "toolStrip";
toolStrip.Size = new Size(1251, 27);
toolStrip.TabIndex = 0;
toolStrip.Text = "Справочники";
//
// toolStripMenu
//
toolStripMenu.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripMenu.DropDownItems.AddRange(new ToolStripItem[] { деталиToolStripMenuItem, кораблиToolStripMenuItem });
toolStripMenu.Image = (Image)resources.GetObject("toolStripMenu.Image");
toolStripMenu.ImageTransparentColor = Color.Magenta;
toolStripMenu.Name = "toolStripMenu";
toolStripMenu.Size = new Size(117, 24);
toolStripMenu.Text = "Справочники";
//
// деталиToolStripMenuItem
//
деталиToolStripMenuItem.Name = еталиToolStripMenuItem";
деталиToolStripMenuItem.Size = new Size(153, 26);
деталиToolStripMenuItem.Text = "Детали";
деталиToolStripMenuItem.Click += ДеталиToolStripMenuItem_Click;
//
// кораблиToolStripMenuItem
//
кораблиToolStripMenuItem.Name = ораблиToolStripMenuItem";
кораблиToolStripMenuItem.Size = new Size(153, 26);
кораблиToolStripMenuItem.Text = "Корабли";
кораблиToolStripMenuItem.Click += КораблиToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DisplayStyle = ToolStripItemDisplayStyle.Text;
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ShipsToolStripMenuItem, shipsDetailsToolStripMenuItem, ordersToolStripMenuItem });
отчетыToolStripMenuItem.Image = (Image)resources.GetObject("отчетыToolStripMenuItem.Image");
отчетыToolStripMenuItem.ImageTransparentColor = Color.Magenta;
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(73, 24);
отчетыToolStripMenuItem.Text = "Отчёты";
//
// ShipsToolStripMenuItem
//
ShipsToolStripMenuItem.Name = "ShipsToolStripMenuItem";
ShipsToolStripMenuItem.Size = new Size(236, 26);
ShipsToolStripMenuItem.Text = "Список кораблей";
ShipsToolStripMenuItem.Click += ShipsToolStripMenuItem_Click;
//
// shipsDetailsToolStripMenuItem
//
shipsDetailsToolStripMenuItem.Name = "shipsDetailsToolStripMenuItem";
shipsDetailsToolStripMenuItem.Size = new Size(236, 26);
shipsDetailsToolStripMenuItem.Text = "Корабли по деталям";
shipsDetailsToolStripMenuItem.Click += shipDetailsToolStripMenuItem_Click;
//
// ordersToolStripMenuItem
//
ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
ordersToolStripMenuItem.Size = new Size(236, 26);
ordersToolStripMenuItem.Text = "Список заказов";
ordersToolStripMenuItem.Click += ordersToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 28);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(984, 366);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1032, 51);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(178, 29);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeInWork
//
buttonTakeInWork.Location = new Point(1032, 110);
buttonTakeInWork.Name = "buttonTakeInWork";
buttonTakeInWork.Size = new Size(178, 29);
buttonTakeInWork.TabIndex = 3;
buttonTakeInWork.Text = "Отдать на выполнение";
buttonTakeInWork.UseVisualStyleBackColor = true;
buttonTakeInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonReady
//
buttonReady.Location = new Point(1032, 171);
buttonReady.Name = "buttonReady";
buttonReady.Size = new Size(178, 29);
buttonReady.TabIndex = 4;
buttonReady.Text = "Заказ готов";
buttonReady.UseVisualStyleBackColor = true;
buttonReady.Click += ButtonOrderReady_Click;
//
// buttonIssue
//
buttonIssue.Location = new Point(1032, 236);
buttonIssue.Name = "buttonIssue";
buttonIssue.Size = new Size(178, 29);
buttonIssue.TabIndex = 5;
buttonIssue.Text = "Заказ выдан";
buttonIssue.UseVisualStyleBackColor = true;
buttonIssue.Click += ButtonIssuedOrder_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(1032, 303);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(178, 29);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить список";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1251, 391);
Controls.Add(buttonRefresh);
Controls.Add(buttonIssue);
Controls.Add(buttonReady);
Controls.Add(buttonTakeInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(toolStrip);
Name = "FormMain";
Text = "Форма заказов";
Load += FormMain_Load;
toolStrip.ResumeLayout(false);
toolStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private ToolStrip toolStrip;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeInWork;
private Button buttonReady;
private Button buttonIssue;
private Button buttonRefresh;
private ToolStripDropDownButton toolStripMenu;
private ToolStripMenuItem деталиToolStripMenuItem;
private ToolStripMenuItem кораблиToolStripMenuItem;
private ToolStripDropDownButton отчетыToolStripMenuItem;
private ToolStripMenuItem ShipsToolStripMenuItem;
private ToolStripMenuItem shipsDetailsToolStripMenuItem;
private ToolStripMenuItem ordersToolStripMenuItem;
}
}

View File

@ -0,0 +1,170 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardDataModels.Enums;
using ShipyardView;
using System.Windows.Forms;
namespace ShipyardView
{
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()
{
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ShipId"].Visible = false;
dataGridView.Columns["ShipName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ДеталиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDetails));
if (service is FormDetails form)
{
form.ShowDialog();
}
}
private void КораблиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShips));
if (service is FormShips 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("Заказ No{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ No{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("Заказ No{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ No{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ShipsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void shipDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShipDetails));
if (service is FormReportShipDetails form)
{
form.ShowDialog();
}
}
private void ordersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,146 @@
<?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>
<metadata name="toolStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="toolStripMenu.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEKSURBVEhL3ZG9DsFQHMXvczDZvIOtXsHObuhqkViI3Quw
6CYmNoMYJJ0NBiFFIoIytOuf0+TeXP3yde+iyS+3OcP53Z4y3/dJJ4HAsiwyTVMp6BQCBIZhKAWdEcHV
vSlBmeB82NFy1KLluEWOPRC5MoHdMWhazwi4RJlALgf4EuT6BI+5kCsTrGddUY658E+QvyXYHq9UnRyC
U87f4aUApcXhnrI9Jzg/laQKFntXlHM+lSQK5psL5fvbp/JvJLGCQqmSWM5JkiCT84igXGtSrruKLQ0T
luAdmZxHBG37FFuWBC/j5XKOmX8WAH7rcI6ZMffPgjQwN2bXJgDo/COBTpjneQ2dML0PY3cISreGe8HM
qgAAAABJRU5ErkJggg==
</value>
</data>
<data name="отчетыToolStripMenuItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEKSURBVEhL3ZG9DsFQHMXvczDZvIOtXsHObuhqkViI3Quw
6CYmNoMYJJ0NBiFFIoIytOuf0+TeXP3yde+iyS+3OcP53Z4y3/dJJ4HAsiwyTVMp6BQCBIZhKAWdEcHV
vSlBmeB82NFy1KLluEWOPRC5MoHdMWhazwi4RJlALgf4EuT6BI+5kCsTrGddUY658E+QvyXYHq9UnRyC
U87f4aUApcXhnrI9Jzg/laQKFntXlHM+lSQK5psL5fvbp/JvJLGCQqmSWM5JkiCT84igXGtSrruKLQ0T
luAdmZxHBG37FFuWBC/j5XKOmX8WAH7rcI6ZMffPgjQwN2bXJgDo/COBTpjneQ2dML0PY3cISreGe8HM
qgAAAABJRU5ErkJggg==
</value>
</data>
</root>

View File

@ -0,0 +1,131 @@
namespace ShipyardView
{
partial class FormReportOrders
{
/// <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.panel = new System.Windows.Forms.Panel();
this.buttonToPdf = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker();
this.labelTo = new System.Windows.Forms.Label();
this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker();
this.labelFrom = new System.Windows.Forms.Label();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
this.panel.Controls.Add(this.dateTimePickerTo);
this.panel.Controls.Add(this.labelTo);
this.panel.Controls.Add(this.dateTimePickerFrom);
this.panel.Controls.Add(this.labelFrom);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(926, 47);
this.panel.TabIndex = 0;
//
// buttonToPdf
//
this.buttonToPdf.Location = new System.Drawing.Point(825, 7);
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(94, 29);
this.buttonToPdf.TabIndex = 5;
this.buttonToPdf.Text = "в Pdf";
this.buttonToPdf.UseVisualStyleBackColor = true;
this.buttonToPdf.Click += new System.EventHandler(this.ButtonToPdf_Click);
//
// buttonMake
//
this.buttonMake.Location = new System.Drawing.Point(643, 7);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(149, 29);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
// dateTimePickerTo
//
this.dateTimePickerTo.Location = new System.Drawing.Point(348, 9);
this.dateTimePickerTo.Name = "dateTimePickerTo";
this.dateTimePickerTo.Size = new System.Drawing.Size(250, 27);
this.dateTimePickerTo.TabIndex = 3;
//
// labelTo
//
this.labelTo.AutoSize = true;
this.labelTo.Location = new System.Drawing.Point(292, 14);
this.labelTo.Name = "labelTo";
this.labelTo.Size = new System.Drawing.Size(27, 20);
this.labelTo.TabIndex = 2;
this.labelTo.Text = "по";
//
// dateTimePickerFrom
//
this.dateTimePickerFrom.Location = new System.Drawing.Point(36, 9);
this.dateTimePickerFrom.Name = "dateTimePickerFrom";
this.dateTimePickerFrom.Size = new System.Drawing.Size(250, 27);
this.dateTimePickerFrom.TabIndex = 1;
//
// labelFrom
//
this.labelFrom.AutoSize = true;
this.labelFrom.Location = new System.Drawing.Point(12, 14);
this.labelFrom.Name = "labelFrom";
this.labelFrom.Size = new System.Drawing.Size(18, 20);
this.labelFrom.TabIndex = 0;
this.labelFrom.Text = "C";
//
// FormReportOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(926, 450);
this.Controls.Add(this.panel);
this.Name = "FormReportOrders";
this.Text = "Заказы";
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonToPdf;
private Button buttonMake;
private DateTimePicker dateTimePickerTo;
private Label labelTo;
private DateTimePicker dateTimePickerFrom;
private Label labelFrom;
}
}

View File

@ -0,0 +1,100 @@
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShipyardView
{
public partial class FormReportOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var dataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
var parameters = new[] { new ReportParameter("ReportParameterPeriod",
$"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
_logger.LogInformation("Сохранение списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,107 @@
namespace ShipyardView
{
partial class FormReportShipDetails
{
/// <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()
{
ButtonSaveToExcel = new Button();
dataGridView = new DataGridView();
ShipColumn = new DataGridViewTextBoxColumn();
DetailColumn = new DataGridViewTextBoxColumn();
CountColumn = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// ButtonSaveToExcel
//
ButtonSaveToExcel.Location = new Point(12, 12);
ButtonSaveToExcel.Name = "ButtonSaveToExcel";
ButtonSaveToExcel.Size = new Size(211, 32);
ButtonSaveToExcel.TabIndex = 0;
ButtonSaveToExcel.Text = "Сохранить в excel";
ButtonSaveToExcel.UseVisualStyleBackColor = true;
ButtonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ShipColumn, DetailColumn, CountColumn });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 62);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(597, 480);
dataGridView.TabIndex = 1;
//
// ShipColumn
//
ShipColumn.HeaderText = "Корабль";
ShipColumn.MinimumWidth = 6;
ShipColumn.Name = "ShipColumn";
//
// DetailColumn
//
DetailColumn.HeaderText = "Деталь";
DetailColumn.MinimumWidth = 6;
DetailColumn.Name = "DetailColumn";
//
// CountColumn
//
CountColumn.HeaderText = "Количество";
CountColumn.MinimumWidth = 6;
CountColumn.Name = "CountColumn";
//
// FormReportShipDetails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(597, 542);
Controls.Add(dataGridView);
Controls.Add(ButtonSaveToExcel);
Name = "FormReportShipDetails";
Text = "Корабли по деталям";
Load += FormReportProductComponents_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button ButtonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ShipColumn;
private DataGridViewTextBoxColumn DetailColumn;
private DataGridViewTextBoxColumn CountColumn;
}
}

View File

@ -0,0 +1,70 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
namespace ShipyardView
{
public partial class FormReportShipDetails : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShipDetails(ILogger<FormReportShipDetails> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportProductComponents_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShipDetail();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShipName, "", "" });
foreach (var listElem in elem.Details)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка кораблей по деталям");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка кораблей по деталям");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveProductComponentToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка кораблей по деталям");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка кораблей по деталям");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

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

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