Compare commits

..

35 Commits

Author SHA1 Message Date
ea5578c18a жирное итого 2024-12-24 09:04:42 +04:00
c7d41abb50 готова к сдаче 2024-12-24 02:39:49 +04:00
2503c9f9c0 интерфейс форм, кроме заказ там с датами копаться нада 2024-12-23 23:54:00 +04:00
684d1c62eb остался заказ вроде... чет там с датами 2024-12-23 23:36:40 +04:00
587229b4ac готова к сдаче 2.0 2024-12-23 22:09:22 +04:00
ac4f2bb913 готова к сдаче 2024-12-23 21:12:37 +04:00
4b27c70d85 группировка для деталей 2024-12-23 01:22:50 +04:00
5cf61026d5 остался пдф 2024-12-23 00:30:21 +04:00
e46c650a3e Merge branch 'LabWork№3' into LabWork№2 2024-12-22 18:57:33 +04:00
d18793daaf фикс для 3 лабы 2024-12-22 18:56:48 +04:00
a6f82f8bd2 фикс 2024-12-22 18:43:09 +04:00
014eab4a08 фикс имен форм 2024-12-19 17:13:52 +04:00
8343749aed фикс отчета справочников, Эгову слава и почет <3 2024-12-16 16:57:47 +04:00
885c3a103a тот же ой 2024-12-16 16:17:59 +04:00
9fdef63038 ой 2024-12-16 15:36:42 +04:00
a6bc108099 ломаная таблица 2024-12-16 03:47:22 +04:00
d49587845b Эксель 2024-12-16 01:56:23 +04:00
ad2cd59537 справочники с ошибкой 2024-12-16 00:58:01 +04:00
47c5208fb2 wordbuilder 2024-12-15 22:21:36 +04:00
2411dfc6f7 в прошлом комите забыл указать, что исправил отображение списка при поплнении склада. Здесь убрал лишнии проверки на мой взгляд 2024-12-15 20:48:37 +04:00
c5ba2907f8 Merge branch 'LabWork№2' of https://git.is.ulstu.ru/MorozovDanil/PIbd-22_MorozovD.V._ProjectRepairCompany into LabWork№2 2024-12-15 20:36:01 +04:00
33ec560a98 Если глобально, то решил убрать обновление заказов тк. считаю это излишним и может угрожать целостности данных 2024-12-15 20:35:24 +04:00
2bcf91fdfe Merge pull request 'LabWork№1' (#6) from LabWork№1 into LabWork№2
Reviewed-on: #6
2024-12-15 19:15:08 +04:00
d33fff8c1b фиксация 2024-12-15 19:07:22 +04:00
c149dcb249 тест 2024-12-15 18:44:30 +04:00
8a60aa872a вроде полный фикс 2024-12-15 16:20:27 +04:00
a8a2fd350e неполный фикс для верности 2024-12-15 15:41:14 +04:00
f6e89b6040 почти все. сломалось 2024-12-02 17:51:40 +04:00
e841730166 готова к сдаче 2024-12-02 15:20:07 +04:00
bb69e427c8 Вроде готова к сдаче 2024-12-02 04:40:52 +04:00
194d4f03e4 готова к сдаче 2024-12-01 02:20:25 +04:00
be0b9e89a2 поправить чуть 2024-11-30 11:28:18 +04:00
32099a12bb переименовал кнопки 2024-11-30 08:32:00 +04:00
96875e17e5 Осталось несколько форм. Уточнить про удаление. Уточнить про заказ и даты. 2024-11-30 07:18:31 +04:00
7bc008185b Добавил перечисление, сущьности. Осталось репозитории, формы и тп. 2024-11-29 21:52:39 +04:00
83 changed files with 6937 additions and 75 deletions

View File

@ -0,0 +1,38 @@
using ProjectRepairCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities;
public class Detail
{
public int Id { get; private set; }
[DisplayName("Название детали")]
public string NameDetail { get; private set; } = string.Empty;
[DisplayName("Количество деталей")]
public int NumberDetail { get; private set; }
[DisplayName("Стоимость детали")]
public double PriceDetail { get; private set; }
[DisplayName("Свойства детали")]
public DetailProperties DetailProperties { get; private set; }
public static Detail CreateEntity(int id, string nameDetail, int numberDetail, double priceDetail, DetailProperties detailProperties)
{
return new Detail
{
Id = id,
NameDetail = nameDetail,
NumberDetail = numberDetail,
PriceDetail = priceDetail,
DetailProperties = detailProperties
};
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities.Enums;
[Flags]
public enum DetailProperties
{
None = 0, // Нет свойств
Fragile = 1, // Хрупкая деталь
Heavy = 2, // Тяжелая
Expensive = 4, // Дорогая
CustomMade = 8, // Изготовлена на заказ
InStock = 16, // В наличии
Discounted = 32 // Со скидкой
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities.Enums;
public enum MasterPost
{
None = 0,
Intern = 1,
Worker = 2,
Head = 3
}

View File

@ -0,0 +1,33 @@
using ProjectRepairCompany.Entities.Enums;
using System.ComponentModel;
namespace ProjectRepairCompany.Entities;
public class Master
{
public int Id { get; private set; }
[DisplayName("ФИО работника")]
public string MasterName { get; private set; } = string.Empty;
[DisplayName("Дата начала работы")]
public DateTime StartDate { get; private set; }
[DisplayName("Должность")]
public MasterPost MasterPost { get; private set; }
public static Master CreateEntity(int id, string masterName, DateTime startDate, MasterPost masterPost)
{
if (startDate > DateTime.Now)
{
throw new ArgumentException("Дата начала работы не может быть в будущем.");
}
return new Master
{
Id = id,
MasterName = masterName,
StartDate = startDate,
MasterPost = masterPost
};
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities;
public class Order
{
[DisplayName("Номер заказа")]
public int Id { get; private set; }
[DisplayName("Дата заказа")]
public DateTime OrderDate { get; private set; }
[DisplayName("Дата начала выполнения ремонта")]
public DateTime DateCompletion { get; private set; }
[DisplayName("Дата выполнения заказа")]
public DateTime DateIssue { get; private set; }
[DisplayName("Стоимость заказа")]
public int FullPrice { get; private set; }
[Browsable(false)]
public int MasterId { get; private set; }
[DisplayName("Работник")]
public string MasterName { get; set; } = string.Empty;
[DisplayName("Детали и кол-во")]
public string OrderAndDetail => OrderDetails != null && OrderDetails.Any()
? string.Join(", ", OrderDetails.Select(od => $"{od.DetailName}: {od.DetailCount}"))
: "Нет данных";
[Browsable(false)]
public IEnumerable<OrderDetail> OrderDetails { get; set; } = [];
public static Order CreateOperation(int id, int fullPrice, int masterId, DateTime dateCompletion,
DateTime dateIssue, IEnumerable<OrderDetail> orderDetails)
{
return new Order
{
Id = id,
OrderDate = DateTime.Now,
DateCompletion = dateCompletion,
DateIssue = dateIssue,
FullPrice = fullPrice,
MasterId = masterId,
OrderDetails = orderDetails
};
}
public void SetOrderDetails(IEnumerable<OrderDetail> orderDetails)
{
if (orderDetails != null && orderDetails.Any())
{
OrderDetails = orderDetails;
}
}
}

View File

@ -0,0 +1,19 @@
namespace ProjectRepairCompany.Entities;
public class OrderDetail
{
public int OrderId { get; private set; }
public int DetailId { get; private set; }
public int DetailCount { get; private set; }
public string DetailName { get; private set; } = string.Empty;
public static OrderDetail CreateOperation(int orderId, int detailId, int detailCount)
{
return new OrderDetail
{
OrderId = orderId,
DetailId = detailId,
DetailCount = detailCount
};
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities;
public class Storage
{
public int Id { get; private set; }
[DisplayName ("Адрес склада")]
public string StorageAddress { get; private set; } = string.Empty;
[DisplayName("Вместимость склада")]
public int Capacity { get; private set; }
public static Storage CreateEntity(int id, string storageAddress, int capacity)
{
return new Storage
{
Id = id,
StorageAddress = storageAddress,
Capacity = capacity
};
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Entities;
public class StorageDetail
{
[Browsable(false)]
public int StorageId { get; private set; }
[Browsable(false)]
public int DetailId { get; private set; }
[DisplayName("Количество деталей")]
public int DetailCount { get; private set; }
[DisplayName("Дата поступления")]
public DateTime SupplyDate { get; private set; } // Дата поступления деталей
[DisplayName("Адрес склада")]
public string StorageAddress { get; private set; } = string.Empty;
[DisplayName("Название детали")]
public string DetailName { get; private set; } = string.Empty;
public static StorageDetail CreateOperation(int storageId, int detailId, int detailCount, DateTime supplyDate)
{
return new StorageDetail
{
StorageId = storageId,
DetailId = detailId,
DetailCount = detailCount,
SupplyDate = supplyDate
};
}
}

View File

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

View File

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

View File

@ -0,0 +1,166 @@
namespace ProjectRepairCompany
{
partial class FormRepairCompany
{
/// <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()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
MasterToolStripMenuItem = new ToolStripMenuItem();
DetailToolStripMenuItem = new ToolStripMenuItem();
StorageToolStripMenuItem = new ToolStripMenuItem();
операцииToolStripMenuItem = new ToolStripMenuItem();
OrderToolStripMenuItem = new ToolStripMenuItem();
StorageDetailToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
MasterReportToolStripMenuItem = new ToolStripMenuItem();
MasterDistributionToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(834, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { MasterToolStripMenuItem, DetailToolStripMenuItem, StorageToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
//
// MasterToolStripMenuItem
//
MasterToolStripMenuItem.Name = "MasterToolStripMenuItem";
MasterToolStripMenuItem.Size = new Size(133, 22);
MasterToolStripMenuItem.Text = "Работники";
MasterToolStripMenuItem.Click += MasterToolStripMenuItem_Click;
//
// DetailToolStripMenuItem
//
DetailToolStripMenuItem.Name = "DetailToolStripMenuItem";
DetailToolStripMenuItem.Size = new Size(133, 22);
DetailToolStripMenuItem.Text = "Детали";
DetailToolStripMenuItem.Click += DetailToolStripMenuItem_Click;
//
// StorageToolStripMenuItem
//
StorageToolStripMenuItem.Name = "StorageToolStripMenuItem";
StorageToolStripMenuItem.Size = new Size(133, 22);
StorageToolStripMenuItem.Text = "Склады";
StorageToolStripMenuItem.Click += StorageToolStripMenuItem_Click;
//
// операцииToolStripMenuItem
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { OrderToolStripMenuItem, StorageDetailToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(75, 20);
операцииToolStripMenuItem.Text = "Операции";
//
// OrderToolStripMenuItem
//
OrderToolStripMenuItem.Name = "OrderToolStripMenuItem";
OrderToolStripMenuItem.Size = new Size(184, 22);
OrderToolStripMenuItem.Text = "Заказы";
OrderToolStripMenuItem.Click += OrderToolStripMenuItem_Click;
//
// StorageDetailToolStripMenuItem
//
StorageDetailToolStripMenuItem.Name = "StorageDetailToolStripMenuItem";
StorageDetailToolStripMenuItem.Size = new Size(184, 22);
StorageDetailToolStripMenuItem.Text = "Пополнение склада";
StorageDetailToolStripMenuItem.Click += StorageDetailToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, MasterReportToolStripMenuItem, MasterDistributionToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.Size = new Size(235, 22);
DirectoryReportToolStripMenuItem.Text = "Документ со справочниками";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// MasterReportToolStripMenuItem
//
MasterReportToolStripMenuItem.Name = "MasterReportToolStripMenuItem";
MasterReportToolStripMenuItem.Size = new Size(235, 22);
MasterReportToolStripMenuItem.Text = "Отчет по мастерам";
MasterReportToolStripMenuItem.Click += MasterReportToolStripMenuItem_Click;
//
// MasterDistributionToolStripMenuItem
//
MasterDistributionToolStripMenuItem.Name = "MasterDistributionToolStripMenuItem";
MasterDistributionToolStripMenuItem.Size = new Size(235, 22);
MasterDistributionToolStripMenuItem.Text = "Заказы мастера";
MasterDistributionToolStripMenuItem.Click += MasterDistributionToolStripMenuItem_Click;
//
// FormRepairCompany
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.Снимок_экрана_2024_09_02_200407;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(834, 407);
Controls.Add(menuStrip1);
DoubleBuffered = true;
MainMenuStrip = menuStrip1;
Name = "FormRepairCompany";
StartPosition = FormStartPosition.CenterScreen;
Text = "Фирма по ремонту техники";
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem MasterToolStripMenuItem;
private ToolStripMenuItem DetailToolStripMenuItem;
private ToolStripMenuItem StorageToolStripMenuItem;
private ToolStripMenuItem операцииToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem StorageDetailToolStripMenuItem;
private ToolStripMenuItem OrderToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem MasterReportToolStripMenuItem;
private ToolStripMenuItem MasterDistributionToolStripMenuItem;
}
}

View File

@ -0,0 +1,112 @@
using ProjectRepairCompany.Forms;
using Unity;
namespace ProjectRepairCompany
{
public partial class FormRepairCompany : Form
{
private readonly IUnityContainer _container;
public FormRepairCompany(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void MasterToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormMasters>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DetailToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDetails>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void StorageToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormStorages>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OrderToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormOrders>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void StorageDetailToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormStorageDetails>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MasterReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormMasterReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MasterDistributionToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormMasterDistributionReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà çàãðóçêè", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="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,170 @@
namespace ProjectRepairCompany.Forms
{
partial class FormDetail
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
checkedListBoxDetailProperties = new CheckedListBox();
label1 = new Label();
label2 = new Label();
textBoxNameDetail = new TextBox();
label3 = new Label();
label4 = new Label();
ButtonSave = new Button();
ButtonCancel = new Button();
numericUpDownPrice = new NumericUpDown();
numericUpDownNumber = new NumericUpDown();
((System.ComponentModel.ISupportInitialize)numericUpDownPrice).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownNumber).BeginInit();
SuspendLayout();
//
// checkedListBoxDetailProperties
//
checkedListBoxDetailProperties.FormattingEnabled = true;
checkedListBoxDetailProperties.Location = new Point(146, 12);
checkedListBoxDetailProperties.Name = "checkedListBoxDetailProperties";
checkedListBoxDetailProperties.Size = new Size(229, 144);
checkedListBoxDetailProperties.TabIndex = 0;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(30, 31);
label1.Name = "label1";
label1.Size = new Size(110, 17);
label1.TabIndex = 1;
label1.Text = "Свойства детали:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(30, 179);
label2.Name = "label2";
label2.Size = new Size(68, 17);
label2.TabIndex = 2;
label2.Text = "Название:";
//
// textBoxNameDetail
//
textBoxNameDetail.Location = new Point(123, 171);
textBoxNameDetail.Name = "textBoxNameDetail";
textBoxNameDetail.Size = new Size(252, 25);
textBoxNameDetail.TabIndex = 3;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(12, 213);
label3.Name = "label3";
label3.Size = new Size(143, 17);
label3.TabIndex = 4;
label3.Text = "Количество на складе:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(12, 258);
label4.Name = "label4";
label4.Size = new Size(86, 17);
label4.TabIndex = 6;
label4.Text = "Цена детали:";
//
// ButtonSave
//
ButtonSave.Location = new Point(30, 307);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(103, 44);
ButtonSave.TabIndex = 8;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(172, 307);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(100, 44);
ButtonCancel.TabIndex = 9;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// numericUpDownPrice
//
numericUpDownPrice.DecimalPlaces = 2;
numericUpDownPrice.Location = new Point(162, 256);
numericUpDownPrice.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 });
numericUpDownPrice.Name = "numericUpDownPrice";
numericUpDownPrice.Size = new Size(169, 25);
numericUpDownPrice.TabIndex = 10;
//
// numericUpDownNumber
//
numericUpDownNumber.Location = new Point(172, 213);
numericUpDownNumber.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownNumber.Name = "numericUpDownNumber";
numericUpDownNumber.Size = new Size(169, 25);
numericUpDownNumber.TabIndex = 11;
//
// FormDetail
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(405, 450);
Controls.Add(numericUpDownNumber);
Controls.Add(numericUpDownPrice);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(textBoxNameDetail);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(checkedListBoxDetailProperties);
Name = "FormDetail";
StartPosition = FormStartPosition.CenterParent;
Text = "Деталь";
((System.ComponentModel.ISupportInitialize)numericUpDownPrice).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownNumber).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckedListBox checkedListBoxDetailProperties;
private Label label1;
private Label label2;
private TextBox textBoxNameDetail;
private Label label3;
private Label label4;
private Button ButtonSave;
private Button ButtonCancel;
private NumericUpDown numericUpDownPrice;
private NumericUpDown numericUpDownNumber;
}
}

View File

@ -0,0 +1,106 @@
using Microsoft.VisualBasic.FileIO;
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
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 ProjectRepairCompany.Forms
{
public partial class FormDetail : Form
{
private readonly IDetailRepository _detailRepository;
private int? _detailId;
public int Id
{
set
{
try
{
var detail = _detailRepository.ReadDetailById(value);
if (detail == null)
{
throw new InvalidOperationException(nameof(detail));
}
foreach (DetailProperties elem in Enum.GetValues(typeof(DetailProperties)))
{
if ((elem & detail.DetailProperties) != 0)
{
checkedListBoxDetailProperties.SetItemChecked(checkedListBoxDetailProperties.Items.IndexOf(elem), true);
}
}
textBoxNameDetail.Text = detail.NameDetail;
numericUpDownNumber.Value = (decimal)detail.NumberDetail;
numericUpDownPrice.Value = (decimal)detail.PriceDetail;
_detailId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormDetail(IDetailRepository detailRepository)
{
InitializeComponent();
_detailRepository = detailRepository ??
throw new ArgumentNullException(nameof(detailRepository));
foreach (var elem in Enum.GetValues(typeof(DetailProperties)))
{
checkedListBoxDetailProperties.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxNameDetail.Text) ||
checkedListBoxDetailProperties.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
if (_detailId.HasValue)
{
_detailRepository.UpdateDetail(CreateDetail(_detailId.Value));
}
else
{
_detailRepository.CreateDetail(CreateDetail(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Detail CreateDetail(int id)
{
DetailProperties detailProperties = DetailProperties.None;
foreach (var elem in checkedListBoxDetailProperties.CheckedItems)
{
detailProperties |= (DetailProperties)elem;
}
return Detail.CreateEntity(id, textBoxNameDetail.Text,
Convert.ToInt32(numericUpDownNumber.Value), Convert.ToDouble(numericUpDownPrice.Value), detailProperties);
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,125 @@
namespace ProjectRepairCompany.Forms
{
partial class FormDetails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel1 = new Panel();
ButtonUp = new Button();
ButtonDel = new Button();
ButtonAdd = new Button();
dataGridView = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(ButtonUp);
panel1.Controls.Add(ButtonDel);
panel1.Controls.Add(ButtonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(607, 0);
panel1.Name = "panel1";
panel1.Size = new Size(193, 450);
panel1.TabIndex = 2;
//
// ButtonUp
//
ButtonUp.BackgroundImage = Properties.Resources.Feedbin_Icon_home_edit_svg;
ButtonUp.BackgroundImageLayout = ImageLayout.Stretch;
ButtonUp.Location = new Point(42, 113);
ButtonUp.Name = "ButtonUp";
ButtonUp.Size = new Size(117, 77);
ButtonUp.TabIndex = 2;
ButtonUp.UseVisualStyleBackColor = true;
ButtonUp.Click += ButtonUp_Click;
//
// ButtonDel
//
ButtonDel.BackgroundImage = Properties.Resources.Ic_remove_circle_48px_svg;
ButtonDel.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDel.Location = new Point(42, 213);
ButtonDel.Name = "ButtonDel";
ButtonDel.Size = new Size(117, 83);
ButtonDel.TabIndex = 1;
ButtonDel.UseVisualStyleBackColor = true;
ButtonDel.Click += ButtonDel_Click;
//
// ButtonAdd
//
ButtonAdd.BackgroundImage = Properties.Resources._43_436254_plus_green_plus_icon_png;
ButtonAdd.BackgroundImageLayout = ImageLayout.Stretch;
ButtonAdd.Location = new Point(42, 20);
ButtonAdd.Name = "ButtonAdd";
ButtonAdd.Size = new Size(117, 74);
ButtonAdd.TabIndex = 0;
ButtonAdd.UseVisualStyleBackColor = true;
ButtonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(607, 450);
dataGridView.TabIndex = 3;
//
// FormDetails
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormDetails";
Text = "Детали";
Load += FormDetails_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonUp;
private Button ButtonDel;
private Button ButtonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,120 @@
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormDetails : Form
{
private readonly IUnityContainer _container;
private readonly IDetailRepository _detailRepository;
public FormDetails(IUnityContainer container, IDetailRepository detailRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_detailRepository = detailRepository ??
throw new ArgumentNullException(nameof(detailRepository));
}
private void FormDetails_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDetail>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка добавления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUp_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
try
{
var form = _container.Resolve<FormDetail>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка изменения", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_detailRepository.DeleteDetail(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
try
{
dataGridView.DataSource = _detailRepository.ReadDetails();
dataGridView.Columns["Id"].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

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

View File

@ -0,0 +1,100 @@
namespace ProjectRepairCompany.Forms
{
partial class FormDirectoryReport
{
/// <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()
{
checkBoxMasters = new CheckBox();
checkBoxDetails = new CheckBox();
checkBoxStorages = new CheckBox();
ButtonBuild = new Button();
SuspendLayout();
//
// checkBoxMasters
//
checkBoxMasters.AutoSize = true;
checkBoxMasters.Location = new Point(34, 28);
checkBoxMasters.Name = "checkBoxMasters";
checkBoxMasters.Size = new Size(89, 21);
checkBoxMasters.TabIndex = 0;
checkBoxMasters.Text = "Работники";
checkBoxMasters.UseVisualStyleBackColor = true;
//
// checkBoxDetails
//
checkBoxDetails.AutoSize = true;
checkBoxDetails.Location = new Point(34, 83);
checkBoxDetails.Name = "checkBoxDetails";
checkBoxDetails.Size = new Size(69, 21);
checkBoxDetails.TabIndex = 1;
checkBoxDetails.Text = "Детали";
checkBoxDetails.UseVisualStyleBackColor = true;
//
// checkBoxStorages
//
checkBoxStorages.AutoSize = true;
checkBoxStorages.Location = new Point(34, 135);
checkBoxStorages.Name = "checkBoxStorages";
checkBoxStorages.Size = new Size(71, 21);
checkBoxStorages.TabIndex = 2;
checkBoxStorages.Text = "Склады";
checkBoxStorages.UseVisualStyleBackColor = true;
//
// ButtonBuild
//
ButtonBuild.Location = new Point(155, 28);
ButtonBuild.Name = "ButtonBuild";
ButtonBuild.Size = new Size(139, 128);
ButtonBuild.TabIndex = 3;
ButtonBuild.Text = "Формировать отчет";
ButtonBuild.UseVisualStyleBackColor = true;
ButtonBuild.Click += ButtonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(398, 249);
Controls.Add(ButtonBuild);
Controls.Add(checkBoxStorages);
Controls.Add(checkBoxDetails);
Controls.Add(checkBoxMasters);
Name = "FormDirectoryReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчет по справочникам";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxMasters;
private CheckBox checkBoxDetails;
private CheckBox checkBoxStorages;
private Button ButtonBuild;
}
}

View File

@ -0,0 +1,58 @@
using ProjectRepairCompany.Reports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxMasters.Checked && !checkBoxDetails.Checked && !checkBoxStorages.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if (_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxMasters.Checked, checkBoxDetails.Checked, checkBoxStorages.Checked))
{
MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах","Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,141 @@
namespace ProjectRepairCompany.Forms
{
partial class FormMaster
{
/// <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()
{
comboBoxPost = new ComboBox();
ButtonSave = new Button();
ButtonCancel = new Button();
label1 = new Label();
label2 = new Label();
label3 = new Label();
textBoxName = new TextBox();
dateTimePicker = new DateTimePicker();
SuspendLayout();
//
// comboBoxPost
//
comboBoxPost.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxPost.FormattingEnabled = true;
comboBoxPost.Location = new Point(205, 84);
comboBoxPost.Name = "comboBoxPost";
comboBoxPost.Size = new Size(121, 25);
comboBoxPost.TabIndex = 0;
//
// ButtonSave
//
ButtonSave.Location = new Point(32, 183);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(96, 45);
ButtonSave.TabIndex = 1;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(178, 183);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(88, 45);
ButtonCancel.TabIndex = 2;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(30, 43);
label1.Name = "label1";
label1.Size = new Size(37, 17);
label1.TabIndex = 3;
label1.Text = "Имя:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(30, 87);
label2.Name = "label2";
label2.Size = new Size(77, 17);
label2.TabIndex = 4;
label2.Text = "Должность:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(30, 129);
label3.Name = "label3";
label3.Size = new Size(134, 17);
label3.TabIndex = 5;
label3.Text = "Дата начала работы:";
//
// textBoxName
//
textBoxName.Location = new Point(205, 35);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(121, 25);
textBoxName.TabIndex = 6;
//
// dateTimePicker
//
dateTimePicker.Location = new Point(192, 123);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(152, 25);
dateTimePicker.TabIndex = 7;
dateTimePicker.Value = new DateTime(2024, 11, 30, 5, 36, 53, 0);
//
// FormMaster
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(400, 276);
Controls.Add(dateTimePicker);
Controls.Add(textBoxName);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(comboBoxPost);
Name = "FormMaster";
Text = "Работник";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxPost;
private Button ButtonSave;
private Button ButtonCancel;
private Label label1;
private Label label2;
private Label label3;
private TextBox textBoxName;
private DateTimePicker dateTimePicker;
}
}

View File

@ -0,0 +1,81 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using ProjectRepairCompany.Repositories;
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 ProjectRepairCompany.Forms;
public partial class FormMaster : Form
{
private readonly IMasterRepository _masterRepository;
private int? _masterId;
public int Id
{
set
{
try
{
var master = _masterRepository.ReadMasterById(value);
if (master == null)
{
throw new InvalidOperationException(nameof(master));
}
textBoxName.Text = master.MasterName;
comboBoxPost.SelectedItem = master.MasterPost;
dateTimePicker.Value = master.StartDate;
_masterId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormMaster(IMasterRepository masterRepository)
{
InitializeComponent();
_masterRepository = masterRepository ??
throw new ArgumentNullException(nameof(masterRepository));
comboBoxPost.DataSource = Enum.GetValues(typeof(MasterPost));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxPost.SelectedIndex < 1)
{
throw new Exception("Заполните все данные");
}
if (_masterId.HasValue)
{
_masterRepository.UpdateMaster(CreateMaster(_masterId.Value));
}
else
{
_masterRepository.CreateMaster(CreateMaster(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Master CreateMaster(int id) => Master.CreateEntity(id, textBoxName.Text, dateTimePicker.Value, (MasterPost)comboBoxPost.SelectedItem!);
}

View File

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

View File

@ -0,0 +1,111 @@
namespace ProjectRepairCompany.Forms
{
partial class FormMasterDistributionReport
{
/// <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()
{
dateTimePickerDate = new DateTimePicker();
label1 = new Label();
ButtonFilePath = new Button();
LabelFileName = new Label();
ButtonCreate = new Button();
SuspendLayout();
//
// dateTimePickerDate
//
dateTimePickerDate.Location = new Point(89, 78);
dateTimePickerDate.Name = "dateTimePickerDate";
dateTimePickerDate.Size = new Size(210, 23);
dateTimePickerDate.TabIndex = 0;
//
// label1
//
label1.AutoSize = true;
label1.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point, 204);
label1.Location = new Point(29, 82);
label1.Name = "label1";
label1.Size = new Size(39, 17);
label1.TabIndex = 1;
label1.Text = "Дата:";
//
// ButtonFilePath
//
ButtonFilePath.Location = new Point(43, 25);
ButtonFilePath.Name = "ButtonFilePath";
ButtonFilePath.Size = new Size(78, 35);
ButtonFilePath.TabIndex = 2;
ButtonFilePath.Text = "Выбрать";
ButtonFilePath.UseVisualStyleBackColor = true;
ButtonFilePath.Click += ButtonFilePath_Click;
//
// LabelFileName
//
LabelFileName.AutoSize = true;
LabelFileName.Font = new Font("Segoe UI", 14.25F, FontStyle.Regular, GraphicsUnit.Point, 204);
LabelFileName.Location = new Point(151, 27);
LabelFileName.Name = "LabelFileName";
LabelFileName.Size = new Size(57, 25);
LabelFileName.TabIndex = 3;
LabelFileName.Text = "Файл";
//
// ButtonCreate
//
ButtonCreate.Font = new Font("Segoe UI", 9.75F, FontStyle.Italic, GraphicsUnit.Point, 204);
ButtonCreate.Location = new Point(29, 117);
ButtonCreate.Name = "ButtonCreate";
ButtonCreate.Size = new Size(275, 35);
ButtonCreate.TabIndex = 4;
ButtonCreate.Text = "Сформировать";
ButtonCreate.UseVisualStyleBackColor = true;
ButtonCreate.Click += ButtonCreate_Click;
//
// FormMasterDistributionReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(541, 175);
Controls.Add(ButtonCreate);
Controls.Add(LabelFileName);
Controls.Add(ButtonFilePath);
Controls.Add(label1);
Controls.Add(dateTimePickerDate);
Name = "FormMasterDistributionReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчет заказов мастера";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerDate;
private Label label1;
private Button ButtonFilePath;
private Label LabelFileName;
private Button ButtonCreate;
}
}

View File

@ -0,0 +1,66 @@
using ProjectRepairCompany.Reports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms;
public partial class FormMasterDistributionReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormMasterDistributionReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
LabelFileName.Text = Path.GetFileName(_fileName);
}
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePickerDate.Value))
{
MessageBox.Show("Документ сформирован", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

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

View File

@ -0,0 +1,164 @@
namespace ProjectRepairCompany.Forms
{
partial class FormMasterReport
{
/// <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()
{
ButtonMakeReport = new Button();
comboBoxMaster = new ComboBox();
label1 = new Label();
label2 = new Label();
label3 = new Label();
dateTimePickerStart = new DateTimePicker();
dateTimePickerEnd = new DateTimePicker();
textBoxFilePath = new TextBox();
label4 = new Label();
ButtonFilePath = new Button();
SuspendLayout();
//
// ButtonMakeReport
//
ButtonMakeReport.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
ButtonMakeReport.Location = new Point(95, 209);
ButtonMakeReport.Name = "ButtonMakeReport";
ButtonMakeReport.Size = new Size(174, 42);
ButtonMakeReport.TabIndex = 0;
ButtonMakeReport.Text = "Сформировать";
ButtonMakeReport.UseVisualStyleBackColor = true;
ButtonMakeReport.Click += ButtonMakeReport_Click;
//
// comboBoxMaster
//
comboBoxMaster.FormattingEnabled = true;
comboBoxMaster.Location = new Point(113, 80);
comboBoxMaster.Name = "comboBoxMaster";
comboBoxMaster.Size = new Size(174, 23);
comboBoxMaster.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 130);
label1.Name = "label1";
label1.Size = new Size(77, 15);
label1.TabIndex = 2;
label1.Text = "Дата начала:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(12, 162);
label2.Name = "label2";
label2.Size = new Size(71, 15);
label2.TabIndex = 3;
label2.Text = "Дата конца:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(12, 83);
label3.Name = "label3";
label3.Size = new Size(95, 15);
label3.TabIndex = 4;
label3.Text = "Выбор мастера:";
//
// dateTimePickerStart
//
dateTimePickerStart.Location = new Point(95, 124);
dateTimePickerStart.Name = "dateTimePickerStart";
dateTimePickerStart.Size = new Size(174, 23);
dateTimePickerStart.TabIndex = 5;
//
// dateTimePickerEnd
//
dateTimePickerEnd.Location = new Point(95, 156);
dateTimePickerEnd.Name = "dateTimePickerEnd";
dateTimePickerEnd.Size = new Size(174, 23);
dateTimePickerEnd.TabIndex = 6;
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(113, 21);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.Size = new Size(232, 23);
textBoxFilePath.TabIndex = 7;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(12, 29);
label4.Name = "label4";
label4.Size = new Size(83, 15);
label4.TabIndex = 8;
label4.Text = "Путь к файлу:";
//
// ButtonFilePath
//
ButtonFilePath.Location = new Point(351, 19);
ButtonFilePath.Name = "ButtonFilePath";
ButtonFilePath.Size = new Size(31, 24);
ButtonFilePath.TabIndex = 9;
ButtonFilePath.Text = "...";
ButtonFilePath.UseVisualStyleBackColor = true;
ButtonFilePath.Click += ButtonFilePath_Click;
//
// FormMasterReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(389, 328);
Controls.Add(ButtonFilePath);
Controls.Add(label4);
Controls.Add(textBoxFilePath);
Controls.Add(dateTimePickerEnd);
Controls.Add(dateTimePickerStart);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(comboBoxMaster);
Controls.Add(ButtonMakeReport);
Name = "FormMasterReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчет по мастерам";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonMakeReport;
private ComboBox comboBoxMaster;
private Label label1;
private Label label2;
private Label label3;
private DateTimePicker dateTimePickerStart;
private DateTimePicker dateTimePickerEnd;
private TextBox textBoxFilePath;
private Label label4;
private Button ButtonFilePath;
}
}

View File

@ -0,0 +1,84 @@
using ProjectRepairCompany.Reports;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormMasterReport : Form
{
private readonly IUnityContainer _container;
private readonly IMasterRepository _masterRepository;
public FormMasterReport(IUnityContainer container, IOrderRepository orderRepository, IMasterRepository masterRepository)
{
InitializeComponent();
_container = container
?? throw new ArgumentNullException(nameof(container));
_masterRepository = masterRepository ??
throw new ArgumentNullException(nameof(masterRepository));
comboBoxMaster.DataSource = masterRepository.ReadMasters();
comboBoxMaster.DisplayMember = "MasterName";
comboBoxMaster.ValueMember = "Id";
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxMaster.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
}
if (dateTimePickerEnd.Value <= dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
var tableReport = _container.Resolve<TableReport>();
var masterId = (int)comboBoxMaster.SelectedValue!;
var masterName = ((dynamic)comboBoxMaster.SelectedItem).MasterName;
if (tableReport.CreateTable(textBoxFilePath.Text, masterId, masterName, dateTimePickerStart.Value, dateTimePickerEnd.Value))
{
MessageBox.Show("Документ успешно сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
}
}

View File

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

View File

@ -0,0 +1,125 @@
namespace ProjectRepairCompany.Forms
{
partial class FormMasters
{
/// <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()
{
panel1 = new Panel();
ButtonUp = new Button();
ButtonDel = new Button();
ButtonAdd = new Button();
dataGridView = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(ButtonUp);
panel1.Controls.Add(ButtonDel);
panel1.Controls.Add(ButtonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(607, 0);
panel1.Name = "panel1";
panel1.Size = new Size(193, 450);
panel1.TabIndex = 1;
//
// ButtonUp
//
ButtonUp.BackgroundImage = Properties.Resources.Feedbin_Icon_home_edit_svg;
ButtonUp.BackgroundImageLayout = ImageLayout.Stretch;
ButtonUp.Location = new Point(42, 113);
ButtonUp.Name = "ButtonUp";
ButtonUp.Size = new Size(117, 77);
ButtonUp.TabIndex = 2;
ButtonUp.UseVisualStyleBackColor = true;
ButtonUp.Click += ButtonUp_Click;
//
// ButtonDel
//
ButtonDel.BackgroundImage = Properties.Resources.Ic_remove_circle_48px_svg;
ButtonDel.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDel.Location = new Point(42, 213);
ButtonDel.Name = "ButtonDel";
ButtonDel.Size = new Size(117, 83);
ButtonDel.TabIndex = 1;
ButtonDel.UseVisualStyleBackColor = true;
ButtonDel.Click += ButtonDel_Click;
//
// ButtonAdd
//
ButtonAdd.BackgroundImage = Properties.Resources._43_436254_plus_green_plus_icon_png;
ButtonAdd.BackgroundImageLayout = ImageLayout.Stretch;
ButtonAdd.Location = new Point(42, 20);
ButtonAdd.Name = "ButtonAdd";
ButtonAdd.Size = new Size(117, 74);
ButtonAdd.TabIndex = 0;
ButtonAdd.UseVisualStyleBackColor = true;
ButtonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(607, 450);
dataGridView.TabIndex = 2;
//
// FormMasters
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormMasters";
Text = "Работники";
Load += FormMasters_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonUp;
private Button ButtonDel;
private Button ButtonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,120 @@
using ProjectRepairCompany.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormMasters : Form
{
private readonly IUnityContainer _container;
private readonly IMasterRepository _masterRepository;
public FormMasters(IUnityContainer container, IMasterRepository masterRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_masterRepository = masterRepository ??
throw new ArgumentNullException(nameof(masterRepository));
}
private void FormMasters_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormMaster>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка добавления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUp_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
try
{
var form = _container.Resolve<FormMaster>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка изменения", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_masterRepository.DeleteMaster(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
try
{
dataGridView.DataSource = _masterRepository.ReadMasters();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["StartDate"].DefaultCellStyle.Format = "dd MMMM yyyy";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

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

View File

@ -0,0 +1,246 @@
namespace ProjectRepairCompany.Forms
{
partial class FormOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
ButtonSave = new Button();
ButtonCancel = new Button();
label1 = new Label();
label2 = new Label();
dateTimePickerOrderDate = new DateTimePicker();
dateTimeCompletion = new DateTimePicker();
dateTimeIssue = new DateTimePicker();
label3 = new Label();
label4 = new Label();
numericUpDownFullPrice = new NumericUpDown();
label5 = new Label();
comboBoxMaster = new ComboBox();
groupBoxDetail = new GroupBox();
dataGridView = new DataGridView();
Detail = new DataGridViewComboBoxColumn();
DetailCount = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)numericUpDownFullPrice).BeginInit();
groupBoxDetail.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// ButtonSave
//
ButtonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonSave.Location = new Point(25, 478);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(96, 42);
ButtonSave.TabIndex = 0;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCancel.Location = new Point(322, 478);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(118, 42);
ButtonCancel.TabIndex = 1;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 9);
label1.Name = "label1";
label1.Size = new Size(149, 17);
label1.TabIndex = 2;
label1.Text = "Дата получения заказа:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(12, 63);
label2.Name = "label2";
label2.Size = new Size(134, 17);
label2.TabIndex = 3;
label2.Text = "Дата начала работы:";
//
// dateTimePickerOrderDate
//
dateTimePickerOrderDate.CausesValidation = false;
dateTimePickerOrderDate.Enabled = false;
dateTimePickerOrderDate.Location = new Point(190, 12);
dateTimePickerOrderDate.Name = "dateTimePickerOrderDate";
dateTimePickerOrderDate.Size = new Size(188, 25);
dateTimePickerOrderDate.TabIndex = 4;
//
// dateTimeCompletion
//
dateTimeCompletion.Location = new Point(190, 55);
dateTimeCompletion.Name = "dateTimeCompletion";
dateTimeCompletion.Size = new Size(210, 25);
dateTimeCompletion.TabIndex = 5;
//
// dateTimeIssue
//
dateTimeIssue.Location = new Point(190, 101);
dateTimeIssue.Name = "dateTimeIssue";
dateTimeIssue.Size = new Size(200, 25);
dateTimeIssue.TabIndex = 6;
dateTimeIssue.Value = new DateTime(2024, 12, 15, 0, 0, 0, 0);
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(12, 107);
label3.Name = "label3";
label3.Size = new Size(135, 17);
label3.TabIndex = 7;
label3.Text = "Дата вручения заказ:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(25, 147);
label4.Name = "label4";
label4.Size = new Size(121, 17);
label4.TabIndex = 8;
label4.Text = "Полная стоимость:";
//
// numericUpDownFullPrice
//
numericUpDownFullPrice.DecimalPlaces = 2;
numericUpDownFullPrice.Location = new Point(189, 146);
numericUpDownFullPrice.Maximum = new decimal(new int[] { 100000, 0, 0, 0 });
numericUpDownFullPrice.Name = "numericUpDownFullPrice";
numericUpDownFullPrice.Size = new Size(186, 25);
numericUpDownFullPrice.TabIndex = 9;
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(81, 194);
label5.Name = "label5";
label5.Size = new Size(66, 17);
label5.TabIndex = 10;
label5.Text = "Работник:";
//
// comboBoxMaster
//
comboBoxMaster.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxMaster.FormattingEnabled = true;
comboBoxMaster.Location = new Point(189, 186);
comboBoxMaster.Name = "comboBoxMaster";
comboBoxMaster.Size = new Size(182, 25);
comboBoxMaster.TabIndex = 11;
//
// groupBoxDetail
//
groupBoxDetail.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupBoxDetail.Controls.Add(dataGridView);
groupBoxDetail.Location = new Point(30, 234);
groupBoxDetail.Name = "groupBoxDetail";
groupBoxDetail.RightToLeft = RightToLeft.No;
groupBoxDetail.Size = new Size(401, 224);
groupBoxDetail.TabIndex = 12;
groupBoxDetail.TabStop = false;
groupBoxDetail.Text = "Детали";
//
// dataGridView
//
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { Detail, DetailCount });
dataGridView.Location = new Point(3, 21);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
dataGridView.Size = new Size(395, 200);
dataGridView.TabIndex = 0;
//
// Detail
//
Detail.HeaderText = "Название детали";
Detail.Name = "Detail";
//
// DetailCount
//
DetailCount.HeaderText = "Число деталей";
DetailCount.Name = "DetailCount";
//
// FormOrder
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(461, 532);
Controls.Add(groupBoxDetail);
Controls.Add(comboBoxMaster);
Controls.Add(label5);
Controls.Add(numericUpDownFullPrice);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(dateTimeIssue);
Controls.Add(dateTimeCompletion);
Controls.Add(dateTimePickerOrderDate);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Name = "FormOrder";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказ";
((System.ComponentModel.ISupportInitialize)numericUpDownFullPrice).EndInit();
groupBoxDetail.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonSave;
private Button ButtonCancel;
private Label label1;
private Label label2;
private DateTimePicker dateTimePickerOrderDate;
private DateTimePicker dateTimeCompletion;
private DateTimePicker dateTimeIssue;
private Label label3;
private Label label4;
private NumericUpDown numericUpDownFullPrice;
private Label label5;
private ComboBox comboBoxMaster;
private GroupBox groupBoxDetail;
private DataGridView dataGridView;
private DataGridViewComboBoxColumn Detail;
private DataGridViewTextBoxColumn DetailCount;
}
}

View File

@ -0,0 +1,127 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectRepairCompany.Forms
{
public partial class FormOrder : Form
{
private readonly IOrderRepository _orderRepository;
private int? _orderId;
public int Id
{
set
{
try
{
var order = _orderRepository.ReadOrderById(value);
if (order == null)
{
throw new InvalidOperationException(nameof(order));
}
comboBoxMaster.SelectedValue = order.MasterId;
numericUpDownFullPrice.Value = (decimal)order.FullPrice;
dateTimeCompletion.Value = order.DateCompletion;
dateTimeIssue.Value = order.DateIssue;
dataGridView.Rows.Clear();
foreach (var detail in order.OrderDetails)
{
dataGridView.Rows.Add(detail.DetailId, detail.DetailCount);
}
_orderId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormOrder(IOrderRepository orderRepository, IMasterRepository masterRepository, IDetailRepository detailRepository)
{
InitializeComponent();
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
comboBoxMaster.DataSource = masterRepository.ReadMasters();
comboBoxMaster.DisplayMember = "MasterName";
comboBoxMaster.ValueMember = "Id";
Detail.DataSource = detailRepository.ReadDetails();
Detail.DisplayMember = "NameDetail";
Detail.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (dataGridView.RowCount < 1 || comboBoxMaster.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля.");
}
var order = CreateOrder();
_orderRepository.CreateOrder(order);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<OrderDetail> CreateListOrderDetailsFromDataGrid()
{
var list = new List<OrderDetail>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["Detail"].Value == null ||
row.Cells["DetailCount"].Value == null)
{
continue;
}
list.Add(OrderDetail.CreateOperation(
0,
Convert.ToInt32(row.Cells["Detail"].Value),
Convert.ToInt32(row.Cells["DetailCount"].Value)
));
}
return list;
}
private Order CreateOrder()
{
var orderDetails = CreateListOrderDetailsFromDataGrid();
return Order.CreateOperation(
0,
Convert.ToInt32(numericUpDownFullPrice.Value),
(int)comboBoxMaster.SelectedValue,
dateTimeCompletion.Value,
dateTimeIssue.Value,
orderDetails
);
}
}
}

View File

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

View File

@ -0,0 +1,111 @@
namespace ProjectRepairCompany.Forms
{
partial class FormOrders
{
/// <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()
{
panel1 = new Panel();
ButtonDel = new Button();
ButtonAdd = new Button();
dataGridView = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(ButtonDel);
panel1.Controls.Add(ButtonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(1169, 0);
panel1.Name = "panel1";
panel1.Size = new Size(193, 397);
panel1.TabIndex = 2;
//
// ButtonDel
//
ButtonDel.BackgroundImage = Properties.Resources.Ic_remove_circle_48px_svg;
ButtonDel.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDel.Location = new Point(42, 188);
ButtonDel.Name = "ButtonDel";
ButtonDel.Size = new Size(117, 73);
ButtonDel.TabIndex = 1;
ButtonDel.UseVisualStyleBackColor = true;
ButtonDel.Click += ButtonDel_Click;
//
// ButtonAdd
//
ButtonAdd.BackgroundImage = Properties.Resources._43_436254_plus_green_plus_icon_png;
ButtonAdd.BackgroundImageLayout = ImageLayout.Stretch;
ButtonAdd.Location = new Point(42, 18);
ButtonAdd.Name = "ButtonAdd";
ButtonAdd.Size = new Size(117, 65);
ButtonAdd.TabIndex = 0;
ButtonAdd.UseVisualStyleBackColor = true;
ButtonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(1169, 397);
dataGridView.TabIndex = 3;
//
// FormOrders
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1362, 397);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormOrders";
Text = "Заказы";
Load += FormOrders_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonDel;
private Button ButtonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,92 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormOrders : Form
{
private readonly IUnityContainer _container;
private readonly IOrderRepository _orderRepository;
public FormOrders(IUnityContainer container, IOrderRepository orderRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_orderRepository = orderRepository ??
throw new ArgumentNullException(nameof(orderRepository));
}
private void FormOrders_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormOrder>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка добавления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_orderRepository.DeleteOrder(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _orderRepository.ReadOrders();
private bool TryGetIdentifierFromSelectRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

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

View File

@ -0,0 +1,121 @@
namespace ProjectRepairCompany.Forms
{
partial class FormStorage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
label1 = new Label();
label2 = new Label();
textBoxAdress = new TextBox();
ButtonSave = new Button();
ButtonCancel = new Button();
numericUpDownCapacity = new NumericUpDown();
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).BeginInit();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(32, 33);
label1.Name = "label1";
label1.Size = new Size(47, 17);
label1.TabIndex = 0;
label1.Text = "Адрес:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(32, 77);
label2.Name = "label2";
label2.Size = new Size(111, 17);
label2.TabIndex = 1;
label2.Text = "Вместительность:";
//
// textBoxAdress
//
textBoxAdress.Location = new Point(149, 25);
textBoxAdress.Name = "textBoxAdress";
textBoxAdress.Size = new Size(162, 25);
textBoxAdress.TabIndex = 2;
//
// ButtonSave
//
ButtonSave.Location = new Point(32, 139);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(89, 51);
ButtonSave.TabIndex = 4;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(163, 139);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(89, 51);
ButtonCancel.TabIndex = 5;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// numericUpDownCapacity
//
numericUpDownCapacity.Location = new Point(149, 69);
numericUpDownCapacity.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownCapacity.Name = "numericUpDownCapacity";
numericUpDownCapacity.Size = new Size(162, 25);
numericUpDownCapacity.TabIndex = 6;
//
// FormStorage
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(370, 253);
Controls.Add(numericUpDownCapacity);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(textBoxAdress);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormStorage";
StartPosition = FormStartPosition.CenterParent;
Text = "Склад";
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private TextBox textBoxAdress;
private Button ButtonSave;
private Button ButtonCancel;
private NumericUpDown numericUpDownCapacity;
}
}

View File

@ -0,0 +1,81 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
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 ProjectRepairCompany.Forms
{
public partial class FormStorage : Form
{
private readonly IStorageRepository _storageRepository;
private int? _storageId;
public int Id
{
set
{
try
{
var storage = _storageRepository.ReadStorageById(value);
if (storage == null)
{
throw new InvalidOperationException(nameof(storage));
}
textBoxAdress.Text = storage.StorageAddress;
numericUpDownCapacity.Value = storage.Capacity;
_storageId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormStorage(IStorageRepository storageRepository)
{
InitializeComponent();
_storageRepository = storageRepository ??
throw new ArgumentNullException(nameof(storageRepository));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxAdress.Text))
{
throw new Exception("Заполните все данные");
}
if (_storageId.HasValue)
{
_storageRepository.UpdateStorage(CreateStorage(_storageId.Value));
}
else
{
_storageRepository.CreateStorage(CreateStorage(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Storage CreateStorage(int id) => Storage.CreateEntity(id,
textBoxAdress.Text, Convert.ToInt32(numericUpDownCapacity.Value));
}
}

View File

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

View File

@ -0,0 +1,167 @@
namespace ProjectRepairCompany.Forms
{
partial class FormStorageDetail
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
ButtonSave = new Button();
ButtonCancel = new Button();
label1 = new Label();
label2 = new Label();
label3 = new Label();
numericUpDownCount = new NumericUpDown();
dateTimePickerDate = new DateTimePicker();
comboBoxAddress = new ComboBox();
label4 = new Label();
comboBoxDetail = new ComboBox();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit();
SuspendLayout();
//
// ButtonSave
//
ButtonSave.Location = new Point(44, 179);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(86, 31);
ButtonSave.TabIndex = 0;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(163, 180);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(99, 28);
ButtonCancel.TabIndex = 1;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(30, 26);
label1.Name = "label1";
label1.Size = new Size(50, 17);
label1.TabIndex = 2;
label1.Text = "Деталь";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(28, 61);
label2.Name = "label2";
label2.Size = new Size(78, 17);
label2.TabIndex = 3;
label2.Text = "Количество";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(44, 101);
label3.Name = "label3";
label3.Size = new Size(36, 17);
label3.TabIndex = 4;
label3.Text = "Дата";
//
// numericUpDownCount
//
numericUpDownCount.Location = new Point(128, 62);
numericUpDownCount.Name = "numericUpDownCount";
numericUpDownCount.Size = new Size(154, 25);
numericUpDownCount.TabIndex = 5;
//
// dateTimePickerDate
//
dateTimePickerDate.Location = new Point(119, 104);
dateTimePickerDate.Name = "dateTimePickerDate";
dateTimePickerDate.Size = new Size(187, 25);
dateTimePickerDate.TabIndex = 6;
//
// comboBoxAddress
//
comboBoxAddress.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxAddress.FormattingEnabled = true;
comboBoxAddress.Location = new Point(119, 148);
comboBoxAddress.Name = "comboBoxAddress";
comboBoxAddress.Size = new Size(183, 25);
comboBoxAddress.TabIndex = 8;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(15, 151);
label4.Name = "label4";
label4.Size = new Size(91, 17);
label4.TabIndex = 9;
label4.Text = "Адрес склада:";
//
// comboBoxDetail
//
comboBoxDetail.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxDetail.FormattingEnabled = true;
comboBoxDetail.Location = new Point(119, 23);
comboBoxDetail.Name = "comboBoxDetail";
comboBoxDetail.Size = new Size(183, 25);
comboBoxDetail.TabIndex = 10;
//
// FormStorageDetail
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(393, 283);
Controls.Add(comboBoxDetail);
Controls.Add(label4);
Controls.Add(comboBoxAddress);
Controls.Add(dateTimePickerDate);
Controls.Add(numericUpDownCount);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Name = "FormStorageDetail";
Text = "FormStorageDetail";
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonSave;
private Button ButtonCancel;
private Label label1;
private Label label2;
private Label label3;
private NumericUpDown numericUpDownCount;
private DateTimePicker dateTimePickerDate;
private ComboBox comboBoxAddress;
private Label label4;
private ComboBox comboBoxDetail;
}
}

View File

@ -0,0 +1,47 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Linq;
using System.Windows.Forms;
namespace ProjectRepairCompany.Forms
{
public partial class FormStorageDetail : Form
{
private readonly IStorageDetailRepository _storageDetailRepository;
public FormStorageDetail(IStorageDetailRepository storageDetailRepository, IDetailRepository detailRepository, IStorageRepository storageRepository)
{
InitializeComponent();
_storageDetailRepository = storageDetailRepository ?? throw new ArgumentNullException(nameof(storageDetailRepository));
comboBoxAddress.DataSource = storageRepository.ReadStorages();
comboBoxAddress.DisplayMember = "StorageAddress";
comboBoxAddress.ValueMember = "Id";
comboBoxDetail.DataSource = detailRepository.ReadDetails();
comboBoxDetail.DisplayMember = "NameDetail";
comboBoxDetail.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxDetail.SelectedIndex < 0 || comboBoxAddress.SelectedIndex < 0 || Convert.ToInt32(numericUpDownCount.Value) == 0)
{
throw new Exception("Заполни все поля");
}
_storageDetailRepository.CreateStorageDetail(StorageDetail.CreateOperation((int)comboBoxAddress.SelectedValue!, (int)comboBoxDetail.SelectedValue!, Convert.ToInt32(numericUpDownCount.Value), dateTimePickerDate.Value));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка сохранения данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
}
}

View File

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

View File

@ -0,0 +1,97 @@
namespace ProjectRepairCompany.Forms
{
partial class FormStorageDetails
{
/// <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()
{
panel1 = new Panel();
ButtonAdd = new Button();
dataGridView = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(ButtonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(607, 0);
panel1.Name = "panel1";
panel1.Size = new Size(193, 450);
panel1.TabIndex = 3;
//
// ButtonAdd
//
ButtonAdd.BackgroundImage = Properties.Resources._43_436254_plus_green_plus_icon_png;
ButtonAdd.BackgroundImageLayout = ImageLayout.Stretch;
ButtonAdd.Location = new Point(42, 20);
ButtonAdd.Name = "ButtonAdd";
ButtonAdd.Size = new Size(117, 74);
ButtonAdd.TabIndex = 0;
ButtonAdd.UseVisualStyleBackColor = true;
ButtonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(607, 450);
dataGridView.TabIndex = 4;
//
// FormStorageDetails
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormStorageDetails";
Text = "Пополнение складов";
Load += FormStorageDetail_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,71 @@
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories;
using System;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormStorageDetails : Form
{
private readonly IUnityContainer _container;
private readonly IStorageDetailRepository _storageDetailRepository;
public FormStorageDetails(IUnityContainer container, IStorageDetailRepository storageDetailRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_storageDetailRepository = storageDetailRepository ?? throw new ArgumentNullException(nameof(storageDetailRepository));
}
private void FormStorageDetail_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormStorageDetail>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка добавления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
try
{
dataGridView.DataSource = _storageDetailRepository.ReadStorageDetails();
dataGridView.Columns["SupplyDate"].DefaultCellStyle.Format = "dd.MM.yyyy hh:mm";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка загрузки данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["StorageId"].Value);
return true;
}
}
}

View File

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

View File

@ -0,0 +1,126 @@
namespace ProjectRepairCompany.Forms
{
partial class FormStorages
{
/// <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()
{
panel1 = new Panel();
ButtonUp = new Button();
ButtonDel = new Button();
ButtonAdd = new Button();
dataGridView = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(ButtonUp);
panel1.Controls.Add(ButtonDel);
panel1.Controls.Add(ButtonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(615, 0);
panel1.Name = "panel1";
panel1.Size = new Size(193, 470);
panel1.TabIndex = 0;
//
// ButtonUp
//
ButtonUp.BackgroundImage = Properties.Resources.Feedbin_Icon_home_edit_svg;
ButtonUp.BackgroundImageLayout = ImageLayout.Stretch;
ButtonUp.Location = new Point(42, 113);
ButtonUp.Name = "ButtonUp";
ButtonUp.Size = new Size(117, 77);
ButtonUp.TabIndex = 2;
ButtonUp.UseVisualStyleBackColor = true;
ButtonUp.Click += ButtonUp_Click;
//
// ButtonDel
//
ButtonDel.BackgroundImage = Properties.Resources.Ic_remove_circle_48px_svg;
ButtonDel.BackgroundImageLayout = ImageLayout.Stretch;
ButtonDel.Location = new Point(42, 213);
ButtonDel.Name = "ButtonDel";
ButtonDel.Size = new Size(117, 83);
ButtonDel.TabIndex = 1;
ButtonDel.UseVisualStyleBackColor = true;
ButtonDel.Click += ButtonDel_Click;
//
// ButtonAdd
//
ButtonAdd.BackgroundImage = Properties.Resources._43_436254_plus_green_plus_icon_png;
ButtonAdd.BackgroundImageLayout = ImageLayout.Stretch;
ButtonAdd.Location = new Point(42, 20);
ButtonAdd.Name = "ButtonAdd";
ButtonAdd.Size = new Size(117, 74);
ButtonAdd.TabIndex = 0;
ButtonAdd.UseVisualStyleBackColor = true;
ButtonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(615, 470);
dataGridView.TabIndex = 1;
//
// FormStorages
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(808, 470);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormStorages";
StartPosition = FormStartPosition.CenterParent;
Text = "Склады";
Load += FormStorages_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonUp;
private Button ButtonDel;
private Button ButtonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,111 @@
using ProjectRepairCompany.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectRepairCompany.Forms
{
public partial class FormStorages : Form
{
private readonly IUnityContainer _container;
private readonly IStorageRepository _storageRepository;
public FormStorages(IUnityContainer container, IStorageRepository storageRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_storageRepository = storageRepository ??
throw new ArgumentNullException(nameof(storageRepository));
}
private void FormStorages_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Ошибка загрузки", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormStorage>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка добавления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUp_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
try
{
var form = _container.Resolve<FormStorage>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка изменения", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectRow(out int findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_storageRepository.DeleteStorage(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() {
dataGridView.DataSource = _storageRepository.ReadStorages();
dataGridView.Columns["Id"].Visible = false;
}
private bool TryGetIdentifierFromSelectRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

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

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectRepairCompany
{
internal static class Program
@ -11,7 +19,32 @@ namespace ProjectRepairCompany
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
Application.Run(CreateContainer().Resolve<FormRepairCompany>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IDetailRepository, DetailRepository>();
container.RegisterType<IMasterRepository, MasterRepository>();
container.RegisterType<IStorageRepository, StorageRepository>();
container.RegisterType<IStorageDetailRepository, StorageDetailRepository>();
container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@ -8,4 +8,43 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="PdfSharp.MigraDoc.Standard.DocumentObjectModel" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectRepairCompany.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectRepairCompany.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap _43_436254_plus_green_plus_icon_png {
get {
object obj = ResourceManager.GetObject("43-436254_plus-green-plus-icon-png", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Feedbin_Icon_home_edit_svg {
get {
object obj = ResourceManager.GetObject("Feedbin-Icon-home-edit.svg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Ic_remove_circle_48px_svg {
get {
object obj = ResourceManager.GetObject("Ic_remove_circle_48px.svg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Снимок_экрана_2024_09_02_200407 {
get {
object obj = ResourceManager.GetObject("Снимок экрана 2024-09-02 200407", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

View File

@ -0,0 +1,53 @@
using Microsoft.Extensions.Logging;
using ProjectRepairCompany.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Reports;
public class ChartReport
{
private readonly IOrderRepository _orderRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IOrderRepository orderRepository,
ILogger<ChartReport> logger)
{
_orderRepository = orderRepository ??
throw new
ArgumentNullException(nameof(orderRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
new PdfBuilder(filePath)
.AddHeader("Заказы выполненные мастерами")
.AddPieChart($"Выполненные заказы за {dateTime:dd MMMM yyyy}", GetData(dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _orderRepository
.ReadOrders(dateForm: dateTime.Date, dateTo: dateTime.Date.AddDays(1))
.GroupBy(x => x.MasterName, (key, group) => new {
MasterName = key,
Count = group.Count()
})
.Select(x => (x.MasterName.ToString(), (double)x.Count))
.ToList();
}
}

View File

@ -0,0 +1,75 @@
using Microsoft.Extensions.Logging;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Reports;
public class DocReport
{
private readonly IStorageRepository _storageRepository;
private readonly IMasterRepository _masterRepository;
private readonly IDetailRepository _detailRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IMasterRepository masterRepository, IDetailRepository detailRepository, IStorageRepository storageRepository, ILogger<DocReport> logger)
{
_masterRepository = masterRepository
?? throw new ArgumentNullException(nameof(masterRepository));
_detailRepository = detailRepository
?? throw new ArgumentNullException(nameof(detailRepository));
_storageRepository = storageRepository
?? throw new ArgumentNullException(nameof(storageRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeMasters, bool includeDetails, bool includeStorages)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (includeMasters)
{
builder.AddParagraph("Мастера").AddTable([2400, 2400, 2400], GetMasters());
}
if (includeDetails)
{
builder.AddParagraph("Детали").AddTable([2400, 2400, 2400, 2400], GetDetails());
}
if (includeStorages)
{
builder.AddParagraph("Склады").AddTable([2400, 2400], GetStorages());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка формирования");
return false;
}
}
private List<string[]> GetMasters()
{
return [["Работник", "Должность", "Дата начала работы"],
.. _masterRepository.ReadMasters().Select(x => new string[] { x.MasterName, x.MasterPost.ToString(), x.StartDate.ToString("dd.MM.yyyy") }),
];
}
private List<string[]> GetDetails()
{
return [["Название детали", "Цена", "Число", "Свойства"],
.. _detailRepository.ReadDetails().Select(x => new string[] { x.NameDetail, x.PriceDetail.ToString("N2"), x.NumberDetail.ToString(), x.DetailProperties.ToString() }),
];
}
private List<string[]> GetStorages()
{
return [["Адрес", "Вместимость"],
.. _storageRepository.ReadStorages().Select(x => new string[] { x.StorageAddress, x.Capacity.ToString() }),
];
}
}

View File

@ -0,0 +1,330 @@
using DocumentFormat.OpenXml;
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 ProjectRepairCompany.Reports;
internal class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header,
StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "",
StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference =
new
StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text,
StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j],
StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j],
StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j],
StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath,
SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets =
spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells,
worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
// TODO добавить шрифт с жирным
// Шрифт с жирным текстом
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
Bold = new Bold(), // Жирный текст
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
// TODO добавить настройку с границами
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder()
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// TODO дополнить форматы
// Жирный текст без границ
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// Обычный текст с границами
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// Жирный текст с границами
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
// TODO дополнить стили
BoldTextWithoutBorder = 1,
SimpleTextWithBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex!
== rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null &&
c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null &&
cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value,
cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() +
columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@ -0,0 +1,80 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Reports;
public class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double
Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
var normalStyle = _document.Styles["Normal"];
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 14;
headerStyle.ParagraphFormat.Alignment = ParagraphAlignment.Center;
}
}

View File

@ -0,0 +1,89 @@
using Microsoft.Extensions.Logging;
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Repositories;
using ProjectRepairCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
namespace ProjectRepairCompany.Reports;
internal class TableReport
{
private readonly IOrderRepository _orderRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] Headers = { "Мастер", "Номер заказа", "Дата вручения заказа", "Детали и кол-во", "Итоговая стоимость" };
public TableReport(IOrderRepository orderRepository, ILogger<TableReport> logger)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int masterId, string masterName, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader($"Сводка по заказам мастера {masterName}", 1, 5)
.AddParagraph($"за период: {startDate:dd.MM.yyyy} - {endDate:dd.MM.yyyy}", 0)
.AddTable(new[] { 20, 15, 15, 20, 15 }, GetData(masterId, masterName, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int masterId, string masterName, DateTime startDate, DateTime endDate)
{
var orders = _orderRepository
.ReadOrders(startDate, endDate, masterId)
.ToList();
if (!orders.Any())
return new List<string[]> { Headers };
var detailsData = orders
.Select(order => new
{
MasterName = masterName,
OrderDate = order.DateIssue,
OrderId = order.Id,
Details = string.Join(", ", order.OrderDetails.Select(d => $"Деталь: {d.DetailName} Кол-во: {d.DetailCount}")),
FullPrice = order.FullPrice
})
.ToList();
var result = new List<string[]> { Headers };
result.AddRange(detailsData.Select(detail => new string[]
{
detail.MasterName,
detail.OrderId.ToString(),
detail.OrderDate.ToString("dd.MM.yyyy"),
detail.Details.ToString(),
detail.FullPrice.ToString()
}));
result.Add(new string[]
{
"Итого",
"",
"",
"",
detailsData.Sum(d => d.FullPrice).ToString()
});
return result;
}
}

View File

@ -0,0 +1,101 @@
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 ProjectRepairCompany.Reports;
internal class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
var runProperties = run.AppendChild(new RunProperties());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12},
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12},
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12},
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12},
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12},
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12}
)
));
//header
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
//data
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -0,0 +1,18 @@
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IDetailRepository
{
IEnumerable<Detail> ReadDetails();
Detail ReadDetailById(int id);
void CreateDetail(Detail detail);
void UpdateDetail(Detail detail);
void DeleteDetail(int id);
}

View File

@ -0,0 +1,18 @@
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IMasterRepository
{
IEnumerable<Master> ReadMasters();
Master ReadMasterById(int id);
void CreateMaster(Master master);
void UpdateMaster(Master master);
void DeleteMaster(int id);
}

View File

@ -0,0 +1,16 @@
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null);
Order ReadOrderById(int id);
void CreateOrder(Order order);
void DeleteOrder(int id);
}

View File

@ -0,0 +1,15 @@
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IStorageDetailRepository
{
IEnumerable<StorageDetail> ReadStorageDetails(DateTime? dateFrom = null, DateTime? dateTo = null, int? storageId = null,
int? detailId = null);
void CreateStorageDetail(StorageDetail storageDetail);
}

View File

@ -0,0 +1,17 @@
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories;
public interface IStorageRepository
{
IEnumerable<Storage> ReadStorages();
Storage ReadStorageById(int id);
void CreateStorage(Storage storage);
void UpdateStorage(Storage storage);
void DeleteStorage(int id);
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString =>
"Host=localhost;Port=5432;Database=otp;Username=postgres;Password=postgres";
}

View File

@ -0,0 +1,128 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories.Implementations;
public class DetailRepository : IDetailRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DetailRepository> _logger;
public DetailRepository(IConnectionString connectionString, ILogger<DetailRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateDetail(Detail detail)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(detail));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Detail (NameDetail, NumberDetail, PriceDetail, DetailProperties)
VALUES (@NameDetail, @NumberDetail, @PriceDetail, @DetailProperties)";
connection.Execute(queryInsert, detail);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления");
throw;
}
}
public void UpdateDetail(Detail detail)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(detail));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Detail
SET
NameDetail = @NameDetail,
NumberDetail = @NumberDetail,
PriceDetail = @PriceDetail,
DetailProperties = @DetailProperties
WHERE Id = @Id";
connection.Execute(queryUpdate, detail);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка редактирования");
throw;
}
}
public void DeleteDetail(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Detail
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления");
throw;
}
}
public Detail ReadDetailById(int id)
{
_logger.LogInformation("Получение по id");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Detail
WHERE Id = @id";
var detail = connection.QueryFirst<Detail>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(detail));
return detail;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка поиска");
throw;
}
}
public IEnumerable<Detail> ReadDetails()
{
_logger.LogInformation("Получение объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Detail";
var details = connection.Query<Detail>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(details));
return details;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
}

View File

@ -0,0 +1,126 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories.Implementations;
public class MasterRepository : IMasterRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<MasterRepository> _logger;
public MasterRepository(IConnectionString connectionString, ILogger<MasterRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateMaster(Master master)
{
_logger.LogInformation("Добавление обьекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(master));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Master (MasterName, StartDate, MasterPost)
VALUES (@MasterName, @StartDate, @MasterPost)";
connection.Execute(queryInsert, master);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления");
throw;
}
}
public void UpdateMaster(Master master)
{
_logger.LogInformation("Редактирование обьекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(master));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Master
SET
MasterName = @MasterName,
StartDate = @StartDate,
MasterPost = @MasterPost
WHERE Id = @Id";
connection.Execute(queryUpdate, master);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка Редактирования");
throw;
}
}
public void DeleteMaster(int id)
{
_logger.LogInformation("Удаление обьекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Master
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка Удаления");
throw;
}
}
public Master ReadMasterById(int id)
{
_logger.LogInformation("Получение по id");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Master
WHERE Id=@id";
var master = connection.QueryFirst<Master>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(master));
return master;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка поиска");
throw;
}
}
public IEnumerable<Master> ReadMasters()
{
_logger.LogInformation("Получение объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Master";
var master = connection.Query<Master>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(master));
return master;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
}

View File

@ -0,0 +1,191 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectRepairCompany.Entities;
using ProjectRepairCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
namespace ProjectRepairCompany.Repositories.Implementations;
public class OrderRepository : IOrderRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateOrder(Order order)
{
_logger.LogInformation("Добавление нового заказа.");
_logger.LogDebug("Объект заказа: {json}", JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO ""Order"" (OrderDate, DateCompletion, DateIssue, FullPrice, MasterId)
VALUES (@OrderDate, @DateCompletion, @DateIssue, @FullPrice, @MasterId)
RETURNING Id";
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
_logger.LogInformation("Новый заказ создан с Id {OrderId}", orderId);
var querySubInsert = @"
INSERT INTO OrderDetail (OrderId, DetailId, DetailCount)
VALUES (@OrderId, @DetailId, @DetailCount)";
foreach (var elem in order.OrderDetails)
{
_logger.LogDebug("Добавление детали: DetailId = {DetailId}, DetailCount = {DetailCount}",
elem.DetailId, elem.DetailCount);
connection.Execute(querySubInsert, new { orderId, elem.DetailId, elem.DetailCount }, transaction);
}
transaction.Commit();
_logger.LogInformation("Заказ с деталями успешно добавлен.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении заказа.");
throw;
}
}
public void DeleteOrder(int id)
{
_logger.LogInformation("Удаление объекта с Id {OrderId}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteDetails = "DELETE FROM OrderDetail WHERE OrderId = @OrderId";
connection.Execute(queryDeleteDetails, new { OrderId = id }, transaction);
var queryDeleteOrder = "DELETE FROM \"Order\" WHERE Id = @Id";
connection.Execute(queryDeleteOrder, new { Id = id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении");
throw;
}
}
public Order ReadOrderById(int id)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM ""Order"" WHERE Id = @id";
var orders = connection.QueryFirst<Order>(querySelect, new {id});
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
public IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (masterId.HasValue)
{
builder.AddCondition("o.MasterId = @masterId");
}
if (dateForm.HasValue)
{
builder.AddCondition("o.DateIssue >= @dateForm");
}
if (dateTo.HasValue)
{
builder.AddCondition("o.DateIssue <= @dateTo");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @$"
SELECT
o.Id AS Id,
o.OrderDate,
o.DateCompletion,
o.DateIssue,
o.FullPrice,
o.MasterId,
m.MasterName AS MasterName,
od.DetailId,
od.DetailCount,
d.namedetail AS DetailName
FROM ""Order"" o
LEFT JOIN OrderDetail od ON o.Id = od.OrderId
LEFT JOIN Detail d ON d.Id = od.DetailId
LEFT JOIN Master m ON m.Id = o.MasterId
{builder.Build()}
ORDER BY o.DateIssue";
var orderDict = new Dictionary<int, Order>();
connection.Query<Order, OrderDetail, Order>(querySelect,
(order, orderDetail) =>
{
if (!orderDict.TryGetValue(order.Id, out var existingOrder))
{
existingOrder = order;
existingOrder.OrderDetails = new List<OrderDetail>();
orderDict.Add(existingOrder.Id, existingOrder);
}
if (orderDetail != null)
{
((List<OrderDetail>)existingOrder.OrderDetails).Add(orderDetail);
}
return existingOrder;
},
splitOn: "DetailId",
param: new { dateForm, dateTo, masterId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orderDict.Values));
return orderDict.Values.ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories.Implementations;
internal class QueryBuilder
{
private readonly StringBuilder _builder;
public QueryBuilder()
{
_builder = new();
}
public QueryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
{
_builder.Append(" AND ");
}
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
{
return string.Empty;
}
return $"WHERE {_builder}";
}
}

View File

@ -0,0 +1,70 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
namespace ProjectRepairCompany.Repositories.Implementations;
public class StorageDetailRepository : IStorageDetailRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StorageDetailRepository> _logger;
public StorageDetailRepository(IConnectionString connectionString, ILogger<StorageDetailRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStorageDetail(StorageDetail storageDetail)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(storageDetail));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO StorageDetail (StorageId, DetailId, DetailCount, SupplyDate)
VALUES (@StorageId, @DetailId, @DetailCount, @SupplyDate)";
connection.Execute(queryInsert, storageDetail);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления");
throw;
}
}
public IEnumerable<StorageDetail> ReadStorageDetails(DateTime? dateFrom = null, DateTime? dateTo = null, int? storageId = null, int? detailId = null)
{
_logger.LogInformation("Получение объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT
sd.*,
s.StorageAddress as ""StorageAddress"",
d.NameDetail as ""DetailName""
FROM StorageDetail sd
LEFT JOIN Storage s ON s.Id = sd.StorageId
LEFT JOIN Detail d ON d.Id = sd.DetailId
WHERE (@storageId IS NULL OR sd.StorageId = @storageId)
AND (@detailId IS NULL OR sd.DetailId = @detailId)";
var storageDetails = connection.Query<StorageDetail>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(storageDetails));
return storageDetails;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
}

View File

@ -0,0 +1,122 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectRepairCompany.Entities;
using System;
using System.Collections.Generic;
using Npgsql;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRepairCompany.Repositories.Implementations;
public class StorageRepository : IStorageRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StorageRepository> _logger;
public StorageRepository(IConnectionString connectionString, ILogger<StorageRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStorage(Storage storage)
{
_logger.LogInformation("Добавление обьекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(storage));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Storage (StorageAddress, Capacity)
VALUES (@StorageAddress, @Capacity)";
connection.Execute(queryInsert, storage);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления");
throw;
}
}
public void UpdateStorage(Storage storage)
{
_logger.LogInformation("Редактирование обьекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(storage));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Storage
SET
StorageAddress = @StorageAddress,
Capacity = @Capacity
WHERE Id = @Id";
connection.Execute(queryUpdate, storage);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка Редактирования");
throw;
}
}
public void DeleteStorage(int id)
{
_logger.LogInformation("Удаление обьекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Storage
WHERE Id=@id";
connection.Execute(queryDelete, new {id});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка Удаления");
throw;
}
}
public Storage ReadStorageById(int id)
{
_logger.LogInformation("Получение по id");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Storage
WHERE Id=@id";
var storage = connection.QueryFirst<Storage>(querySelect, new {id});
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(storage));
return storage;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка поиска");
throw;
}
}
public IEnumerable<Storage> ReadStorages()
{
_logger.LogInformation("Получение объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Storage";
var storage = connection.Query<Storage>(querySelect).ToList();
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(storage));
return storage;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 474 KiB

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logo/repairCompany_log.txt",
"rollingInterval": "Day"
}
}
]
}
}

BIN
ИконкаМинус.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
ИконкаПлюс.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB