Compare commits

..

18 Commits

Author SHA1 Message Date
397bc186f1 Изменил(а) на 'SoftwareInstallation/SoftwareInstallation/FormPackages.Designer.cs' 2023-05-25 20:01:36 +04:00
951c9e0612 fix 2023-05-22 21:26:28 +04:00
Katerina881
3a28b05517 lab4 passed 2023-04-21 11:02:16 +04:00
Katerina881
73db42e588 FormPackage fix 2023-04-21 09:46:00 +04:00
acf2235f76 package software fixed 2023-04-21 01:38:04 +04:00
fa05cb1b6d some errors fixed 2023-04-21 00:09:37 +04:00
68f3837e64 almost done 2023-04-20 21:50:17 +04:00
8e66853e8b lab 4 reports logic + document logic 2023-04-19 23:01:19 +04:00
4326593e9c lab3 done 2023-04-19 18:49:18 +04:00
5e59750290 Brunch fix (3) 2023-04-16 00:41:06 +04:00
e7dec86f9c Bruch fix 2023-04-16 00:31:47 +04:00
326ea686fa lab3 needs patching 2023-04-09 14:42:51 +04:00
f9c2fb9701 Исправление ошибок 2023-03-26 22:13:55 +04:00
baed74da66 lab 2 done 2023-03-26 15:08:08 +04:00
accc28176f pre final 2023-03-12 20:20:27 +04:00
3de75dc783 models done 2023-03-12 18:00:46 +04:00
40fb3142eb lab1 final 2023-03-11 22:58:09 +04:00
90f8af59f4 1 lab 2023-03-11 22:53:15 +04:00
109 changed files with 7826 additions and 0 deletions

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="2.19.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.14" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AbstractSoftwareInstallationContracts\AbstractSoftwareInstallationContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,118 @@
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using AbstractSoftwareInstallationDataModels;
namespace AbstractSoftwareInstallationBusinessLogic.BusinessLogic
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage OrderStorage)
{
_logger = logger;
_orderStorage = OrderStorage;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.PackageId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у суши", nameof(model.PackageId));
}
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}. PackageId: { PackageId}", model.Id, model.Sum, model.PackageId);
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Orderid:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Order status is incorrect");
return false;
}
model.Status = OrderStatus.Принят;
model.DateCreate = DateTime.Now;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Failed to insert order into a storage");
return false;
}
return true;
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus _newStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(model));
}
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,110 @@
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace AbstractSoftwareInstallationBusinessLogic.BusinessLogic
{
public class PackageLogic : IPackageLogic
{
private readonly ILogger _logger;
private readonly IPackageStorage _packageStorage;
public PackageLogic(ILogger<PackageLogic> logger, IPackageStorage PackageStorage)
{
_logger = logger;
_packageStorage = PackageStorage;
}
public List<PackageViewModel>? ReadList(PackageSearchModel? model)
{
_logger.LogInformation("ReadList. PackageName:{PackageName}.Id:{ Id}", model?.PackageName, model?.Id);
var list = model == null ? _packageStorage.GetFullList() : _packageStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public PackageViewModel? ReadElement(PackageSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. PackageName:{PackageName}.Id:{ Id}", model.PackageName, model.Id);
var element = _packageStorage.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(PackageBindingModel model)
{
CheckModel(model);
if (_packageStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(PackageBindingModel model)
{
CheckModel(model);
if (_packageStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(PackageBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_packageStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(PackageBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.PackageName))
{
throw new ArgumentNullException("Нет названия пакета",
nameof(model.PackageName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена пакета должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Package. PackageName:{PackageName}.Price:{Price}. Id: {Id}", model.PackageName, model.Price, model.Id);
var element = _packageStorage.GetElement(new PackageSearchModel
{
PackageName = model.PackageName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Пакет с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,107 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.BusinessLogic
{
public class ReportLogic : IReportLogic
{
private readonly ISoftwareStorage _softwareStorage;
private readonly IPackageStorage _packageStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IPackageStorage packageStorage, ISoftwareStorage softwareStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_packageStorage = packageStorage;
_softwareStorage = softwareStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
/// Получение списка компонент с указанием, в каких изделиях используются
public List<ReportPackageSoftwareViewModel> GetPackageSoftware()
{
var packages = _packageStorage.GetFullList();
var list = new List<ReportPackageSoftwareViewModel>();
foreach (var doc in packages)
{
var record = new ReportPackageSoftwareViewModel
{
PackageName = doc.PackageName,
Softwares = new List<(string Blank, int Count)>(),
TotalCount = 0
};
foreach (var software in doc.PackageSoftware.Values)
{
record.Softwares.Add((software.Item1.SoftwareName, software.Item2));
record.TotalCount += software.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,
PackageName = x.PackageName,
Sum = x.Sum,
Status = x.Status.ToString(),
})
.ToList();
}
/// Сохранение компонент в файл-Word
public void SavePackagesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список документов",
Packages = _packageStorage.GetFullList()
});
}
/// Сохранение компонент с указаеним продуктов в файл-Excel
public void SavePackageSoftwareToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список документов",
PackageSoftware = GetPackageSoftware()
});
}
/// Сохранение заказов в файл-Pdf
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 AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace AbstractSoftwareInstallationBusinessLogic
{
public class SoftwareLogic : ISoftwareLogic
{
private readonly ILogger _logger;
private readonly ISoftwareStorage _softwareStorage;
public SoftwareLogic(ILogger<SoftwareLogic> logger, ISoftwareStorage SoftwareStorage)
{
_logger = logger;
_softwareStorage = SoftwareStorage;
}
public List<SoftwareViewModel>? ReadList(SoftwareSearchModel? model)
{
_logger.LogInformation("ReadList. SoftwareName:{SoftwareName}.Id:{ Id}", model?.SoftwareName, model?.Id);
var list = model == null ? _softwareStorage.GetFullList() : _softwareStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public SoftwareViewModel? ReadElement(SoftwareSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. SoftwareName:{SoftwareName}.Id:{ Id}", model.SoftwareName, model.Id);
var element = _softwareStorage.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(SoftwareBindingModel model)
{
CheckModel(model);
if (_softwareStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(SoftwareBindingModel model)
{
CheckModel(model);
if (_softwareStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(SoftwareBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_softwareStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(SoftwareBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.SoftwareName))
{
throw new ArgumentNullException("Нет названия ПО", nameof(model.SoftwareName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена ПО должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Software. SoftwareName:{SoftwareName}.Cost:{ Cost}. Id: { Id}", model.SoftwareName, model.Cost, model.Id);
var element = _softwareStorage.GetElement(new SoftwareSearchModel
{
SoftwareName = model.SoftwareName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("ПО с таким названием уже есть");
}
}
}}

View File

@ -0,0 +1,85 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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.PackageSoftware)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.PackageName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Software, Count) in pc.Softwares)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Software,
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);
}
/// Создание excel-файла
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,63 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с{ info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "4cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Сумма", "Статус" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.PackageName, order.Sum.ToString(), order.Status },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
SavePdf(info);
}
/// Создание pdf-файла
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,49 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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 package in info.Packages)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{(package.PackageName + " - ", new WordTextProperties { Size = "24", Bold = true}),
(package.Price.ToString(), new WordTextProperties { Size = "24", })},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
/// Создание doc-файла
protected abstract void CreateWord(WordInfo info);
/// Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
/// Сохранение файла
protected abstract void SaveWord(WordInfo info);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,18 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,16 @@
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportPackageSoftwareViewModel> PackageSoftware { get; set; } = new ();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,18 @@
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,19 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,16 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,17 @@
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<PackageViewModel> Packages { get; set; } = new();
}
}

View File

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

View File

@ -0,0 +1,19 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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,329 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// Настройка стилей для файла
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None }); var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style = BorderStyleValues.Thin
};
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// Получение номера стиля из типа
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.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.Close();
}
}
}

View File

@ -0,0 +1,96 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using MigraDoc.DocumentObjectModel.Tables;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
namespace AbstractSoftwareInstallationBusinessLogic.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,118 @@
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperEnums;
using AbstractSoftwareInstallationBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationBusinessLogic.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.Close();
}
}
}

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="..\AbstractSoftwareInstallationDataModels\AbstractSoftwareInstallationDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,21 @@
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int PackageId { 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,17 @@
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.BindingModels
{
public class PackageBindingModel : IPackageModel
{
public int Id { get; set; }
public string PackageName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (ISoftwareModel, int)> PackageSoftware{get;set;} = new();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.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,11 @@
using AbstractSoftwareInstallationDataModels.Models;
namespace AbstractSoftwareInstallationContracts.BindingModels
{
public class SoftwareBindingModel : ISoftwareModel
{
public int Id { get; set; }
public string SoftwareName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
namespace AbstractSoftwareInstallationContracts.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
namespace AbstractSoftwareInstallationContracts.BusinessLogicsContracts
{
public interface IPackageLogic
{
List<PackageViewModel>? ReadList(PackageSearchModel? model);
PackageViewModel? ReadElement(PackageSearchModel model);
bool Create(PackageBindingModel model);
bool Update(PackageBindingModel model);
bool Delete(PackageBindingModel model);
}
}

View File

@ -0,0 +1,41 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
/// <summary>
/// Получение списка компонент с указанием, в каких изделиях используются
/// </summary>
/// <returns></returns>
List<ReportPackageSoftwareViewModel> GetPackageSoftware();
/// <summary>
/// Получение списка заказов за определенный период
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
/// <summary>
/// Сохранение компонент в файл-Word
/// </summary>
/// <param name="model"></param>
void SavePackagesToWordFile(ReportBindingModel model);
/// <summary>
/// Сохранение компонент с указаеним продуктов в файл-Excel
/// </summary>
/// <param name="model"></param>
void SavePackageSoftwareToExcelFile(ReportBindingModel model);
/// <summary>
/// Сохранение заказов в файл-Pdf
/// </summary>
/// <param name="model"></param>
void SaveOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.BusinessLogicsContracts
{
public interface ISoftwareLogic
{
List<SoftwareViewModel>? ReadList(SoftwareSearchModel? model);
SoftwareViewModel? ReadElement(SoftwareSearchModel model);
bool Create(SoftwareBindingModel model);
bool Update(SoftwareBindingModel model);
bool Delete(SoftwareBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.SearchModels
{
public class PackageSearchModel
{
public int? Id { get; set; }
public string? PackageName { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.SearchModels
{
public class SoftwareSearchModel
{
public int? Id { get; set; }
public string? SoftwareName { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
namespace AbstractSoftwareInstallationContracts.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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
namespace AbstractSoftwareInstallationContracts.StoragesContracts
{
public interface IPackageStorage
{
List<PackageViewModel> GetFullList();
List<PackageViewModel> GetFilteredList(PackageSearchModel model);
PackageViewModel? GetElement(PackageSearchModel model);
PackageViewModel? Insert(PackageBindingModel model);
PackageViewModel? Update(PackageBindingModel model);
PackageViewModel? Delete(PackageBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.ViewModels;
namespace AbstractSoftwareInstallationContracts.StoragesContracts
{
public interface ISoftwareStorage
{
List<SoftwareViewModel> GetFullList();
List<SoftwareViewModel> GetFilteredList(SoftwareSearchModel model);
SoftwareViewModel? GetElement(SoftwareSearchModel model);
SoftwareViewModel? Insert(SoftwareBindingModel model);
SoftwareViewModel? Update(SoftwareBindingModel model);
SoftwareViewModel? Delete(SoftwareBindingModel model);
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.ComponentModel;
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер заказа")]
public int Id { get; set; }
public int PackageId { get; set; }
[DisplayName("Пакет")]
public string PackageName { 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,25 @@
using AbstractSoftwareInstallationDataModels.Models;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.ViewModels
{
public class PackageViewModel : IPackageModel
{
public int Id { get; set; }
[DisplayName("Имя пакета")]
public string PackageName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (ISoftwareModel, int)> PackageSoftware
{
get;
set;
} = new();
}
}

View File

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

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.ViewModels
{
public class ReportPackageSoftwareViewModel
{
public string PackageName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Software, int Count)> Softwares { get; set; } = new();
}
}

View File

@ -0,0 +1,19 @@
using AbstractSoftwareInstallationDataModels.Models;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationContracts.ViewModels
{
public class SoftwareViewModel : ISoftwareModel
{
public int Id { get; set; }
[DisplayName("Название")]
public string SoftwareName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

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,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDataModels.Models
{
public interface IOrderModel : IId
{
int PackageId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDataModels.Models
{
public interface IPackageModel : IId
{
string PackageName { get; }
double Price { get; }
Dictionary<int, (ISoftwareModel, int)> PackageSoftware { get; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDataModels.Models
{
public interface ISoftwareModel : IId
{
string SoftwareName { get; }
double Cost { get; }
}
}

View File

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

View File

@ -0,0 +1,28 @@
using AbstractPackageInstallationDatabaseImplement.Models;
using AbstractSoftwareInstallationDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement
{
public class AbstractSoftwareInstallationDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=IS-429-00\SQLEXPRESS;Initial Catalog=SogtwareInstallation;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Software> Softwares { set; get; }
public virtual DbSet<Package> Packages { set; get; }
public virtual DbSet<PackageSoftware> PackageSoftwares { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}
}

View File

@ -0,0 +1,24 @@
<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.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AbstractSoftwareInstallationContracts\AbstractSoftwareInstallationContracts.csproj" />
<ProjectReference Include="..\AbstractSoftwareInstallationDataModels\AbstractSoftwareInstallationDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,89 @@
using AbstractPackageInstallationDatabaseImplement.Models;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new AbstractSoftwareInstallationDatabase();
return context.Orders.Include(x => x.Package).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
return context.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Include(x => x.Package)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new AbstractSoftwareInstallationDatabase();
return context.Orders
.Include(x => x.Package)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new AbstractSoftwareInstallationDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders.Include(x => x.Package).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
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.Package).FirstOrDefault(x => x.Id == order.Id)?.GetViewModel;
}
}
}

View File

@ -0,0 +1,113 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Implements
{
public class PackageStorage : IPackageStorage
{
public List<PackageViewModel> GetFullList()
{
using var context = new AbstractSoftwareInstallationDatabase();
return context.Packages
.Include(x => x.Softwares)
.ThenInclude(x => x.Software)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<PackageViewModel> GetFilteredList(PackageSearchModel model)
{
if (string.IsNullOrEmpty(model.PackageName))
{
return new();
}
using var context = new AbstractSoftwareInstallationDatabase();
return context.Packages
.Include(x => x.Softwares)
.ThenInclude(x => x.Software)
.Where(x => x.PackageName.Contains(model.PackageName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public PackageViewModel? GetElement(PackageSearchModel model)
{
if (string.IsNullOrEmpty(model.PackageName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new AbstractSoftwareInstallationDatabase();
return context.Packages
.Include(x => x.Softwares)
.ThenInclude(x => x.Software)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PackageName)
&& x.PackageName == model.PackageName)
|| (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public PackageViewModel? Insert(PackageBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
var newPackage = Package.Create(context, model);
if (newPackage == null)
{
return null;
}
context.Packages.Add(newPackage);
context.SaveChanges();
return newPackage.GetViewModel;
}
public PackageViewModel? Update(PackageBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var Package = context.Packages.FirstOrDefault(rec => rec.Id == model.Id);
if (Package == null)
{
return null;
}
Package.Update(model);
context.SaveChanges();
Package.UpdateSoftwares(context, model);
transaction.Commit();
return Package.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public PackageViewModel? Delete(PackageBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
var element = context.Packages
.Include(x => x.Softwares)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Packages.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,90 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Implements
{
public class SoftwareStorage : ISoftwareStorage
{
public List<SoftwareViewModel> GetFullList()
{
using var context = new AbstractSoftwareInstallationDatabase();
return context.Softwares
.Select(x => x.GetViewModel)
.ToList();
}
public List<SoftwareViewModel> GetFilteredList(SoftwareSearchModel model)
{
if (string.IsNullOrEmpty(model.SoftwareName))
{
return new();
}
using var context = new AbstractSoftwareInstallationDatabase();
return context.Softwares
.Where(x => x.SoftwareName.Contains(model.SoftwareName))
.Select(x => x.GetViewModel)
.ToList();
}
public SoftwareViewModel? GetElement(SoftwareSearchModel model)
{
if (string.IsNullOrEmpty(model.SoftwareName) && !model.Id.HasValue)
{
return null;
}
using var context = new AbstractSoftwareInstallationDatabase();
return context.Softwares
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SoftwareName)
&& x.SoftwareName == model.SoftwareName)
|| (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public SoftwareViewModel? Insert(SoftwareBindingModel model)
{
var newSoftware = Software.Create(model);
if (newSoftware == null)
{
return null;
}
using var context = new AbstractSoftwareInstallationDatabase();
context.Softwares.Add(newSoftware);
context.SaveChanges();
return newSoftware.GetViewModel;
}
public SoftwareViewModel? Update(SoftwareBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
var Software = context.Softwares.FirstOrDefault(x => x.Id == model.Id);
if (Software == null)
{
return null;
}
Software.Update(model);
context.SaveChanges();
return Software.GetViewModel;
}
public SoftwareViewModel? Delete(SoftwareBindingModel model)
{
using var context = new AbstractSoftwareInstallationDatabase();
var element = context.Softwares.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Softwares.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,171 @@
// <auto-generated />
using System;
using AbstractSoftwareInstallationDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AbstractSoftwareInstallationDatabaseImplement.Migrations
{
[DbContext(typeof(AbstractSoftwareInstallationDatabase))]
[Migration("20230419141439_Init")]
partial class Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("AbstractPackageInstallationDatabaseImplement.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>("PackageId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("PackageId");
b.ToTable("Orders");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Package", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PackageName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Packages");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.PackageSoftware", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("PackageId")
.HasColumnType("int");
b.Property<int>("SoftwareId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PackageId");
b.HasIndex("SoftwareId");
b.ToTable("PackageSoftwares");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Software", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("SoftwareName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Softwares");
});
modelBuilder.Entity("AbstractPackageInstallationDatabaseImplement.Models.Order", b =>
{
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Package", "Package")
.WithMany("Orders")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.PackageSoftware", b =>
{
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Package", "Package")
.WithMany("Softwares")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Software", "Software")
.WithMany("PackageSoftwares")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
b.Navigation("Software");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Package", b =>
{
b.Navigation("Orders");
b.Navigation("Softwares");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Software", b =>
{
b.Navigation("PackageSoftwares");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,125 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AbstractSoftwareInstallationDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Packages",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PackageName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Packages", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Softwares",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SoftwareName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Softwares", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PackageId = 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_Packages_PackageId",
column: x => x.PackageId,
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "PackageSoftwares",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PackageId = table.Column<int>(type: "int", nullable: false),
SoftwareId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PackageSoftwares", x => x.Id);
table.ForeignKey(
name: "FK_PackageSoftwares_Packages_PackageId",
column: x => x.PackageId,
principalTable: "Packages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PackageSoftwares_Softwares_SoftwareId",
column: x => x.SoftwareId,
principalTable: "Softwares",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_PackageId",
table: "Orders",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_PackageSoftwares_PackageId",
table: "PackageSoftwares",
column: "PackageId");
migrationBuilder.CreateIndex(
name: "IX_PackageSoftwares_SoftwareId",
table: "PackageSoftwares",
column: "SoftwareId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "PackageSoftwares");
migrationBuilder.DropTable(
name: "Packages");
migrationBuilder.DropTable(
name: "Softwares");
}
}
}

View File

@ -0,0 +1,168 @@
// <auto-generated />
using System;
using AbstractSoftwareInstallationDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AbstractSoftwareInstallationDatabaseImplement.Migrations
{
[DbContext(typeof(AbstractSoftwareInstallationDatabase))]
partial class AbstractSoftwareInstallationDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("AbstractPackageInstallationDatabaseImplement.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>("PackageId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("PackageId");
b.ToTable("Orders");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Package", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PackageName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Packages");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.PackageSoftware", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("PackageId")
.HasColumnType("int");
b.Property<int>("SoftwareId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PackageId");
b.HasIndex("SoftwareId");
b.ToTable("PackageSoftwares");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Software", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("SoftwareName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Softwares");
});
modelBuilder.Entity("AbstractPackageInstallationDatabaseImplement.Models.Order", b =>
{
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Package", "Package")
.WithMany("Orders")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.PackageSoftware", b =>
{
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Package", "Package")
.WithMany("Softwares")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractSoftwareInstallationDatabaseImplement.Models.Software", "Software")
.WithMany("PackageSoftwares")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
b.Navigation("Software");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Package", b =>
{
b.Navigation("Orders");
b.Navigation("Softwares");
});
modelBuilder.Entity("AbstractSoftwareInstallationDatabaseImplement.Models.Software", b =>
{
b.Navigation("PackageSoftwares");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,73 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDatabaseImplement;
using AbstractSoftwareInstallationDatabaseImplement.Models;
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractPackageInstallationDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public int PackageId { get; private set; }
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public virtual Package Package { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order
{
PackageId = model.PackageId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
PackageId = PackageId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
PackageName = Package.PackageName
};
}
}

View File

@ -0,0 +1,107 @@
using AbstractPackageInstallationDatabaseImplement.Models;
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDatabaseImplement.Models;
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Models
{
public class Package : IPackageModel
{
public int Id { get; private set; }
[Required]
public string PackageName { get; private set; } = string.Empty;
[Required]
public double Price { get; private set; }
private Dictionary<int, (ISoftwareModel, int)>? _packageSoftwares = null;
[NotMapped]
public Dictionary<int, (ISoftwareModel, int)> PackageSoftware
{
get
{
if (_packageSoftwares == null)
{
_packageSoftwares = Softwares.ToDictionary(recPC => recPC.SoftwareId, recPC => (recPC.Software as ISoftwareModel, recPC.Count));
}
return _packageSoftwares;
}
}
[ForeignKey("PackageId")]
public virtual List<PackageSoftware> Softwares { get; set; } = new();
[ForeignKey("PackageId")]
public virtual List<Order> Orders { get; set; } = new();
public static Package? Create(AbstractSoftwareInstallationDatabase context, PackageBindingModel model)
{
var Softwares = context.Softwares;
return new Package()
{
Id = model.Id,
PackageName = model.PackageName,
Price = model.Price,
Softwares = model.PackageSoftware.Select(x => new PackageSoftware
{
Software = context.Softwares.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(PackageBindingModel model)
{
PackageName = model.PackageName;
Price = model.Price;
}
public PackageViewModel GetViewModel => new()
{
Id = Id,
PackageName = PackageName,
Price = Price,
PackageSoftware = PackageSoftware
};
public void UpdateSoftwares(AbstractSoftwareInstallationDatabase context, PackageBindingModel model)
{
var packageSoftwares = context.PackageSoftwares
.Where(rec => rec.PackageId == model.Id).ToList();
if (packageSoftwares != null && packageSoftwares.Count > 0)
{ // удалили те, которых нет в модели
context.PackageSoftwares.RemoveRange(packageSoftwares.Where(rec => !model.PackageSoftware.ContainsKey(rec.SoftwareId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateSoftware in packageSoftwares)
{
updateSoftware.Count = model.PackageSoftware[updateSoftware.SoftwareId].Item2;
model.PackageSoftware.Remove(updateSoftware.SoftwareId);
}
context.SaveChanges();
}
var package = context.Packages.First(x => x.Id == Id);
foreach (var pc in model.PackageSoftware)
{
context.PackageSoftwares.Add(new PackageSoftware
{
Package = package,
Software = context.Softwares.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_packageSoftwares = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Models
{
public class PackageSoftware
{
public int Id { get; set; }
[Required]
public int PackageId { get; set; }
[Required]
public int SoftwareId { get; set; }
[Required]
public int Count { get; set; }
public virtual Software Software { get; set; } = new();
public virtual Package Package { get; set; } = new();
}
}

View File

@ -0,0 +1,53 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationDatabaseImplement.Models
{
public class Software : ISoftwareModel
{
public int Id { get; private set; }
[Required]
public string SoftwareName { get; private set; } = String.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("SoftwareId")]
public virtual List<PackageSoftware> PackageSoftwares { get; set; } = new();
public static Software? Create(SoftwareBindingModel? model)
{
if (model == null)
{
return null;
}
return new Software()
{
Id = model.Id,
SoftwareName = model.SoftwareName,
Cost = model.Cost
};
}
public void Update(SoftwareBindingModel? model)
{
if (model == null)
{
return;
}
SoftwareName = model.SoftwareName;
Cost = model.Cost;
}
public SoftwareViewModel GetViewModel => new()
{
Id = Id,
SoftwareName = SoftwareName,
Cost = Cost
};
}
}

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="..\AbstractSoftwareInstallationContracts\AbstractSoftwareInstallationContracts.csproj" />
<ProjectReference Include="..\AbstractSoftwareInstallationDataModels\AbstractSoftwareInstallationDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,50 @@
using AbstractSoftwareInstallationFileImplement.Models;
using System.Xml.Linq;
namespace AbstractSoftwareInstallationFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string SoftwareFileName = "Software.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string PackageFileName = "Package.xml";
public List<Software> Softwares { get; private set; }
public List<Order> Orders { get; private set; }
public List<Package> Packages { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveSoftwares() => SaveData(Softwares, SoftwareFileName, "Softwares", x => x.GetXElement);
public void SavePackages() => SaveData(Packages, PackageFileName, "Packages", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
private DataFileSingleton()
{
Softwares = LoadData(SoftwareFileName, "Software", x => Software.Create(x)!)!;
Packages = LoadData(PackageFileName, "Package", x => Package.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,91 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationFileImplement.Models;
namespace AbstractSoftwareInstallationFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return GetViewModel(source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)));
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders
.Where(x => x.Id == model.Id)
.Select(x => GetViewModel(x))
.ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
source.Orders.Remove(order);
source.SaveOrders();
return GetViewModel(order);
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var package = source.Packages.FirstOrDefault(x => x.Id == order.PackageId);
if (package != null)
{
viewModel.PackageName = package.PackageName;
}
return viewModel;
}
}
}

View File

@ -0,0 +1,89 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationFileImplement.Implements
{
public class PackageStorage : IPackageStorage
{
private readonly DataFileSingleton source;
public PackageStorage()
{
source = DataFileSingleton.GetInstance();
}
public PackageViewModel? GetElement(PackageSearchModel model)
{
if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue)
{
return null;
}
return source.Packages
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.PackageName)
&& x.PackageName == model.PackageName)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<PackageViewModel> GetFilteredList(PackageSearchModel model)
{
if (string.IsNullOrEmpty(model.PackageName))
{
return new();
}
return source.Packages
.Where(x => x.PackageName.Contains(model.PackageName))
.Select(x => x.GetViewModel)
.ToList();
}
public List<PackageViewModel> GetFullList()
{
return source.Packages.Select(x => x.GetViewModel).ToList();
}
public PackageViewModel? Insert(PackageBindingModel model)
{
model.Id = source.Packages.Count > 0 ? source.Packages.Max(x => x.Id) + 1 : 1;
var newPackage = Package.Create(model);
if (newPackage == null)
{
return null;
}
source.Packages.Add(newPackage);
source.SavePackages();
return newPackage.GetViewModel;
}
public PackageViewModel? Update(PackageBindingModel model)
{
var Package = source.Packages.FirstOrDefault(x => x.Id == model.Id);
if (Package == null)
{
return null;
}
Package.Update(model);
source.SavePackages();
return Package.GetViewModel;
}
public PackageViewModel? Delete(PackageBindingModel model)
{
var Package = source.Packages.FirstOrDefault(x => x.Id == model.Id);
if (Package == null)
{
return null;
}
source.Packages.Remove(Package);
source.SavePackages();
return Package.GetViewModel;
}
}
}

View File

@ -0,0 +1,77 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationFileImplement.Models;
namespace AbstractSoftwareInstallationFileImplement.Implements
{
public class SoftwareStorage : ISoftwareStorage
{
private readonly DataFileSingleton _source;
public SoftwareStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<SoftwareViewModel> GetFullList()
{
return _source.Softwares.Select(x => x.GetViewModel).ToList();
}
public List<SoftwareViewModel> GetFilteredList(SoftwareSearchModel
model)
{
if (string.IsNullOrEmpty(model.SoftwareName))
{
return new();
}
return _source.Softwares.Where(x => x.SoftwareName.Contains(model.SoftwareName))
.Select(x => x.GetViewModel)
.ToList();
}
public SoftwareViewModel? GetElement(SoftwareSearchModel model)
{
if (string.IsNullOrEmpty(model.SoftwareName) && !model.Id.HasValue)
{
return null;
}
return _source.Softwares.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.SoftwareName)
&& x.SoftwareName == model.SoftwareName)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public SoftwareViewModel? Insert(SoftwareBindingModel model)
{
model.Id = _source.Softwares.Count > 0 ? _source.Softwares.Max(x => x.Id) + 1 : 1;
var newSoftware = Software.Create(model);
if (newSoftware == null)
{
return null;
}
_source.Softwares.Add(newSoftware);
_source.SaveSoftwares();
return newSoftware.GetViewModel;
}
public SoftwareViewModel? Update(SoftwareBindingModel model)
{
var software = _source.Softwares.FirstOrDefault(x => x.Id == model.Id);
if (software == null)
{
return null;
}
software.Update(model);
_source.SaveSoftwares();
return software.GetViewModel;
}
public SoftwareViewModel? Delete(SoftwareBindingModel model)
{
var software = _source.Softwares.FirstOrDefault(x => x.Id == model.Id);
if (software == null)
{
return null;
}
_source.Softwares.Remove(software);
_source.SaveSoftwares();
return software.GetViewModel;
}
}
}

View File

@ -0,0 +1,90 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AbstractSoftwareInstallationFileImplement.Models
{
internal class Order : IOrderModel
{
public int PackageId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null) return null;
return new Order
{
PackageId = model.PackageId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id,
};
}
public static Order? Create(XElement element)
{
if (element == null) return null;
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
PackageId = Convert.ToInt32(element.Element("PackageId")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
};
}
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
PackageId = PackageId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new(
"Order",
new XAttribute("Id", Id),
new XElement("PackageId", PackageId.ToString()),
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,107 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AbstractSoftwareInstallationFileImplement.Models
{
internal class Package : IPackageModel
{
public string PackageName { get; private set; } = string.Empty;
public double Price { get; private set; }
public int Id { get; private set; }
public Dictionary<int, int> Softwares { get; private set; } = new();
private Dictionary<int, (ISoftwareModel, int)>? _PackageSoftware = null;
public Dictionary<int, (ISoftwareModel, int)> PackageSoftware
{
get
{
if (_PackageSoftware == null)
{
var source = DataFileSingleton.GetInstance();
_PackageSoftware = Softwares.ToDictionary(
x => x.Key,
y => ((source.Softwares.FirstOrDefault(z => z.Id == y.Key) as ISoftwareModel)!, y.Value)
);
}
return _PackageSoftware;
}
}
public static Package? Create(PackageBindingModel? model)
{
if (model == null)
{
return null;
}
return new Package()
{
Id = model.Id,
PackageName = model.PackageName,
Price = model.Price,
Softwares = model.PackageSoftware.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Package? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Package()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
PackageName = element.Element("PackageName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Softwares = element.Element("PackageSoftware")!.Elements("PackageSoftware").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(PackageBindingModel? model)
{
if (model == null)
{
return;
}
PackageName = model.PackageName;
Price = model.Price;
Softwares = model.PackageSoftware.ToDictionary(x => x.Key, x => x.Value.Item2);
_PackageSoftware = null;
}
public PackageViewModel GetViewModel => new()
{
Id = Id,
PackageName = PackageName,
Price = Price,
PackageSoftware = PackageSoftware
};
public XElement GetXElement => new(
"Package",
new XAttribute("Id", Id),
new XElement("PackageName", PackageName),
new XElement("Price", Price.ToString()),
new XElement("PackageSoftware", Softwares.Select(x =>
new XElement("PackageSoftware",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -0,0 +1,64 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AbstractSoftwareInstallationFileImplement.Models
{
internal class Software : ISoftwareModel
{
public int Id { get; private set; }
public string SoftwareName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Software? Create(SoftwareBindingModel model)
{
if (model == null)
{
return null;
}
return new Software()
{
Id = model.Id,
SoftwareName = model.SoftwareName,
Cost = model.Cost
};
}
public static Software? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Software()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SoftwareName = element.Element("SoftwareName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(SoftwareBindingModel model)
{
if (model == null)
{
return;
}
SoftwareName = model.SoftwareName;
Cost = model.Cost;
}
public SoftwareViewModel GetViewModel => new()
{
Id = Id,
SoftwareName = SoftwareName,
Cost = Cost
};
public XElement GetXElement => new("Software",
new XAttribute("Id", Id),
new XElement("SoftwareName", SoftwareName),
new XElement("Cost", Cost.ToString()));
}
}

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="..\AbstractSoftwareInstallationContracts\AbstractSoftwareInstallationContracts.csproj" />
<ProjectReference Include="..\AbstractSoftwareInstallationDataModels\AbstractSoftwareInstallationDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,31 @@
using AbstractSoftwareInstallationListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Software> Softwares { get; set; }
public List<Order> Orders { get; set; }
public List<Package> Packages { get; set; }
private DataListSingleton()
{
Softwares = new List<Software>();
Orders = new List<Order>();
Packages = new List<Package>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,122 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationListImplement;
using AbstractSoftwareInstallationListImplement.Models;
namespace AbstractOrderInstallationListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
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 List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(GetViewModel(order));
}
}
return result;
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(GetViewModel(order));
}
return result;
}
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 package in _source.Packages)
{
if (package.Id == order.PackageId)
{
viewModel.PackageName = package.PackageName;
break;
}
}
return viewModel;
}
}
}

View File

@ -0,0 +1,109 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationListImplement;
using AbstractSoftwareInstallationListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractPackageInstallationListImplement.Implements
{
public class PackageStorage : IPackageStorage
{
private readonly DataListSingleton _source;
public PackageStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<PackageViewModel> GetFullList()
{
var result = new List<PackageViewModel>();
foreach (var package in _source.Packages)
{
result.Add(package.GetViewModel);
}
return result;
}
public List<PackageViewModel> GetFilteredList(PackageSearchModel
model)
{
var result = new List<PackageViewModel>();
if (string.IsNullOrEmpty(model.PackageName))
{
return result;
}
foreach (var package in _source.Packages)
{
if (package.PackageName.Contains(model.PackageName))
{
result.Add(package.GetViewModel);
}
}
return result;
}
public PackageViewModel? GetElement(PackageSearchModel model)
{
if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue)
{
return null;
}
foreach (var package in _source.Packages)
{
if ((!string.IsNullOrEmpty(model.PackageName) &&
package.PackageName == model.PackageName) ||
(model.Id.HasValue && package.Id == model.Id))
{
return package.GetViewModel;
}
}
return null;
}
public PackageViewModel? Insert(PackageBindingModel model)
{
model.Id = 1;
foreach (var package in _source.Packages)
{
if (model.Id <= package.Id)
{
model.Id = package.Id + 1;
}
}
var newPackage = Package.Create(model);
if (newPackage == null)
{
return null;
}
_source.Packages.Add(newPackage);
return newPackage.GetViewModel;
}
public PackageViewModel? Update(PackageBindingModel model)
{
foreach (var package in _source.Packages)
{
if (package.Id == model.Id)
{
package.Update(model);
return package.GetViewModel;
}
}
return null;
}
public PackageViewModel? Delete(PackageBindingModel model)
{
for (int i = 0; i < _source.Packages.Count; ++i)
{
if (_source.Packages[i].Id == model.Id)
{
var element = _source.Packages[i];
_source.Packages.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,105 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationContracts.StoragesContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationListImplement.Models;
namespace AbstractSoftwareInstallationListImplement.Implements
{
public class SoftwareStorage : ISoftwareStorage
{
private readonly DataListSingleton _source;
public SoftwareStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<SoftwareViewModel> GetFullList()
{
var result = new List<SoftwareViewModel>();
foreach (var component in _source.Softwares)
{
result.Add(component.GetViewModel);
}
return result;
}
public List<SoftwareViewModel> GetFilteredList(SoftwareSearchModel
model)
{
var result = new List<SoftwareViewModel>();
if (string.IsNullOrEmpty(model.SoftwareName))
{
return result;
}
foreach (var component in _source.Softwares)
{
if (component.SoftwareName.Contains(model.SoftwareName))
{
result.Add(component.GetViewModel);
}
}
return result;
}
public SoftwareViewModel? GetElement(SoftwareSearchModel model)
{
if (string.IsNullOrEmpty(model.SoftwareName) && !model.Id.HasValue)
{
return null;
}
foreach (var software in _source.Softwares)
{
if ((!string.IsNullOrEmpty(model.SoftwareName) &&
software.SoftwareName == model.SoftwareName) ||
(model.Id.HasValue && software.Id == model.Id))
{
return software.GetViewModel;
}
}
return null;
}
public SoftwareViewModel? Insert(SoftwareBindingModel model)
{
model.Id = 1;
foreach (var software in _source.Softwares)
{
if (model.Id <= software.Id)
{
model.Id = software.Id + 1;
}
}
var newSoftware = Software.Create(model);
if (newSoftware == null)
{
return null;
}
_source.Softwares.Add(newSoftware);
return newSoftware.GetViewModel;
}
public SoftwareViewModel? Update(SoftwareBindingModel model)
{
foreach (var component in _source.Softwares)
{
if (component.Id == model.Id)
{
component.Update(model);
return component.GetViewModel;
}
throw new ArgumentNullException("Новая цена", nameof(model.Cost));
}
return null;
}
public SoftwareViewModel? Delete(SoftwareBindingModel model)
{
for (int i = 0; i < _source.Softwares.Count; ++i)
{
if (_source.Softwares[i].Id == model.Id)
{
var element = _source.Softwares[i];
_source.Softwares.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,59 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels;
using AbstractSoftwareInstallationDataModels.Models;
namespace AbstractSoftwareInstallationListImplement.Models
{
public class Order : IOrderModel
{
public int PackageId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null) return null;
return new Order
{
PackageId = model.PackageId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id,
};
}
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
PackageId = PackageId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,50 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractSoftwareInstallationListImplement.Models
{
public class Package : IPackageModel
{
public string PackageName { get; private set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (ISoftwareModel, int)> PackageSoftware { get; private set; } = new Dictionary<int, (ISoftwareModel, int)>();
public int Id { get; private set; }
public static Package? Create(PackageBindingModel? model)
{
if (model == null) return null;
return new Package
{
Id = model.Id,
PackageName = model.PackageName,
Price = model.Price,
PackageSoftware = model.PackageSoftware
};
}
public void Update(PackageBindingModel? model)
{
if (model == null)
{
return;
}
PackageName = model.PackageName;
Price = model.Price;
PackageSoftware = model.PackageSoftware;
}
public PackageViewModel GetViewModel => new()
{
Id = Id,
PackageName = PackageName,
Price = Price,
PackageSoftware = PackageSoftware
};
}
}

View File

@ -0,0 +1,43 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
namespace AbstractSoftwareInstallationListImplement.Models
{
public class Software : ISoftwareModel
{
public string SoftwareName { get; private set; } = String.Empty;
public double Cost { get; set; }
public int Id { get; private set; }
public static Software? Create(SoftwareBindingModel? model)
{
if (model == null)
{
return null;
}
return new Software()
{
Id = model.Id,
SoftwareName = model.SoftwareName,
Cost = model.Cost
};
}
public void Update(SoftwareBindingModel? model)
{
if (model == null)
{
return;
}
SoftwareName = model.SoftwareName;
Cost = model.Cost;
}
public SoftwareViewModel GetViewModel => new()
{
Id = Id,
SoftwareName = SoftwareName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,61 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoftwareInstallationView", "SoftwareInstallation\SoftwareInstallationView.csproj", "{18A0C203-2758-444C-AF35-2635F88FDB35}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationDataModels", "AbstractSoftwareInstallationDataModels\AbstractSoftwareInstallationDataModels.csproj", "{A883A624-D446-4834-9C5F-6364F0E66314}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationContracts", "AbstractSoftwareInstallationContracts\AbstractSoftwareInstallationContracts.csproj", "{4DA94347-C949-462B-B361-18D297C65CC2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationBusinessLogic", "AbstractSoftwareInstallationBusinessLogic\AbstractSoftwareInstallationBusinessLogic.csproj", "{76E33F5D-6D55-4C28-B26B-9F33B10BA3EF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationListImplement", "AbstractSoftwareInstallationListImplement\AbstractSoftwareInstallationListImplement.csproj", "{31AD2872-9651-476A-9868-C4404FEEB0E4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationFileImplement", "AbstractSoftwareInstallationFileImplement\AbstractSoftwareInstallationFileImplement.csproj", "{BEE13C3F-1BB8-46B4-BC87-CFC367E52A77}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AbstractSoftwareInstallationDatabaseImplement", "AbstractSoftwareInstallationDatabaseImplement\AbstractSoftwareInstallationDatabaseImplement.csproj", "{7631EF04-BAD9-44D7-80C5-6017EDEA7E14}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{18A0C203-2758-444C-AF35-2635F88FDB35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{18A0C203-2758-444C-AF35-2635F88FDB35}.Debug|Any CPU.Build.0 = Debug|Any CPU
{18A0C203-2758-444C-AF35-2635F88FDB35}.Release|Any CPU.ActiveCfg = Release|Any CPU
{18A0C203-2758-444C-AF35-2635F88FDB35}.Release|Any CPU.Build.0 = Release|Any CPU
{A883A624-D446-4834-9C5F-6364F0E66314}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A883A624-D446-4834-9C5F-6364F0E66314}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A883A624-D446-4834-9C5F-6364F0E66314}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A883A624-D446-4834-9C5F-6364F0E66314}.Release|Any CPU.Build.0 = Release|Any CPU
{4DA94347-C949-462B-B361-18D297C65CC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4DA94347-C949-462B-B361-18D297C65CC2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4DA94347-C949-462B-B361-18D297C65CC2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4DA94347-C949-462B-B361-18D297C65CC2}.Release|Any CPU.Build.0 = Release|Any CPU
{76E33F5D-6D55-4C28-B26B-9F33B10BA3EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76E33F5D-6D55-4C28-B26B-9F33B10BA3EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76E33F5D-6D55-4C28-B26B-9F33B10BA3EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76E33F5D-6D55-4C28-B26B-9F33B10BA3EF}.Release|Any CPU.Build.0 = Release|Any CPU
{31AD2872-9651-476A-9868-C4404FEEB0E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{31AD2872-9651-476A-9868-C4404FEEB0E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{31AD2872-9651-476A-9868-C4404FEEB0E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{31AD2872-9651-476A-9868-C4404FEEB0E4}.Release|Any CPU.Build.0 = Release|Any CPU
{BEE13C3F-1BB8-46B4-BC87-CFC367E52A77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BEE13C3F-1BB8-46B4-BC87-CFC367E52A77}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BEE13C3F-1BB8-46B4-BC87-CFC367E52A77}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BEE13C3F-1BB8-46B4-BC87-CFC367E52A77}.Release|Any CPU.Build.0 = Release|Any CPU
{7631EF04-BAD9-44D7-80C5-6017EDEA7E14}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7631EF04-BAD9-44D7-80C5-6017EDEA7E14}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7631EF04-BAD9-44D7-80C5-6017EDEA7E14}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7631EF04-BAD9-44D7-80C5-6017EDEA7E14}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {65E51AEC-89CD-4164-8821-934839107D27}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,145 @@
namespace SoftwareInstallationView
{
partial class FormCreateOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.comboBoxPackage = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.textBoxSum = new System.Windows.Forms.TextBox();
this.labelPackage = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.labelSum = new System.Windows.Forms.Label();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// comboBoxPackage
//
this.comboBoxPackage.BackColor = System.Drawing.SystemColors.Window;
this.comboBoxPackage.FormattingEnabled = true;
this.comboBoxPackage.Location = new System.Drawing.Point(110, 24);
this.comboBoxPackage.Name = "comboBoxPackage";
this.comboBoxPackage.Size = new System.Drawing.Size(310, 23);
this.comboBoxPackage.TabIndex = 0;
this.comboBoxPackage.SelectedIndexChanged += new System.EventHandler(this.ComboBoxProduct_SelectedIndexChanged);
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(110, 62);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(310, 23);
this.textBoxCount.TabIndex = 1;
this.textBoxCount.TextChanged += new System.EventHandler(this.TextBoxCount_TextChanged);
//
// textBoxSum
//
this.textBoxSum.Location = new System.Drawing.Point(110, 101);
this.textBoxSum.Name = "textBoxSum";
this.textBoxSum.Size = new System.Drawing.Size(310, 23);
this.textBoxSum.TabIndex = 2;
//
// labelPackage
//
this.labelPackage.AutoSize = true;
this.labelPackage.Location = new System.Drawing.Point(29, 27);
this.labelPackage.Name = "labelPackage";
this.labelPackage.Size = new System.Drawing.Size(42, 15);
this.labelPackage.TabIndex = 3;
this.labelPackage.Text = "Пакет:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(29, 65);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 4;
this.labelCount.Text = "Количество:";
//
// labelSum
//
this.labelSum.AutoSize = true;
this.labelSum.Location = new System.Drawing.Point(29, 104);
this.labelSum.Name = "labelSum";
this.labelSum.Size = new System.Drawing.Size(48, 15);
this.labelSum.TabIndex = 5;
this.labelSum.Text = "Сумма:";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(247, 132);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(75, 23);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(345, 132);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отменить";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormCreateOrder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(450, 167);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.labelSum);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelPackage);
this.Controls.Add(this.textBoxSum);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxPackage);
this.Name = "FormCreateOrder";
this.Text = "Заказ";
this.ResumeLayout(false);
this.PerformLayout();
this.Load += new System.EventHandler(this.FormCreateOrder_Load);
}
#endregion
private ComboBox comboBoxPackage;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Label labelPackage;
private Label labelCount;
private Label labelSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,128 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace SoftwareInstallationView
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IPackageLogic _logicP;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IPackageLogic logicP, IOrderLogic logicO)
{
InitializeSoftware();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка пакетов для заказа");
try
{
var list = _logicP.ReadList(null);
if (list != null)
{
comboBoxPackage.DisplayMember = "PackageName";
comboBoxPackage.ValueMember = "Id";
comboBoxPackage.DataSource = list;
comboBoxPackage.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки пакетов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
LoadData();
}
private void CalcSum()
{
if (comboBoxPackage.SelectedValue != null &&
!string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxPackage.SelectedValue);
var product = _logicP.ReadElement(new PackageSearchModel
{
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 ComboBoxProduct_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 (comboBoxPackage.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
PackageId = Convert.ToInt32(comboBoxPackage.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,60 @@
<root>
<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,217 @@
using SoftwareInstallation;
namespace SoftwareInstallationView
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button();
this.buttonTakeOrderInWork = new System.Windows.Forms.Button();
this.buttonOrderReady = new System.Windows.Forms.Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.guideToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reportsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.packageToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.storageToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.packagesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.packageSoftwaresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(1, 31);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(602, 230);
this.dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(628, 31);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(153, 23);
this.buttonCreateOrder.TabIndex = 2;
this.buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.UseVisualStyleBackColor = true;
this.buttonCreateOrder.Click += new System.EventHandler(this.buttonCreateOrder_Click);
//
// buttonTakeOrderInWork
//
this.buttonTakeOrderInWork.Location = new System.Drawing.Point(628, 75);
this.buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
this.buttonTakeOrderInWork.Size = new System.Drawing.Size(153, 23);
this.buttonTakeOrderInWork.TabIndex = 3;
this.buttonTakeOrderInWork.Text = "Отдать на выполнение";
this.buttonTakeOrderInWork.UseVisualStyleBackColor = true;
this.buttonTakeOrderInWork.Click += new System.EventHandler(this.buttonTakeOrderInWork_Click);
//
// buttonOrderReady
//
this.buttonOrderReady.Location = new System.Drawing.Point(628, 123);
this.buttonOrderReady.Name = "buttonOrderReady";
this.buttonOrderReady.Size = new System.Drawing.Size(153, 23);
this.buttonOrderReady.TabIndex = 4;
this.buttonOrderReady.Text = "Заказ готов";
this.buttonOrderReady.UseVisualStyleBackColor = true;
this.buttonOrderReady.Click += new System.EventHandler(this.buttonOrderReady_Click);
//
// buttonIssuedOrder
//
this.buttonIssuedOrder.Location = new System.Drawing.Point(628, 171);
this.buttonIssuedOrder.Name = "buttonIssuedOrder";
this.buttonIssuedOrder.Size = new System.Drawing.Size(153, 23);
this.buttonIssuedOrder.TabIndex = 5;
this.buttonIssuedOrder.Text = "Заказ выдан";
this.buttonIssuedOrder.UseVisualStyleBackColor = true;
this.buttonIssuedOrder.Click += new System.EventHandler(this.buttonIssuedOrder_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(628, 219);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(153, 23);
this.buttonRef.TabIndex = 6;
this.buttonRef.Text = "Обновить список";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.guideToolStripMenuItem, this.reportsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(803, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "Справочники";
//
// guideToolStripMenuItem
//
this.guideToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.packageToolStripMenuItem2,
this.storageToolStripMenuItem3});
this.guideToolStripMenuItem.Name = "guideToolStripMenuItem";
this.guideToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.guideToolStripMenuItem.Text = "Справочники";
//
// reportsToolStripMenuItem
//
this.reportsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.packagesToolStripMenuItem,
this.packageSoftwaresToolStripMenuItem,
this.ordersToolStripMenuItem});
this.reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.reportsToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.reportsToolStripMenuItem.Text = "Отчеты";
//
// packagesToolStripMenuItem
//
this.packagesToolStripMenuItem.Name = "packagesToolStripMenuItem";
this.packagesToolStripMenuItem.Size = new System.Drawing.Size(252, 26);
this.packagesToolStripMenuItem.Text = "Список пакетов";
this.packagesToolStripMenuItem.Click += new System.EventHandler(this.packagesToolStripMenuItem_Click);
//
// packageSoftwaresToolStripMenuItem
//
this.packageSoftwaresToolStripMenuItem.Name = "packageSoftwaresToolStripMenuItem";
this.packageSoftwaresToolStripMenuItem.Size = new System.Drawing.Size(252, 26);
this.packageSoftwaresToolStripMenuItem.Text = "ПО по пакетам";
this.packageSoftwaresToolStripMenuItem.Click += new System.EventHandler(this.packageSoftwaresToolStripMenuItem_Click);
//
// ordersToolStripMenuItem
//
this.ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
this.ordersToolStripMenuItem.Size = new System.Drawing.Size(252, 26);
this.ordersToolStripMenuItem.Text = "Список заказов";
this.ordersToolStripMenuItem.Click += new System.EventHandler(this.ordersToolStripMenuItem_Click);
//
// packageToolStripMenuItem2
//
this.packageToolStripMenuItem2.Name = "packageToolStripMenuItem2";
this.packageToolStripMenuItem2.Size = new System.Drawing.Size(180, 22);
this.packageToolStripMenuItem2.Text = "Пакеты";
this.packageToolStripMenuItem2.Click += new System.EventHandler(this.packageToolStripMenuItem_Click);
//
// storageToolStripMenuItem3
//
this.storageToolStripMenuItem3.Name = "storageToolStripMenuItem3";
this.storageToolStripMenuItem3.Size = new System.Drawing.Size(180, 22);
this.storageToolStripMenuItem3.Text = "ПО";
this.storageToolStripMenuItem3.Click += new System.EventHandler(this.softwareToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(803, 263);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonIssuedOrder);
this.Controls.Add(this.buttonOrderReady);
this.Controls.Add(this.buttonTakeOrderInWork);
this.Controls.Add(this.buttonCreateOrder);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "Магазин программного обеспечения";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
this.Load += new System.EventHandler(this.FormMain_Load);
}
#endregion
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private MenuStrip menuStrip1;
private ToolStripMenuItem guideToolStripMenuItem;
private ToolStripMenuItem packageToolStripMenuItem2;
private ToolStripMenuItem storageToolStripMenuItem3;
private ToolStripMenuItem reportsToolStripMenuItem;
private ToolStripMenuItem packagesToolStripMenuItem;
private ToolStripMenuItem packageSoftwaresToolStripMenuItem;
private ToolStripMenuItem ordersToolStripMenuItem;
}
}

View File

@ -0,0 +1,192 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using SoftwareInstallation;
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 SoftwareInstallationView
{
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)
{
InitializeSoftware();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["PackageId"].Visible = false;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{ Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new
OrderBindingModel
{ Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void softwareToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSoftwares));
if (service is FormSoftwares form)
{
form.ShowDialog();
}
}
private void packageToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormPackages));
if (service is FormPackages form)
{
form.ShowDialog();
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ordersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void packageSoftwaresToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportPackageSoftwares));
if (service is FormReportPackageSoftwares form)
{
form.ShowDialog();
}
}
private void packagesToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SavePackagesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

View File

@ -0,0 +1,63 @@
<root>
<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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,225 @@
namespace SoftwareInstallationView
{
partial class FormPackage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxPrice = new System.Windows.Forms.TextBox();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSoftware = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.groupBoxSoftware = new System.Windows.Forms.GroupBox();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelName = new System.Windows.Forms.Label();
this.labelPrice = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.groupBoxSoftware.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBoxName.Location = new System.Drawing.Point(131, 12);
this.textBoxName.Name = "textBox1";
this.textBoxName.Size = new System.Drawing.Size(343, 23);
this.textBoxName.TabIndex = 0;
//
// textBox2
//
this.textBoxPrice.Location = new System.Drawing.Point(131, 57);
this.textBoxPrice.Name = "textBox2";
this.textBoxPrice.Size = new System.Drawing.Size(174, 23);
this.textBoxPrice.TabIndex = 1;
//
// dataGridView1
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnId,
this.ColumnSoftware,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(6, 22);
this.dataGridView.Name = "dataGridView1";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(444, 299);
this.dataGridView.TabIndex = 2;
//
// ColumnId
//
this.ColumnId.HeaderText = "Id";
this.ColumnId.Name = "ColumnId";
this.ColumnId.Visible = false;
//
// ColumnSoftware
//
this.ColumnSoftware.HeaderText = "ПО";
this.ColumnSoftware.Name = "ColumnSoftware";
this.ColumnSoftware.Width = 300;
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.Name = "ColumnCount";
//
// groupBoxSoftware
//
this.groupBoxSoftware.Controls.Add(this.buttonUpdate);
this.groupBoxSoftware.Controls.Add(this.buttonDelete);
this.groupBoxSoftware.Controls.Add(this.dataGridView);
this.groupBoxSoftware.Controls.Add(this.buttonEdit);
this.groupBoxSoftware.Controls.Add(this.buttonAdd);
this.groupBoxSoftware.Location = new System.Drawing.Point(21, 105);
this.groupBoxSoftware.Name = "groupBoxSoftware";
this.groupBoxSoftware.Size = new System.Drawing.Size(586, 327);
this.groupBoxSoftware.TabIndex = 3;
this.groupBoxSoftware.TabStop = false;
this.groupBoxSoftware.Text = "ПО";
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(473, 22);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(98, 29);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(473, 75);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(98, 31);
this.buttonEdit.TabIndex = 1;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(473, 135);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(98, 31);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(473, 194);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(98, 29);
this.buttonUpdate.TabIndex = 4;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(376, 438);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(98, 23);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(494, 438);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(98, 23);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(55, 15);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(62, 15);
this.labelName.TabIndex = 7;
this.labelName.Text = "Название:";
//
// labelPrice
//
this.labelPrice.AutoSize = true;
this.labelPrice.Location = new System.Drawing.Point(55, 60);
this.labelPrice.Name = "labelPrice";
this.labelPrice.Size = new System.Drawing.Size(70, 15);
this.labelPrice.TabIndex = 8;
this.labelPrice.Text = "Стоимость:";
//
// FormPackage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(633, 472);
this.Controls.Add(this.labelPrice);
this.Controls.Add(this.labelName);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxPrice);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.groupBoxSoftware);
this.Name = "FormPackage";
this.Text = "Пакет";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.groupBoxSoftware.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
this.Load += new System.EventHandler(this.FormPackage_Load);
}
#endregion
private TextBox textBoxName;
private TextBox textBoxPrice;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnSoftware;
private DataGridViewTextBoxColumn ColumnCount;
private GroupBox groupBoxSoftware;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
private Button buttonSave;
private Button buttonCancel;
private Label labelName;
private Label labelPrice;
}
}

View File

@ -0,0 +1,229 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.SearchModels;
using AbstractSoftwareInstallationDataModels.Models;
using Microsoft.Extensions.Logging;
using SoftwareInstallation;
namespace SoftwareInstallationView
{
public partial class FormPackage : Form
{
private readonly ILogger _logger;
private readonly IPackageLogic _logic;
private int? _id;
private Dictionary<int, (ISoftwareModel, int)> _packageSoftwares;
public int Id { set { _id = value; } }
public FormPackage(ILogger<FormPackage> logger, IPackageLogic logic)
{
InitializeSoftware();
_logger = logger;
_logic = logic;
_packageSoftwares = new Dictionary<int, (ISoftwareModel, int)>();
}
private void FormPackage_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка ПО");
try
{
var view = _logic.ReadElement(new PackageSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.PackageName;
textBoxPrice.Text = view.Price.ToString();
_packageSoftwares = view.PackageSoftware ?? new Dictionary<int, (ISoftwareModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки ПО");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка ПО пакета");
try
{
if (_packageSoftwares != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _packageSoftwares)
{
dataGridView.Rows.Add(new object[]
{
pc.Key,
pc.Value.Item1.
SoftwareName,
pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
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(FormPackageSoftware));
if (service is FormPackageSoftware form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.SoftwareModel == null)
{
return;
}
_logger.LogInformation("Добавление нового ПО: { SoftwareName} - { Count}", form.SoftwareModel.SoftwareName, form.Count);
if (_packageSoftwares.ContainsKey(form.Id))
{
_packageSoftwares[form.Id] = (form.SoftwareModel, form.Count);
}
else
{
_packageSoftwares.Add(form.Id, (form.SoftwareModel, form.Count));
}
LoadData();
}
}
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormPackageSoftware));
if (service is FormPackageSoftware form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _packageSoftwares[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.SoftwareModel == null)
{
return;
}
_logger.LogInformation("Изменение ПО: { SoftwareName} - { Count}", form.SoftwareModel.SoftwareName, form.Count);
_packageSoftwares[form.Id] = (form.SoftwareModel, form.Count);
LoadData();
}
}
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление ПО: { SoftwareName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_packageSoftwares?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_packageSoftwares == null || _packageSoftwares.Count == 0)
{
MessageBox.Show("Заполните ПО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение пакета");
try
{
var model = new PackageBindingModel
{
Id = _id ?? 0,
PackageName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
PackageSoftware = _packageSoftwares
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения пакета");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _packageSoftwares)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,78 @@
<root>
<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="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSoftware.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSoftware.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,119 @@
namespace SoftwareInstallationView
{
partial class FormPackageSoftware
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.comboBoxSoftware = new System.Windows.Forms.ComboBox();
this.labelSoftware = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(101, 65);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(273, 23);
this.textBox1.TabIndex = 0;
//
// comboBoxSoftware
//
this.comboBoxSoftware.FormattingEnabled = true;
this.comboBoxSoftware.Location = new System.Drawing.Point(101, 24);
this.comboBoxSoftware.Name = "comboBoxSoftware";
this.comboBoxSoftware.Size = new System.Drawing.Size(273, 23);
this.comboBoxSoftware.TabIndex = 1;
//
// labelSoftware
//
this.labelSoftware.AutoSize = true;
this.labelSoftware.Location = new System.Drawing.Point(20, 27);
this.labelSoftware.Name = "labelSoftware";
this.labelSoftware.Size = new System.Drawing.Size(28, 15);
this.labelSoftware.TabIndex = 2;
this.labelSoftware.Text = "ПО:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(20, 68);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 3;
this.labelCount.Text = "Количество:";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(195, 103);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(75, 27);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(299, 103);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 27);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormPackageSoftware
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(403, 142);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelSoftware);
this.Controls.Add(this.comboBoxSoftware);
this.Controls.Add(this.textBox1);
this.Name = "FormPackageSoftware";
this.Text = "ПО пакета";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBox1;
private ComboBox comboBoxSoftware;
private Label labelSoftware;
private Label labelCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,84 @@
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using AbstractSoftwareInstallationContracts.ViewModels;
using AbstractSoftwareInstallationDataModels.Models;
namespace SoftwareInstallationView
{
public partial class FormPackageSoftware : Form
{
private readonly List<SoftwareViewModel>? _list;
public int Id
{
get
{
return Convert.ToInt32(comboBoxSoftware.SelectedValue);
}
set
{
comboBoxSoftware.SelectedValue = value;
}
}
public ISoftwareModel? SoftwareModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBox1.Text); }
set
{ textBox1.Text = value.ToString(); }
}
public FormPackageSoftware(ISoftwareLogic logic)
{
InitializeSoftware();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxSoftware.DisplayMember = "SoftwareName";
comboBoxSoftware.ValueMember = "Id";
comboBoxSoftware.DataSource = _list;
comboBoxSoftware.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxSoftware.SelectedValue == null)
{
MessageBox.Show("Выберите компонент", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,126 @@
namespace SoftwareInstallationView
{
partial class FormPackages
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnId});
this.dataGridView.Location = new System.Drawing.Point(1, 1);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(445, 373);
this.dataGridView.TabIndex = 10;
//
// ColumnId
//
this.ColumnId.FillWeight = 200F;
this.ColumnId.HeaderText = "Id";
this.ColumnId.Name = "ColumnId";
this.ColumnId.Visible = false;
this.ColumnId.Width = 200;
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(461, 193);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(97, 30);
this.buttonUpdate.TabIndex = 9;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(461, 135);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(97, 30);
this.buttonDelete.TabIndex = 8;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(461, 79);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(97, 30);
this.buttonEdit.TabIndex = 7;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(461, 22);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(97, 30);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// FormPackages
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(565, 374);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Name = "FormPackages";
this.Text = "Пакеты";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
private DataGridViewTextBoxColumn ColumnId;
}
}

View File

@ -0,0 +1,107 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using SoftwareInstallation;
namespace SoftwareInstallationView
{
public partial class FormPackages : Form
{
private readonly ILogger _logger;
private readonly IPackageLogic _logic;
public FormPackages(ILogger<FormPackages> logger, IPackageLogic logic)
{
InitializeSoftware();
_logger = logger;
_logic = logic;
LoadData();
}
private void FormPackages_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["PackageName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["PackageSoftware"].Visible = false;
}
_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(FormPackage));
if (service is FormPackage form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
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 PackageBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormPackage));
if (service is FormPackage form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
}
}

View File

@ -0,0 +1,63 @@
<root>
<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="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,131 @@
namespace SoftwareInstallationView
{
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.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.buttonCreateToPdf = new System.Windows.Forms.Button();
this.buttonCreateReport = new System.Windows.Forms.Button();
this.dateTimePicker2 = new System.Windows.Forms.DateTimePicker();
this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.label2);
this.panel.Controls.Add(this.label1);
this.panel.Controls.Add(this.buttonCreateToPdf);
this.panel.Controls.Add(this.buttonCreateReport);
this.panel.Controls.Add(this.dateTimePicker2);
this.panel.Controls.Add(this.dateTimePicker1);
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(800, 46);
this.panel.TabIndex = 0;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(206, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(23, 15);
this.label2.TabIndex = 5;
this.label2.Text = "По";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(15, 15);
this.label1.TabIndex = 4;
this.label1.Text = "С";
//
// buttonCreateToPdf
//
this.buttonCreateToPdf.Location = new System.Drawing.Point(668, 14);
this.buttonCreateToPdf.Name = "buttonCreateToPdf";
this.buttonCreateToPdf.Size = new System.Drawing.Size(110, 23);
this.buttonCreateToPdf.TabIndex = 3;
this.buttonCreateToPdf.Text = "В Pdf";
this.buttonCreateToPdf.UseVisualStyleBackColor = true;
this.buttonCreateToPdf.Click += new System.EventHandler(this.buttonCreateToPdf_Click);
//
// buttonCreateReport
//
this.buttonCreateReport.Location = new System.Drawing.Point(531, 14);
this.buttonCreateReport.Name = "buttonCreateReport";
this.buttonCreateReport.Size = new System.Drawing.Size(100, 23);
this.buttonCreateReport.TabIndex = 2;
this.buttonCreateReport.Text = "Сформировать";
this.buttonCreateReport.UseVisualStyleBackColor = true;
this.buttonCreateReport.Click += new System.EventHandler(this.buttonCreateReport_Click);
//
// dateTimePicker2
//
this.dateTimePicker2.Location = new System.Drawing.Point(256, 12);
this.dateTimePicker2.Name = "dateTimePicker2";
this.dateTimePicker2.Size = new System.Drawing.Size(141, 23);
this.dateTimePicker2.TabIndex = 1;
//
// dateTimePicker1
//
this.dateTimePicker1.Location = new System.Drawing.Point(48, 12);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(143, 23);
this.dateTimePicker1.TabIndex = 0;
//
// FormReportOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 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 Label label2;
private Label label1;
private Button buttonCreateToPdf;
private Button buttonCreateReport;
private DateTimePicker dateTimePicker2;
private DateTimePicker dateTimePicker1;
}
}

View File

@ -0,0 +1,102 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
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 SoftwareInstallationView
{
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("C:/Users/user/source/repos/PIbd-23_Dolgov_D.A._SoftwareInstallation/SoftwareInstallation/SoftwareInstallation/ReportOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void buttonCreateReport_Click(object sender, EventArgs e)
{
if (dateTimePicker1.Value.Date >= dateTimePicker2.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var dataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = dateTimePicker1.Value,
DateTo = dateTimePicker2.Value
});
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
var parameters = new[] { new ReportParameter("ReportParameterPeriod", $"c { dateTimePicker1.Value.ToShortDateString()} по {dateTimePicker2.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{ To}", dateTimePicker1.Value.ToShortDateString(), dateTimePicker2.Value.ToShortDateString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCreateToPdf_Click(object sender, EventArgs e)
{
if (dateTimePicker1.Value.Date >= dateTimePicker2.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 = dateTimePicker1.Value,
DateTo = dateTimePicker2.Value
});
_logger.LogInformation("Сохранение списка заказов на период { From} -{ To}", dateTimePicker1.Value.ToShortDateString(), dateTimePicker2.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,60 @@
<root>
<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,106 @@
namespace SoftwareInstallationView
{
partial class FormReportPackageSoftwares
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSaveToExcel = new System.Windows.Forms.Button();
this.ColumPackage = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSoftware = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ButtonHighlight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumPackage,
this.ColumnSoftware,
this.ColumnCount});
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom;
this.dataGridView.GridColor = System.Drawing.SystemColors.ButtonHighlight;
this.dataGridView.Location = new System.Drawing.Point(0, 47);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(750, 396);
this.dataGridView.TabIndex = 0;
//
// buttonSaveToExcel
//
this.buttonSaveToExcel.Location = new System.Drawing.Point(25, 12);
this.buttonSaveToExcel.Name = "buttonSaveToExcel";
this.buttonSaveToExcel.Size = new System.Drawing.Size(140, 23);
this.buttonSaveToExcel.TabIndex = 1;
this.buttonSaveToExcel.Text = "Сохранить в Excel";
this.buttonSaveToExcel.UseVisualStyleBackColor = true;
this.buttonSaveToExcel.Click += new System.EventHandler(this.buttonSaveToExcel_Click);
//
// ColumPackage
//
this.ColumPackage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumPackage.HeaderText = "Пакет";
this.ColumPackage.Name = "ColumPackage";
//
// ColumnSoftware
//
this.ColumnSoftware.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnSoftware.HeaderText = "ПО";
this.ColumnSoftware.Name = "ColumnSoftware";
//
// ColumnCount
//
this.ColumnCount.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.Name = "ColumnCount";
//
// FormReportPackageSoftwares
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(750, 443);
this.Controls.Add(this.buttonSaveToExcel);
this.Controls.Add(this.dataGridView);
this.Name = "FormReportPackageSoftwares";
this.Text = "Пакеты по ПО";
this.Load += new System.EventHandler(this.FormReportPackageSoftwares_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumPackage;
private DataGridViewTextBoxColumn ColumnSoftware;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,85 @@
using AbstractSoftwareInstallationContracts.BindingModels;
using AbstractSoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SoftwareInstallationView
{
public partial class FormReportPackageSoftwares : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportPackageSoftwares(ILogger<FormReportPackageSoftwares> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportPackageSoftwares_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetPackageSoftware();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.PackageName, "", "" });
foreach (var listElem in elem.Softwares)
{
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.SavePackageSoftwareToExcelFile(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,69 @@
<root>
<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="ColumPackage.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSoftware.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,118 @@
namespace SoftwareInstallation
{
partial class FormSoftware
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer Softwares = 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 && (Softwares != null))
{
Softwares.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 InitializeSoftware()
{
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxCost = new System.Windows.Forms.TextBox();
this.labelName = new System.Windows.Forms.Label();
this.labelCost = new System.Windows.Forms.Label();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(94, 28);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(316, 23);
this.textBoxName.TabIndex = 0;
//
// textBoxCost
//
this.textBoxCost.Location = new System.Drawing.Point(94, 76);
this.textBoxCost.Name = "textBoxCost";
this.textBoxCost.Size = new System.Drawing.Size(156, 23);
this.textBoxCost.TabIndex = 1;
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(29, 28);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(62, 15);
this.labelName.TabIndex = 2;
this.labelName.Text = "Название:";
//
// labelCost
//
this.labelCost.AutoSize = true;
this.labelCost.Location = new System.Drawing.Point(29, 76);
this.labelCost.Name = "labelCost";
this.labelCost.Size = new System.Drawing.Size(38, 15);
this.labelCost.TabIndex = 3;
this.labelCost.Text = "Цена:";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(195, 115);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(103, 26);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(307, 115);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(103, 26);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отменить";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormSoftware
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(441, 153);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.labelCost);
this.Controls.Add(this.labelName);
this.Controls.Add(this.textBoxCost);
this.Controls.Add(this.textBoxName);
this.Name = "FormSoftware";
this.Text = "Программное обеспечение";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxName;
private TextBox textBoxCost;
private Label labelName;
private Label labelCost;
private Button buttonSave;
private Button buttonCancel;
}
}

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