Compare commits

...

4 Commits
main ... Lab03

Author SHA1 Message Date
aec9869fd5 УЛЬТРАМЕГАКОММИТ 3.0. Снизить баллы за 30 изменений. во 2 лабе CR и CRD в операциях местами попутал. Потому и. И так у них всегда 2024-12-20 01:38:50 +04:00
c7a8b337e7 МЕГА КОММИТ 2.0. Подписаться 2024-12-20 01:12:17 +04:00
sa
78706eac6f В товарах выпадающий список магазинов, а не ID
Магазины при загрузке формы теперь прогружаются (Load += в дизайнере).
AutoResizeColumn - Fill для дизайнеров форм
2024-12-03 12:56:36 +03:00
sa
b379829b47 Мега большой коммит всей фазы 2024-12-03 00:17:56 +03:00
81 changed files with 6537 additions and 78 deletions

View File

@ -0,0 +1,16 @@
namespace ProjectOpticsStore.Entities;
public class Customer
{
public int Id { get; private set; }
public string FullName { get; private set; } = string.Empty;
public static Customer CreateEntity(int id, string fullName)
{
return new Customer
{
Id = id,
FullName = fullName ?? string.Empty
};
}
}

View File

@ -0,0 +1,10 @@
namespace ProjectOpticsStore.Entities.Enums;
public enum OrderStatusEnum
{
None = 0,
Pending = 1,
Completed = 2,
Canceled = 3,
InProgress = 4
}

View File

@ -0,0 +1,13 @@
namespace ProjectOpticsStore.Entities.Enums;
[Flags]
public enum ProductTypeEnum
{
None = 0,
Glasses = 1,
ContactLenses = 2,
Sunglasses = 4,
Frame = 8,
Cases = 16
}

View File

@ -0,0 +1,39 @@
using Newtonsoft.Json;
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Entities.Enums;
public class Order
{
public int Id { get; private set; }
public int CustomerId { get; private set; }
public DateTime DateCreated { get; private set; }
public OrderStatusEnum Status { get; private set; } = OrderStatusEnum.Pending;
// Коллекция, описывающая связь "Order_Product"
[JsonIgnore] public IEnumerable<Order_Product> OrderProducts { get; private set; } = new List<Order_Product>();
public static Order CreateOperation(int id, int customerId, IEnumerable<Order_Product> orderProducts, OrderStatusEnum status = OrderStatusEnum.Pending)
{
return new Order
{
Id = id,
CustomerId = customerId,
DateCreated = DateTime.Now,
Status = status,
OrderProducts = orderProducts
};
}
public static Order CreateOperation(TempOrderProduct tempOrderProduct, IEnumerable<Order_Product> orderProducts)
{
return new Order
{
Id = tempOrderProduct.Id,
CustomerId = tempOrderProduct.CustomerId,
DateCreated = tempOrderProduct.DateCreated,
Status = tempOrderProduct.Status,
OrderProducts = orderProducts
};
}
}

View File

@ -0,0 +1,20 @@
namespace ProjectOpticsStore.Entities;
public class Order_Product
{
public int OrderId { get; private set; }
public int ProductId { get; private set; }
public int Quantity { get; private set; }
// Создание элемента связи
public static Order_Product CreateElement(int orderId, int productId, int quantity)
{
return new Order_Product
{
OrderId = orderId,
ProductId = productId,
Quantity = quantity
};
}
}

View File

@ -0,0 +1,26 @@
using ProjectOpticsStore.Entities.Enums;
public class Product
{
public int Id { get; private set; }
public ProductTypeEnum Type { get; private set; }
public double Power { get; private set; }
public int Price { get; private set; }
public int Store { get; private set; }
public float Thickness { get; private set; }
public string Disease { get; private set; } = string.Empty;
public static Product CreateEntity(int id, ProductTypeEnum type, double power, int price, int store, float thickness, string disease)
{
return new Product
{
Id = id,
Type = type,
Power = power,
Price = price,
Store = store,
Thickness = thickness,
Disease = disease ?? string.Empty
};
}
}

View File

@ -0,0 +1,16 @@
namespace ProjectOpticsStore.Entities;
public class Store
{
public int Id { get; private set; }
public string Address { get; private set; } = string.Empty;
public static Store CreateEntity(int id, string address)
{
return new Store
{
Id = id,
Address = address ?? string.Empty
};
}
}

View File

@ -0,0 +1,23 @@
namespace ProjectOpticsStore.Entities;
public class Supply
{
public int Id { get; private set; }
public int StoreId { get; private set; }
public DateTime OperationDate { get; private set; }
public int ProductId { get; private set; } // Связь многие-к-одному с товарами
public int Quantity { get; private set; } // Количество поставленного товара
public static Supply CreateOperation(int id, int storeId, int productId, int quantity)
{
return new Supply
{
Id = id,
StoreId = storeId,
OperationDate = DateTime.Now,
ProductId = productId,
Quantity = quantity
};
}
}

View File

@ -0,0 +1,16 @@
using ProjectOpticsStore.Entities.Enums;
namespace ProjectOpticsStore.Entities;
public class TempOrderProduct
{
public int Id { get; private set; }
public int CustomerId { get; private set; }
public DateTime DateCreated { get; private set; }
public OrderStatusEnum Status { get; private set; }
public int OrderId { get; private set; }
public int ProductId { get; private set; }
public int Quantity { get; private set; }
}

View File

@ -1,39 +0,0 @@
namespace ProjectOpticsStore
{
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 ProjectOpticsStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,171 @@
namespace ProjectOpticsStore
{
partial class FormOpticsStore
{
/// <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();
товарыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
заказчикиToolStripMenuItem = new ToolStripMenuItem();
операцииToolStripMenuItem = new ToolStripMenuItem();
поставкаToolStripMenuItem = new ToolStripMenuItem();
заказатьToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
productReportToolStripMenuItem = new ToolStripMenuItem();
ProductDistributionToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
menuStrip1.Size = new Size(700, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { товарыToolStripMenuItem, магазиныToolStripMenuItem, заказчикиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
//
// товарыToolStripMenuItem
//
товарыToolStripMenuItem.Name = оварыToolStripMenuItem";
товарыToolStripMenuItem.Size = new Size(131, 22);
товарыToolStripMenuItem.Text = "Товары";
товарыToolStripMenuItem.Click += ProductsToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(131, 22);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += StoresToolStripMenuItem_Click;
//
// заказчикиToolStripMenuItem
//
заказчикиToolStripMenuItem.Name = аказчикиToolStripMenuItem";
заказчикиToolStripMenuItem.Size = new Size(131, 22);
заказчикиToolStripMenuItem.Text = "Заказчики";
заказчикиToolStripMenuItem.Click += CustomersToolStripMenuItem_Click;
//
// операцииToolStripMenuItem
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { поставкаToolStripMenuItem, заказатьToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(75, 20);
операцииToolStripMenuItem.Text = "Операции";
//
// поставкаToolStripMenuItem
//
поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem";
поставкаToolStripMenuItem.Size = new Size(131, 22);
поставкаToolStripMenuItem.Text = "Поставить";
поставкаToolStripMenuItem.Click += SupplyToolStripMenuItem_Click;
//
// заказатьToolStripMenuItem
//
заказатьToolStripMenuItem.Name = аказатьToolStripMenuItem";
заказатьToolStripMenuItem.Size = new Size(131, 22);
заказатьToolStripMenuItem.Text = "Заказать";
заказатьToolStripMenuItem.Click += OrderToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, productReportToolStripMenuItem, ProductDistributionToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
DirectoryReportToolStripMenuItem.Size = new Size(280, 22);
DirectoryReportToolStripMenuItem.Text = "Документ со справочниками";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// productReportToolStripMenuItem
//
productReportToolStripMenuItem.Name = "productReportToolStripMenuItem";
productReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
productReportToolStripMenuItem.Size = new Size(280, 22);
productReportToolStripMenuItem.Text = "Движение товаров";
productReportToolStripMenuItem.Click += productReportToolStripMenuItem_Click;
//
// ProductDistributionToolStripMenuItem
//
ProductDistributionToolStripMenuItem.Name = "ProductDistributionToolStripMenuItem";
ProductDistributionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
ProductDistributionToolStripMenuItem.Size = new Size(280, 22);
ProductDistributionToolStripMenuItem.Text = "Распределение товаров";
ProductDistributionToolStripMenuItem.Click += ProductDistributionToolStripMenuItem_Click;
//
// FormOpticsStore
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.catwithglasses;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(700, 338);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(3, 2, 3, 2);
Name = "FormOpticsStore";
StartPosition = FormStartPosition.CenterScreen;
Text = "Салон Оптики";
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem операцииToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem товарыToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem заказчикиToolStripMenuItem;
private ToolStripMenuItem поставкаToolStripMenuItem;
private ToolStripMenuItem заказатьToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem productReportToolStripMenuItem;
private ToolStripMenuItem ProductDistributionToolStripMenuItem;
}
}

View File

@ -0,0 +1,119 @@
using ProjectOpticsStore.Forms;
using Unity;
namespace ProjectOpticsStore;
public partial class FormOpticsStore : Form
{
private readonly IUnityContainer _container;
public FormOpticsStore(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
// Îáðàáîò÷èê äëÿ ñïðàâî÷íèêîâ
private void ProductsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProducts>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå òàê íàçûâàåìûõ òîâàðîâ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void StoresToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormStores>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå òàê íàçûâàåìûõ ìàãàçèíîâ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CustomersToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormCustomers>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå òàê íàçûâàåìûõ ïîêóïàòåëåé", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Îáðàáîò÷èê äëÿ îïåðàöèé
private void SupplyToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormSupplies>().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 DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå ïðåìîãà îò÷åòà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void productReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProductReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå îò÷åòà ÷åâî íåñåò âîîáùå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ProductDistributionToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormSupplyDistributionReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå îò÷åòà ÷åâî íåñåò âîîáùå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
}

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,97 @@
namespace ProjectOpticsStore.Forms
{
partial class FormCustomer
{
/// <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()
{
textBoxFullName = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
labelFullName = new Label();
SuspendLayout();
//
// textBoxFullName
//
textBoxFullName.Location = new Point(209, 45);
textBoxFullName.Name = "textBoxFullName";
textBoxFullName.Size = new Size(295, 27);
textBoxFullName.TabIndex = 0;
//
// buttonSave
//
buttonSave.Location = new Point(28, 240);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(124, 40);
buttonSave.TabIndex = 1;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(209, 240);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(124, 40);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelFullName
//
labelFullName.AutoSize = true;
labelFullName.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
labelFullName.Location = new Point(28, 41);
labelFullName.Name = "labelFullName";
labelFullName.Size = new Size(153, 28);
labelFullName.TabIndex = 3;
labelFullName.Text = "ФИО заказчика";
//
// FormCustomer
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(527, 306);
Controls.Add(labelFullName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxFullName);
Name = "FormCustomer";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказчик";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxFullName;
private Button buttonSave;
private Button buttonCancel;
private Label labelFullName;
}
}

View File

@ -0,0 +1,72 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormCustomer : Form
{
private readonly ICustomerRepository _customerRepository;
private int? _customerId;
// Конструктор принимает экземпляр ICustomerRepository
public FormCustomer(ICustomerRepository customerRepository)
{
InitializeComponent();
_customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
}
public int Id
{
set
{
try
{
var customer = _customerRepository.ReadCustomerById(value);
if (customer == null)
{
throw new InvalidDataException(nameof(customer));
}
textBoxFullName.Text = customer.FullName;
_customerId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFullName.Text))
{
throw new Exception("Имеются незаполненные поля");
}
if (_customerId.HasValue)
{
// Если редактируем существующего клиента
_customerRepository.UpdateCustomer(CreateCustomer(_customerId.Value));
}
else
{
// Если создаем нового клиента
_customerRepository.CreateCustomer(CreateCustomer(0));
}
Close(); // Закрываем форму после сохранения
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
// Метод для создания объекта Customer
private Customer CreateCustomer(int id) => Customer.CreateEntity(id, textBoxFullName.Text);
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
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,130 @@
namespace ProjectOpticsStore.Forms
{
partial class FormCustomers
{
/// <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()
{
panelButtons = new Panel();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panelButtons
//
panelButtons.Controls.Add(buttonDel);
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 1;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.Margin = new Padding(3, 2, 3, 2);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 51;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(569, 338);
dataGridViewData.TabIndex = 2;
//
// FormCustomers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewData);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormCustomers";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказчики";
Load += FormCustomers_Load;
panelButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelButtons;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,100 @@
using ProjectOpticsStore.Repositories;
using Unity;
namespace ProjectOpticsStore.Forms;
public partial class FormCustomers : Form
{
private readonly IUnityContainer _container;
private readonly ICustomerRepository _customerRepository;
public FormCustomers(IUnityContainer container, ICustomerRepository customerRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
}
private void FormCustomers_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<FormCustomer>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormCustomer>();
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 (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_customerRepository.DeleteCustomer(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewData.DataSource = _customerRepository.ReadCustomers();
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.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 ProjectOpticsStore.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()
{
checkBoxCustomers = new CheckBox();
checkBoxStores = new CheckBox();
checkBoxProducts = new CheckBox();
buttonCreate = new Button();
SuspendLayout();
//
// checkBoxCustomers
//
checkBoxCustomers.AutoSize = true;
checkBoxCustomers.Location = new Point(42, 28);
checkBoxCustomers.Name = "checkBoxCustomers";
checkBoxCustomers.Size = new Size(83, 19);
checkBoxCustomers.TabIndex = 0;
checkBoxCustomers.Text = "Заказчики";
checkBoxCustomers.UseVisualStyleBackColor = true;
//
// checkBoxStores
//
checkBoxStores.AutoSize = true;
checkBoxStores.Location = new Point(42, 78);
checkBoxStores.Name = "checkBoxStores";
checkBoxStores.Size = new Size(82, 19);
checkBoxStores.TabIndex = 1;
checkBoxStores.Text = "Магазины";
checkBoxStores.UseVisualStyleBackColor = true;
//
// checkBoxProducts
//
checkBoxProducts.AutoSize = true;
checkBoxProducts.Location = new Point(42, 127);
checkBoxProducts.Name = "checkBoxProducts";
checkBoxProducts.Size = new Size(67, 19);
checkBoxProducts.TabIndex = 2;
checkBoxProducts.Text = "Товары";
checkBoxProducts.UseVisualStyleBackColor = true;
//
// buttonCreate
//
buttonCreate.Location = new Point(233, 49);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(123, 74);
buttonCreate.TabIndex = 3;
buttonCreate.Text = "Определенным образом сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(398, 181);
Controls.Add(buttonCreate);
Controls.Add(checkBoxProducts);
Controls.Add(checkBoxStores);
Controls.Add(checkBoxCustomers);
Name = "FormDirectoryReport";
StartPosition = FormStartPosition.CenterParent;
Text = "FormDirectoryReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxCustomers;
private CheckBox checkBoxStores;
private CheckBox checkBoxProducts;
private Button buttonCreate;
}
}

View File

@ -0,0 +1,48 @@
using ProjectOpticsStore.Reports;
using Unity;
namespace ProjectOpticsStore.Forms;
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void buttonCreate_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxCustomers.Checked && !checkBoxStores.Checked && !checkBoxProducts.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, checkBoxCustomers.Checked,
checkBoxStores.Checked, checkBoxProducts.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,173 @@
namespace ProjectOpticsStore.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();
comboBoxCustomer = new ComboBox();
label1 = new Label();
label2 = new Label();
dateTimePickerOrderDate = new DateTimePicker();
label3 = new Label();
comboBoxStatus = new ComboBox();
dataGridViewProducts = new DataGridView();
groupBox1 = new GroupBox();
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit();
groupBox1.SuspendLayout();
SuspendLayout();
//
// ButtonSave
//
ButtonSave.Location = new Point(32, 499);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(133, 45);
ButtonSave.TabIndex = 6;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(291, 499);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(133, 45);
ButtonCancel.TabIndex = 7;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// comboBoxCustomer
//
comboBoxCustomer.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxCustomer.FormattingEnabled = true;
comboBoxCustomer.Location = new Point(139, 12);
comboBoxCustomer.Name = "comboBoxCustomer";
comboBoxCustomer.Size = new Size(288, 28);
comboBoxCustomer.TabIndex = 8;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(29, 15);
label1.Name = "label1";
label1.Size = new Size(71, 20);
label1.TabIndex = 9;
label1.Text = "Заказчик";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(29, 73);
label2.Name = "label2";
label2.Size = new Size(86, 20);
label2.TabIndex = 10;
label2.Text = "ДатаВремя";
//
// dateTimePickerOrderDate
//
dateTimePickerOrderDate.Enabled = false;
dateTimePickerOrderDate.Location = new Point(139, 68);
dateTimePickerOrderDate.Name = "dateTimePickerOrderDate";
dateTimePickerOrderDate.Size = new Size(288, 27);
dateTimePickerOrderDate.TabIndex = 11;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(29, 128);
label3.Name = "label3";
label3.Size = new Size(52, 20);
label3.TabIndex = 12;
label3.Text = "Статус";
//
// comboBoxStatus
//
comboBoxStatus.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStatus.FormattingEnabled = true;
comboBoxStatus.Location = new Point(139, 125);
comboBoxStatus.Name = "comboBoxStatus";
comboBoxStatus.Size = new Size(288, 28);
comboBoxStatus.TabIndex = 13;
//
// dataGridViewProducts
//
dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProducts.Dock = DockStyle.Fill;
dataGridViewProducts.Location = new Point(3, 23);
dataGridViewProducts.Name = "dataGridViewProducts";
dataGridViewProducts.RowHeadersVisible = false;
dataGridViewProducts.RowHeadersWidth = 51;
dataGridViewProducts.Size = new Size(392, 236);
dataGridViewProducts.TabIndex = 14;
//
// groupBox1
//
groupBox1.Controls.Add(dataGridViewProducts);
groupBox1.Location = new Point(29, 191);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(398, 262);
groupBox1.TabIndex = 15;
groupBox1.TabStop = false;
groupBox1.Text = "Заказы";
//
// FormOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(455, 569);
Controls.Add(groupBox1);
Controls.Add(comboBoxStatus);
Controls.Add(label3);
Controls.Add(dateTimePickerOrderDate);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(comboBoxCustomer);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Name = "FormOrder";
Text = "Заказать товары";
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit();
groupBox1.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonSave;
private Button ButtonCancel;
private ComboBox comboBoxCustomer;
private Label label1;
private Label label2;
private DateTimePicker dateTimePickerOrderDate;
private Label label3;
private ComboBox comboBoxStatus;
private DataGridView dataGridViewProducts;
private GroupBox groupBox1;
}
}

View File

@ -0,0 +1,127 @@
using ProjectOpticsStore.Entities.Enums;
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
using DocumentFormat.OpenXml.Drawing.Charts;
namespace ProjectOpticsStore.Forms;
public partial class FormOrder : Form
{
private readonly IOrderRepository _orderRepository;
private readonly ICustomerRepository _customerRepository;
private readonly IProductRepository _productRepository;
public FormOrder(IOrderRepository orderRepository, ICustomerRepository customerRepository, IProductRepository productRepository)
{
InitializeComponent();
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
// Настройка ComboBox для выбора клиента
comboBoxCustomer.DataSource = _customerRepository.ReadCustomers()
.Select(c => new { c.Id })
.ToList();
comboBoxCustomer.DisplayMember = "Id";
comboBoxCustomer.ValueMember = "Id";
comboBoxCustomer.DropDownStyle = ComboBoxStyle.DropDownList;
// Настройка ComboBox для выбора статуса заказа
comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatusEnum));
comboBoxStatus.DropDownStyle = ComboBoxStyle.DropDownList;
dataGridViewProducts.AllowUserToAddRows = true;
dataGridViewProducts.AllowUserToDeleteRows = true;
// Настройка таблицы товаров
InitializeDataGridViewProducts();
// Настройка DateTimePicker для даты заказа
dateTimePickerOrderDate.Value = DateTime.Now;
dateTimePickerOrderDate.Enabled = false;
}
private void InitializeDataGridViewProducts()
{
// Отключаем авто-генерацию столбцов
dataGridViewProducts.AutoGenerateColumns = false;
// Устанавливаем режим авторазмера столбцов
dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
// Столбец "Товар"
var productColumn = new DataGridViewComboBoxColumn
{
Name = "ColumnProduct",
HeaderText = "Товар",
DataSource = _productRepository.ReadProducts()
.Select(p => new { p.Id, p.Type }) // Пример данных: Id и Name
.ToList(),
DisplayMember = "Type",
ValueMember = "Id",
FlatStyle = FlatStyle.Flat
};
dataGridViewProducts.Columns.Add(productColumn);
// Столбец "Количество"
var quantityColumn = new DataGridViewTextBoxColumn
{
Name = "ColumnQuantity",
HeaderText = "Количество",
ValueType = typeof(int)
};
dataGridViewProducts.Columns.Add(quantityColumn);
productColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
quantityColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(comboBoxCustomer.Text) || comboBoxStatus.SelectedItem == null || dataGridViewProducts.RowCount < 1)
{
throw new Exception("Имеются незаполненные поля");
}
var customerId = (int)comboBoxCustomer.SelectedValue!;
var status = (OrderStatusEnum)comboBoxStatus.SelectedItem!;
var orderProducts = CreateOrderProductsFromDataGrid();
var order = Order.CreateOperation(0, customerId, orderProducts, status);
_orderRepository.CreateOrder(order);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private List<Order_Product> CreateOrderProductsFromDataGrid()
{
var list = new List<Order_Product>();
foreach (DataGridViewRow row in dataGridViewProducts.Rows)
{
// Пропускаем строку, если не указаны значения для продукта или количества
if (row.Cells["ColumnProduct"].Value == null || row.Cells["ColumnQuantity"].Value == null)
continue;
list.Add(Order_Product.CreateElement(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value),
Convert.ToInt32(row.Cells["ColumnQuantity"].Value)));
}
return list.GroupBy(x => x.ProductId, x => x.Quantity, (id, quantity) =>
Order_Product.CreateElement(0, id, quantity.Sum())).ToList();
}
}

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,99 @@
namespace ProjectOpticsStore.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()
{
panelButtons = new Panel();
buttonAdd = new Button();
dataGridViewOrders = new DataGridView();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewOrders).BeginInit();
SuspendLayout();
//
// panelButtons
//
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 2;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewOrders
//
dataGridViewOrders.AllowUserToAddRows = false;
dataGridViewOrders.AllowUserToDeleteRows = false;
dataGridViewOrders.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewOrders.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewOrders.Dock = DockStyle.Fill;
dataGridViewOrders.Location = new Point(0, 0);
dataGridViewOrders.Margin = new Padding(3, 2, 3, 2);
dataGridViewOrders.MultiSelect = false;
dataGridViewOrders.Name = "dataGridViewOrders";
dataGridViewOrders.ReadOnly = true;
dataGridViewOrders.RowHeadersVisible = false;
dataGridViewOrders.RowHeadersWidth = 51;
dataGridViewOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewOrders.Size = new Size(569, 338);
dataGridViewOrders.TabIndex = 3;
//
// FormOrders
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewOrders);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormOrders";
Text = "Заказать товары";
Load += FormOrders_Load;
panelButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewOrders).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelButtons;
private Button buttonAdd;
private DataGridView dataGridViewOrders;
}
}

View File

@ -0,0 +1,73 @@
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormOrders : Form
{
private readonly IOrderRepository _orderRepository;
private readonly ICustomerRepository _customerRepository;
private readonly IProductRepository _productRepository;
public FormOrders(IOrderRepository orderRepository, ICustomerRepository customerRepository, IProductRepository productRepository)
{
InitializeComponent();
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
}
// Загрузка списка заказов при загрузке формы
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
{
// Передаем все три зависимости в конструктор FormOrder
using (var form = new FormOrder(_orderRepository, _customerRepository, _productRepository))
{
form.ShowDialog();
}
LoadList(); // Перезагружаем список после добавления
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Метод для загрузки списка заказов в DataGridView
private void LoadList()
{
dataGridViewOrders.DataSource = _orderRepository.ReadOrders();
//if (dataGridViewOrders.Columns.Contains("OrderProducts"))
//{
// dataGridViewOrders.Columns["OrderProducts"].Visible = false;
//}
}
// Метод для получения идентификатора заказа из выбранной строки в DataGridView
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewOrders.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewOrders.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,209 @@
namespace ProjectOpticsStore.Forms
{
partial class FormProduct
{
/// <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();
checkedListBoxProductType = new CheckedListBox();
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
label5 = new Label();
label6 = new Label();
textBoxPower = new TextBox();
textBoxPrice = new TextBox();
textBoxThickness = new TextBox();
textBoxDisease = new TextBox();
comboBoxStore = new ComboBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Location = new Point(32, 493);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(124, 40);
buttonSave.TabIndex = 2;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(201, 493);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(124, 40);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// checkedListBoxProductType
//
checkedListBoxProductType.FormattingEnabled = true;
checkedListBoxProductType.Location = new Point(157, 22);
checkedListBoxProductType.Name = "checkedListBoxProductType";
checkedListBoxProductType.Size = new Size(254, 114);
checkedListBoxProductType.TabIndex = 4;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(32, 22);
label1.Name = "label1";
label1.Size = new Size(90, 20);
label1.TabIndex = 5;
label1.Text = "Тип товара:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(32, 171);
label2.Name = "label2";
label2.Size = new Size(85, 20);
label2.TabIndex = 6;
label2.Text = "Мощность:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(32, 227);
label3.Name = "label3";
label3.Size = new Size(48, 20);
label3.TabIndex = 7;
label3.Text = "Цена:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(32, 287);
label4.Name = "label4";
label4.Size = new Size(72, 20);
label4.TabIndex = 8;
label4.Text = "Магазин:";
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(32, 352);
label5.Name = "label5";
label5.Size = new Size(122, 20);
label5.TabIndex = 9;
label5.Text = "Толщина (чево):";
//
// label6
//
label6.AutoSize = true;
label6.Location = new Point(32, 406);
label6.Name = "label6";
label6.Size = new Size(70, 20);
label6.TabIndex = 10;
label6.Text = "Болезнь:";
//
// textBoxPower
//
textBoxPower.Location = new Point(157, 168);
textBoxPower.Name = "textBoxPower";
textBoxPower.Size = new Size(254, 27);
textBoxPower.TabIndex = 11;
//
// textBoxPrice
//
textBoxPrice.Location = new Point(157, 224);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.Size = new Size(254, 27);
textBoxPrice.TabIndex = 12;
//
// textBoxThickness
//
textBoxThickness.Location = new Point(157, 349);
textBoxThickness.Name = "textBoxThickness";
textBoxThickness.Size = new Size(254, 27);
textBoxThickness.TabIndex = 14;
//
// textBoxDisease
//
textBoxDisease.Location = new Point(157, 406);
textBoxDisease.Multiline = true;
textBoxDisease.Name = "textBoxDisease";
textBoxDisease.Size = new Size(254, 67);
textBoxDisease.TabIndex = 15;
//
// comboBoxStore
//
comboBoxStore.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStore.FormattingEnabled = true;
comboBoxStore.Location = new Point(157, 287);
comboBoxStore.Name = "comboBoxStore";
comboBoxStore.Size = new Size(254, 28);
comboBoxStore.TabIndex = 16;
//
// FormProduct
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(436, 545);
Controls.Add(comboBoxStore);
Controls.Add(textBoxDisease);
Controls.Add(textBoxThickness);
Controls.Add(textBoxPrice);
Controls.Add(textBoxPower);
Controls.Add(label6);
Controls.Add(label5);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(checkedListBoxProductType);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormProduct";
Text = "Так называемые товары";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private CheckedListBox checkedListBoxProductType;
private Label label1;
private Label label2;
private Label label3;
private Label label4;
private Label label5;
private Label label6;
private TextBox textBoxPower;
private TextBox textBoxPrice;
private TextBox textBoxThickness;
private TextBox textBoxDisease;
private ComboBox comboBoxStore;
}
}

View File

@ -0,0 +1,127 @@
using ProjectOpticsStore.Entities.Enums;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormProduct : Form
{
private readonly IProductRepository _productRepository;
private readonly IStoreRepository _storeRepository;
private int? _productId;
public int Id
{
set
{
try
{
// Загрузка данных продукта
var product = _productRepository.ReadProductById(value);
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
// Заполнение значений CheckedListBox
foreach (ProductTypeEnum elem in Enum.GetValues(typeof(ProductTypeEnum)))
{
if ((elem & product.Type) != 0)
{
checkedListBoxProductType.SetItemChecked(
checkedListBoxProductType.Items.IndexOf(elem), true);
}
}
// Заполнение текстовых полей
textBoxPower.Text = product.Power.ToString();
textBoxPrice.Text = product.Price.ToString();
comboBoxStore.SelectedValue = product.Store;
textBoxThickness.Text = product.Thickness.ToString("F2");
textBoxDisease.Text = product.Disease;
_productId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormProduct(IProductRepository productRepository, IStoreRepository storeRepository)
{
InitializeComponent();
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
// Инициализация CheckedListBox значениями перечисления
foreach (var elem in Enum.GetValues(typeof(ProductTypeEnum)))
{
checkedListBoxProductType.Items.Add(elem);
}
// Инициализация ComboBox для магазинов
comboBoxStore.DataSource = _storeRepository.ReadStores().ToList();
comboBoxStore.DisplayMember = "Address"; // Отображаем адрес магазина
comboBoxStore.ValueMember = "Id"; // Значение это идентификатор магазина
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
// Проверка на заполненность всех обязательных полей
if (checkedListBoxProductType.CheckedItems.Count == 0 ||
string.IsNullOrWhiteSpace(textBoxPower.Text) ||
string.IsNullOrWhiteSpace(textBoxPrice.Text) ||
comboBoxStore.SelectedValue == null ||
string.IsNullOrWhiteSpace(textBoxThickness.Text))
{
throw new Exception("Имеются незаполненные поля.");
}
// Сохранение данных
if (_productId.HasValue)
{
_productRepository.UpdateProduct(CreateProduct(_productId.Value));
}
else
{
_productRepository.CreateProduct(CreateProduct(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Product CreateProduct(int id)
{
// Сбор значений из CheckedListBox
ProductTypeEnum productType = ProductTypeEnum.None;
foreach (var elem in checkedListBoxProductType.CheckedItems)
{
productType |= (ProductTypeEnum)elem;
}
// Получение идентификатора магазина из ComboBox (это целое число)
int storeId = (int)comboBoxStore.SelectedValue!;
// Создание сущности Product
return Product.CreateEntity(
id,
productType,
double.Parse(textBoxPower.Text),
int.Parse(textBoxPrice.Text),
storeId, // Передаем идентификатор магазина, а не адрес
float.Parse(textBoxThickness.Text),
textBoxDisease.Text
);
}
}

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 ProjectOpticsStore.Forms
{
partial class FormProductReport
{
/// <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()
{
dateTimePickerStartDate = new DateTimePicker();
dateTimePickerEndDate = new DateTimePicker();
label1 = new Label();
label2 = new Label();
buttonMakeReport = new Button();
comboBoxProducts = new ComboBox();
label3 = new Label();
label4 = new Label();
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
SuspendLayout();
//
// dateTimePickerStartDate
//
dateTimePickerStartDate.Location = new Point(141, 163);
dateTimePickerStartDate.Name = "dateTimePickerStartDate";
dateTimePickerStartDate.Size = new Size(200, 23);
dateTimePickerStartDate.TabIndex = 0;
//
// dateTimePickerEndDate
//
dateTimePickerEndDate.Location = new Point(141, 221);
dateTimePickerEndDate.Name = "dateTimePickerEndDate";
dateTimePickerEndDate.Size = new Size(200, 23);
dateTimePickerEndDate.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(35, 169);
label1.Name = "label1";
label1.Size = new Size(77, 15);
label1.TabIndex = 2;
label1.Text = "Дата начала:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(35, 227);
label2.Name = "label2";
label2.Size = new Size(71, 15);
label2.TabIndex = 3;
label2.Text = "Дата конца:";
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(119, 287);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(130, 41);
buttonMakeReport.TabIndex = 4;
buttonMakeReport.Text = "Сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// comboBoxProducts
//
comboBoxProducts.FormattingEnabled = true;
comboBoxProducts.Location = new Point(141, 106);
comboBoxProducts.Name = "comboBoxProducts";
comboBoxProducts.Size = new Size(200, 23);
comboBoxProducts.TabIndex = 5;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(35, 109);
label3.Name = "label3";
label3.Size = new Size(42, 15);
label3.TabIndex = 6;
label3.Text = "Товар:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(35, 46);
label4.Name = "label4";
label4.Size = new Size(90, 15);
label4.TabIndex = 7;
label4.Text = "Путь до файла:";
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(141, 43);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(169, 23);
textBoxFilePath.TabIndex = 8;
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(311, 43);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(30, 23);
buttonSelectFilePath.TabIndex = 9;
buttonSelectFilePath.Text = "<3";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// FormProductReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(380, 363);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(comboBoxProducts);
Controls.Add(buttonMakeReport);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(dateTimePickerEndDate);
Controls.Add(dateTimePickerStartDate);
Name = "FormProductReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчет по товару";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerStartDate;
private DateTimePicker dateTimePickerEndDate;
private Label label1;
private Label label2;
private Button buttonMakeReport;
private ComboBox comboBoxProducts;
private Label label3;
private Label label4;
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
}
}

View File

@ -0,0 +1,76 @@
using ProjectOpticsStore.Reports;
using ProjectOpticsStore.Repositories;
using ProjectOpticsStore.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 ProjectOpticsStore.Forms
{
public partial class FormProductReport : Form
{
IUnityContainer _container;
public FormProductReport(IUnityContainer container, IProductRepository productRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxProducts.DataSource = productRepository.ReadProducts();
comboBoxProducts.DisplayMember = "Type";
comboBoxProducts.ValueMember = "Id";
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxProducts.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
}
if (dateTimePickerEndDate.Value <= dateTimePickerStartDate.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxProducts.SelectedValue!,
dateTimePickerStartDate.Value, dateTimePickerEndDate.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,129 @@
namespace ProjectOpticsStore.Forms
{
partial class FormProducts
{
/// <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()
{
panelButtons = new Panel();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridViewProducts = new DataGridView();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit();
SuspendLayout();
//
// panelButtons
//
panelButtons.Controls.Add(buttonDel);
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 3;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewProducts
//
dataGridViewProducts.AllowUserToAddRows = false;
dataGridViewProducts.AllowUserToDeleteRows = false;
dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProducts.Dock = DockStyle.Fill;
dataGridViewProducts.Location = new Point(0, 0);
dataGridViewProducts.Margin = new Padding(3, 2, 3, 2);
dataGridViewProducts.MultiSelect = false;
dataGridViewProducts.Name = "dataGridViewProducts";
dataGridViewProducts.ReadOnly = true;
dataGridViewProducts.RowHeadersVisible = false;
dataGridViewProducts.RowHeadersWidth = 51;
dataGridViewProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewProducts.Size = new Size(569, 338);
dataGridViewProducts.TabIndex = 4;
//
// FormProducts
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewProducts);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormProducts";
Text = "Работа с товарами";
Load += FormProducts_Load;
panelButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelButtons;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridViewProducts;
}
}

View File

@ -0,0 +1,108 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
using Unity;
namespace ProjectOpticsStore.Forms;
public partial class FormProducts : Form
{
private readonly IUnityContainer _container;
private readonly IProductRepository _productRepository;
public FormProducts(IUnityContainer container, IProductRepository productRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
}
private void FormProducts_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<FormProduct>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var productId))
{
return;
}
try
{
// Открытие формы редактирования существующего товара
var form = _container.Resolve<FormProduct>();
form.Id = productId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var productId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
// Удаление товара
_productRepository.DeleteProduct(productId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
// Загрузка списка товаров в DataGridView
dataGridViewProducts.DataSource = _productRepository.ReadProducts().ToList();
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewProducts.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// Получение идентификатора выбранного товара
id = Convert.ToInt32(dataGridViewProducts.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,96 @@
namespace ProjectOpticsStore.Forms
{
partial class FormStore
{
/// <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()
{
textBoxAddress = new TextBox();
labelFullName = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxAddress
//
textBoxAddress.Location = new Point(134, 69);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(295, 27);
textBoxAddress.TabIndex = 1;
//
// labelFullName
//
labelFullName.AutoSize = true;
labelFullName.Font = new Font("Segoe UI", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
labelFullName.Location = new Point(22, 65);
labelFullName.Name = "labelFullName";
labelFullName.Size = new Size(71, 28);
labelFullName.TabIndex = 4;
labelFullName.Text = "Адрес:";
//
// buttonSave
//
buttonSave.Location = new Point(40, 278);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(124, 40);
buttonSave.TabIndex = 5;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(206, 278);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(124, 40);
buttonCancel.TabIndex = 6;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormStore
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(469, 341);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelFullName);
Controls.Add(textBoxAddress);
Name = "FormStore";
Text = "Магазины";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxAddress;
private Label labelFullName;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,79 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormStore : Form
{
private readonly IStoreRepository _storeRepository;
private int? _storeId;
public int Id
{
set
{
try
{
// Загрузка данных магазина
var store = _storeRepository.ReadStoreById(value);
if (store == null)
{
throw new InvalidDataException(nameof(store));
}
textBoxAddress.Text = store.Address;
_storeId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormStore(IStoreRepository storeRepository)
{
InitializeComponent();
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
// Проверка на заполненность обязательных полей
if (string.IsNullOrWhiteSpace(textBoxAddress.Text))
{
throw new Exception("Адрес магазина не указан.");
}
// Сохранение данных
if (_storeId.HasValue)
{
_storeRepository.UpdateStore(CreateStore(_storeId.Value));
}
else
{
_storeRepository.CreateStore(CreateStore(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private Store CreateStore(int id)
{
// Создание сущности Store
return Store.CreateEntity(id, textBoxAddress.Text);
}
}

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,129 @@
namespace ProjectOpticsStore.Forms
{
partial class FormStores
{
/// <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()
{
panelButtons = new Panel();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridViewStores = new DataGridView();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewStores).BeginInit();
SuspendLayout();
//
// panelButtons
//
panelButtons.Controls.Add(buttonDel);
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 4;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewStores
//
dataGridViewStores.AllowUserToAddRows = false;
dataGridViewStores.AllowUserToDeleteRows = false;
dataGridViewStores.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewStores.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewStores.Dock = DockStyle.Fill;
dataGridViewStores.Location = new Point(0, 0);
dataGridViewStores.Margin = new Padding(3, 2, 3, 2);
dataGridViewStores.MultiSelect = false;
dataGridViewStores.Name = "dataGridViewStores";
dataGridViewStores.ReadOnly = true;
dataGridViewStores.RowHeadersVisible = false;
dataGridViewStores.RowHeadersWidth = 51;
dataGridViewStores.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewStores.Size = new Size(569, 338);
dataGridViewStores.TabIndex = 5;
//
// FormStores
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewStores);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormStores";
Text = "Так сказать магазины";
Load += FormStores_Load;
panelButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewStores).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelButtons;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridViewStores;
}
}

View File

@ -0,0 +1,106 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
using Unity;
namespace ProjectOpticsStore.Forms;
public partial class FormStores : Form
{
private readonly IUnityContainer _container;
private readonly IStoreRepository _storeRepository;
public FormStores(IUnityContainer container, IStoreRepository storeRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
}
private void FormStores_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<FormStore>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var storeId))
{
return;
}
try
{
var form = _container.Resolve<FormStore>();
form.Id = storeId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var storeId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_storeRepository.DeleteStore(storeId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
// Загрузка списка магазинов в DataGridView
dataGridViewStores.DataSource = _storeRepository.ReadStores().ToList();
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewStores.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// Получение идентификатора выбранного магазина
id = Convert.ToInt32(dataGridViewStores.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,114 @@
namespace ProjectOpticsStore.Forms
{
partial class FormSupplies
{
/// <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()
{
panelButtons = new Panel();
buttonAdd = new Button();
dataGridViewSupplies = new DataGridView();
buttonDel = new Button();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewSupplies).BeginInit();
SuspendLayout();
//
// panelButtons
//
panelButtons.Controls.Add(buttonDel);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 5;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewSupplies
//
dataGridViewSupplies.AllowUserToAddRows = false;
dataGridViewSupplies.AllowUserToDeleteRows = false;
dataGridViewSupplies.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewSupplies.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewSupplies.Dock = DockStyle.Fill;
dataGridViewSupplies.Location = new Point(0, 0);
dataGridViewSupplies.Margin = new Padding(3, 2, 3, 2);
dataGridViewSupplies.MultiSelect = false;
dataGridViewSupplies.Name = "dataGridViewSupplies";
dataGridViewSupplies.ReadOnly = true;
dataGridViewSupplies.RowHeadersVisible = false;
dataGridViewSupplies.RowHeadersWidth = 51;
dataGridViewSupplies.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewSupplies.Size = new Size(569, 338);
dataGridViewSupplies.TabIndex = 6;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(18, 241);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// FormSupplies
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewSupplies);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSupplies";
Text = "Определенным образом поставка";
Load += FormSupplies_Load;
panelButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewSupplies).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelButtons;
private Button buttonAdd;
private DataGridView dataGridViewSupplies;
private Button buttonDel;
}
}

View File

@ -0,0 +1,85 @@

using Unity;
namespace ProjectOpticsStore.Forms;
public partial class FormSupplies : Form
{
private readonly IUnityContainer _container;
private readonly ISupplyRepository _supplyRepository;
public FormSupplies(IUnityContainer container, ISupplyRepository supplyRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository));
}
private void FormSupplies_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<FormSupply>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
// Загрузка списка поставок в DataGridView
dataGridViewSupplies.DataSource = _supplyRepository.ReadSupplies().ToList();
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var orderId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_supplyRepository.DeleteSupply(orderId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewSupplies.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// Получение идентификатора выбранного магазина
id = Convert.ToInt32(dataGridViewSupplies.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,168 @@
namespace ProjectOpticsStore.Forms
{
partial class FormSupply
{
/// <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()
{
comboBoxStore = new ComboBox();
comboBoxProduct = new ComboBox();
numericUpDownQuantity = new NumericUpDown();
dateTimePickerOperationDate = new DateTimePicker();
buttonSave = new Button();
buttonCancel = new Button();
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).BeginInit();
SuspendLayout();
//
// comboBoxStore
//
comboBoxStore.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStore.FormattingEnabled = true;
comboBoxStore.Location = new Point(148, 12);
comboBoxStore.Name = "comboBoxStore";
comboBoxStore.Size = new Size(288, 28);
comboBoxStore.TabIndex = 9;
//
// comboBoxProduct
//
comboBoxProduct.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxProduct.FormattingEnabled = true;
comboBoxProduct.Location = new Point(148, 85);
comboBoxProduct.Name = "comboBoxProduct";
comboBoxProduct.Size = new Size(288, 28);
comboBoxProduct.TabIndex = 10;
//
// numericUpDownQuantity
//
numericUpDownQuantity.Location = new Point(148, 157);
numericUpDownQuantity.Name = "numericUpDownQuantity";
numericUpDownQuantity.Size = new Size(150, 27);
numericUpDownQuantity.TabIndex = 11;
//
// dateTimePickerOperationDate
//
dateTimePickerOperationDate.Enabled = false;
dateTimePickerOperationDate.Location = new Point(148, 233);
dateTimePickerOperationDate.Name = "dateTimePickerOperationDate";
dateTimePickerOperationDate.Size = new Size(250, 27);
dateTimePickerOperationDate.TabIndex = 12;
//
// buttonSave
//
buttonSave.Location = new Point(44, 371);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(124, 40);
buttonSave.TabIndex = 13;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(204, 371);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(124, 40);
buttonCancel.TabIndex = 14;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(44, 15);
label1.Name = "label1";
label1.Size = new Size(72, 20);
label1.TabIndex = 15;
label1.Text = "Магазин:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(44, 85);
label2.Name = "label2";
label2.Size = new Size(54, 20);
label2.TabIndex = 16;
label2.Text = "Товар:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(44, 159);
label3.Name = "label3";
label3.Size = new Size(93, 20);
label3.TabIndex = 17;
label3.Text = "Количество:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(44, 238);
label4.Name = "label4";
label4.Size = new Size(89, 20);
label4.TabIndex = 18;
label4.Text = "ДатаВремя:";
//
// FormSupply
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(598, 450);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(dateTimePickerOperationDate);
Controls.Add(numericUpDownQuantity);
Controls.Add(comboBoxProduct);
Controls.Add(comboBoxStore);
Name = "FormSupply";
Text = "Поставка";
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxStore;
private ComboBox comboBoxProduct;
private NumericUpDown numericUpDownQuantity;
private DateTimePicker dateTimePickerOperationDate;
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private Label label2;
private Label label3;
private Label label4;
}
}

View File

@ -0,0 +1,67 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormSupply : Form
{
private readonly ISupplyRepository _supplyRepository;
private readonly IStoreRepository _storeRepository;
private readonly IProductRepository _productRepository;
public FormSupply(ISupplyRepository supplyRepository, IStoreRepository storeRepository, IProductRepository productRepository)
{
InitializeComponent();
_supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository));
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
// Инициализация ComboBox для магазинов
comboBoxStore.DataSource = _storeRepository.ReadStores().ToList();
comboBoxStore.DisplayMember = "Address";
comboBoxStore.ValueMember = "Id";
// Инициализация ComboBox для товаров
comboBoxProduct.DataSource = _productRepository.ReadProducts().ToList();
comboBoxProduct.DisplayMember = "Name";
comboBoxProduct.ValueMember = "Id";
// Устанавливаем дату как текущую и блокируем редактирование
dateTimePickerOperationDate.Value = DateTime.Now;
dateTimePickerOperationDate.Enabled = false;
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
// Проверка на заполненность полей
if (comboBoxStore.SelectedIndex < 0 || comboBoxProduct.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
// Создание новой поставки
var supply = Supply.CreateOperation(
id: 0, // Новый объект, идентификатор пока 0
storeId: (int)comboBoxStore.SelectedValue!,
productId: (int)comboBoxProduct.SelectedValue!,
quantity: (int)numericUpDownQuantity.Value
);
_supplyRepository.CreateSupply(supply);
MessageBox.Show("Поставка успешно добавлена", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
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,108 @@
namespace ProjectOpticsStore.Forms
{
partial class FormSupplyDistributionReport
{
/// <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()
{
buttonSelectFileName = new Button();
buttonCreate = new Button();
dateTimePicker = new DateTimePicker();
labelFileName = new Label();
label2 = new Label();
SuspendLayout();
//
// buttonSelectFileName
//
buttonSelectFileName.Location = new Point(29, 36);
buttonSelectFileName.Name = "buttonSelectFileName";
buttonSelectFileName.Size = new Size(75, 23);
buttonSelectFileName.TabIndex = 0;
buttonSelectFileName.Text = "Выбрать";
buttonSelectFileName.UseVisualStyleBackColor = true;
buttonSelectFileName.Click += ButtonSelectFileName_Click;
//
// buttonCreate
//
buttonCreate.Location = new Point(110, 176);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(112, 23);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// dateTimePicker
//
dateTimePicker.Location = new Point(100, 81);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(200, 23);
dateTimePicker.TabIndex = 2;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(138, 40);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(36, 15);
labelFileName.TabIndex = 3;
labelFileName.Text = "Файл";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(29, 87);
label2.Name = "label2";
label2.Size = new Size(35, 15);
label2.TabIndex = 4;
label2.Text = "Дата:";
//
// FormSupplyDistributionReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(332, 233);
Controls.Add(label2);
Controls.Add(labelFileName);
Controls.Add(dateTimePicker);
Controls.Add(buttonCreate);
Controls.Add(buttonSelectFileName);
Name = "FormSupplyDistributionReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Поставки товара";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFileName;
private Button buttonCreate;
private DateTimePicker dateTimePicker;
private Label labelFileName;
private Label label2;
}
}

View File

@ -0,0 +1,64 @@
using ProjectOpticsStore.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 ProjectOpticsStore.Forms;
public partial class FormSupplyDistributionReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormSupplyDistributionReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePicker.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 ButtonSelectFileName_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);
}
}
}

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,9 +1,18 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectOpticsStore.Repositories;
using ProjectOpticsStore.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ProjectOpticsStore
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
@ -11,7 +20,35 @@ namespace ProjectOpticsStore
// 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<FormOpticsStore>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ICustomerRepository, CustomerRepository>(new TransientLifetimeManager());
container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager());
container.RegisterType<IProductRepository, ProductRepository>(new TransientLifetimeManager());
container.RegisterType<IStoreRepository, StoreRepository>(new TransientLifetimeManager());
container.RegisterType<ISupplyRepository, SupplyRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>(new TransientLifetimeManager());
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,48 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<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="Microsoft.Extensions.Logging.Abstractions" 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="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.Container" Version="5.11.11" />
<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,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="Order" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>Order, ProjectOpticsStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectOpticsStore.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("ProjectOpticsStore.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 Button_Add {
get {
object obj = ResourceManager.GetObject("Button_Add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Button_Delete {
get {
object obj = ResourceManager.GetObject("Button_Delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Button_Edit {
get {
object obj = ResourceManager.GetObject("Button_Edit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap catwithglasses {
get {
object obj = ResourceManager.GetObject("catwithglasses", 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="Button_Edit" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Button_Edit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="catwithglasses" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\catwithglasses.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Button_Add" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Button_Add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Button_Delete" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Button_Delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
using ProjectOpticsStore.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectOpticsStore.Reports;
public class ChartReport
{
private readonly ISupplyRepository _supplyRepository; // Изменение типа репозитория
private readonly ILogger<ChartReport> _logger;
public ChartReport(ISupplyRepository supplyRepository, ILogger<ChartReport> logger) // Изменение параметра конструктора
{
_supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Распределение поставок по товарам") // Изменено заголовок для соответствия Supply
.AddPieChart("Поставки", GetData(dateTime)) // Изменено название графика
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _supplyRepository
.ReadSupplies() // Изменено на метод, который читает поставки
.Where(x => x.OperationDate.Date == dateTime.Date) // Используем OperationDate вместо DateCreated
.GroupBy(x => x.ProductId, (key, group) => new { ID = key, TotalQuantity = group.Sum(y => y.Quantity) }) // Группировка по ProductId
.Select(x => (x.ID.ToString(), (double)x.TotalQuantity)) // Изменено на TotalQuantity
.ToList();
}
}

View File

@ -0,0 +1,77 @@
using Microsoft.Extensions.Logging;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Reports;
public class DocReport
{
private readonly ICustomerRepository _customerRepository;
private readonly IStoreRepository _storeRepository;
private readonly IProductRepository _productRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(ICustomerRepository customerRepository, IStoreRepository storeRepository,
IProductRepository productRepository, ILogger<DocReport> logger)
{
_customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); ;
}
public bool CreateDoc(string filePath, bool includeCustomers, bool includeStores, bool includeProducts)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (includeCustomers)
{
builder.AddParagraph("Заказчики").AddTable([2400], GetCustomers());
}
if (includeStores)
{
builder.AddParagraph("Магазины").AddTable([2400], GetStores());
}
if (includeProducts)
{
builder.AddParagraph("Товары").AddTable([2400, 2400, 2400, 2400, 2400, 2400], GetProducts());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetCustomers()
{
return [
["ФИО Заказчика"],
.. _customerRepository
.ReadCustomers()
.Select(x => new string[] { x.FullName}),
];
}
private List<string[]> GetStores()
{
return [
["Адрес магазина"],
.. _storeRepository
.ReadStores()
.Select(x => new string[] { x.Address}),
];
}
private List<string[]> GetProducts()
{
return [
["Тип", "Мощность", "Цена", "Магазин","Толщина", "Болезнь"],
.. _productRepository
.ReadProducts()
.Select(x => new string[] {x.Type.ToString(), x.Power.ToString(), x.Price.ToString(), x.Store.ToString(), x.Thickness.ToString(), x.Disease}),
];
}
}

View File

@ -0,0 +1,311 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace ProjectOpticsStore.Reports;
public 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.BoldTextWithBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithBorder);
}
_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)
{
//Создаем объект для хранения стилей т.н. Open XML SDK
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)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
Bold = new Bold(),
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()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Medium },
RightBorder = new RightBorder() { Style = BorderStyleValues.Medium },
TopBorder = new TopBorder() { Style = BorderStyleValues.Medium },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Medium },
DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Medium },
});
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
}
});
// Формат с границей
cellFormats.Append(new CellFormat
{
NumberFormatId = 1,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// Жирный шрифт без границы
cellFormats.Append(new CellFormat
{
NumberFormatId = 2,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// Жирный шрифт с границей
cellFormats.Append(new CellFormat
{
NumberFormatId = 3,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 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,90 @@
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;
using Color = MigraDoc.DocumentObjectModel.Color;
namespace ProjectOpticsStore.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()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
var headerStyle = _document.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 14;
headerStyle.Font.Color = Colors.DeepPink;
}
}

View File

@ -0,0 +1,81 @@
using Microsoft.Extensions.Logging;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Reports;
public class TableReport
{
private readonly IOrderRepository _orderRepository;
private readonly ISupplyRepository _supplyRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Продукт", "Дата", "Количество пришло", "Количество ушло"];
public TableReport(IOrderRepository orderRepository, ISupplyRepository supplyRepository,
ILogger<TableReport> logger)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int productID, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению товара", 0, 4)
.AddParagraph("за период", 0)
.AddTable([10, 10, 15, 15], GetData(productID, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int productID, DateTime startDate, DateTime endDate)
{
var data = _orderRepository
.ReadOrders()
.Where(x => x.DateCreated >= startDate && x.DateCreated <= endDate && x.OrderProducts.Any(y => y.ProductId == productID))
.Select(x => new
{
ProductID = x.OrderProducts.First(y => y.ProductId == productID).ProductId,
Date = x.DateCreated,
CountIn = (int?)null,
CountOut = (int?)x.OrderProducts.FirstOrDefault(y => y.ProductId == productID)?.Quantity
})
.Union(
_supplyRepository
.ReadSupplies()
.Where(x => x.OperationDate >= startDate && x.OperationDate <= endDate && x.ProductId == productID)
.Select(x => new
{
ProductID = x.ProductId,
Date = x.OperationDate,
CountIn = (int?)x.Quantity,
CountOut = (int?)null
}))
.OrderBy(x => x.Date);
return
new List<string[]> { TableReport.item }
.Union(
data.Select(x => new string[]
{
x.ProductID.ToString(),
x.Date.ToString(),
x.CountIn?.ToString() ?? string.Empty,
x.CountOut?.ToString() ?? string.Empty
}))
.Union(new[] {
new[] { "Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString() }
})
.ToList();
}
}

View File

@ -0,0 +1,88 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace ProjectOpticsStore.Reports;
public 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());
run.PrependChild(new RunProperties());
run.RunProperties.AddChild(new Bold());
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 })));
// Заголовок
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);
// Данные
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,6 @@
namespace ProjectOpticsStore.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -0,0 +1,12 @@
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories;
public interface ICustomerRepository
{
IEnumerable<Customer> ReadCustomers();
Customer ReadCustomerById(int id);
void CreateCustomer(Customer customer);
void UpdateCustomer(Customer customer);
void DeleteCustomer(int id);
}

View File

@ -0,0 +1,11 @@
namespace ProjectOpticsStore.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrders(
DateTime? dateFrom = null,
DateTime? dateTo = null,
int? customerId = null
);
void CreateOrder(Order order);
}

View File

@ -0,0 +1,10 @@
namespace ProjectOpticsStore.Repositories;
public interface IProductRepository
{
IEnumerable<Product> ReadProducts();
Product ReadProductById(int id);
void CreateProduct(Product product);
void UpdateProduct(Product product);
void DeleteProduct(int id);
}

View File

@ -0,0 +1,12 @@
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories;
public interface IStoreRepository
{
IEnumerable<Store> ReadStores();
Store ReadStoreById(int id);
void CreateStore(Store store);
void UpdateStore(Store store);
void DeleteStore(int id);
}

View File

@ -0,0 +1,15 @@
using ProjectOpticsStore.Entities;
public interface ISupplyRepository
{
IEnumerable<Supply> ReadSupplies(
DateTime? dateFrom = null,
DateTime? dateTo = null,
int? storeId = null,
int? productId = null
);
void CreateSupply(Supply supply);
void DeleteSupply(int id);
}

View File

@ -0,0 +1,6 @@
namespace ProjectOpticsStore.Repositories.Implementations;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=127.0.0.1;Database=opticsstore;Username=postgres;Password=postgres";
}

View File

@ -0,0 +1,116 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class CustomerRepository : ICustomerRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CustomerRepository> _logger;
public CustomerRepository(IConnectionString connectionString, ILogger<CustomerRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateCustomer(Customer customer)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Customers (FullName)
VALUES (@FullName)";
connection.Execute(queryInsert, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateCustomer(Customer customer)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Customers
SET
FullName=@Fullname
WHERE Id=@Id";
connection.Execute(queryUpdate, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteCustomer(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Customers
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Customer ReadCustomerById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Customers
WHERE Id=@id";
var customer = connection.QueryFirst<Customer>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer));
return customer;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Customer> ReadCustomers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Customers";
var customers = connection.Query<Customer>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customers));
return customers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,87 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
using Unity;
namespace ProjectOpticsStore.Repositories.Implementations;
internal 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 Orders (CustomerId, DateCreated, Status)
VALUES (@CustomerId, @DateCreated, @Status);
SELECT MAX(Id) FROM Orders";
var OrderId = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @"
INSERT INTO Orders_Products (OrderId, ProductId, Quantity)
VALUES (@OrderId, @ProductId, @Quantity)";
foreach (var elem in order.OrderProducts)
{
connection.Execute(querySubInsert, new { OrderId, elem.ProductId, elem.Quantity }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Order> ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT o.*, op.OrderId, op.ProductId, op.Quantity
FROM Orders o
INNER JOIN Orders_Products op ON op.OrderId = o.Id";
_logger.LogDebug("Выполняется SQL-запрос: {Query}", querySelect);
var orderProducts = connection.Query<TempOrderProduct>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orderProducts));
return orderProducts
.GroupBy(
x => x.Id,
y => y,
(key, value) => Order.CreateOperation(
value.First(),
value.Select(z => Order_Product.CreateElement(z.OrderId, z.ProductId, z.Quantity))
)
).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,124 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class ProductRepository : IProductRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductRepository> _logger;
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProduct(Product product)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Products (Type, Power, Price, Store, Thickness, Disease)
VALUES (@Type, @Power, @Price, @Store, @Thickness, @Disease)";
connection.Execute(queryInsert, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateProduct(Product product)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Products
SET
Type=@Type,
Power=@Power,
Price=@Price,
Store=@Store,
Thickness=@Thickness,
Disease=@Disease
WHERE Id=@Id";
connection.Execute(queryUpdate, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteProduct(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Products
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Product ReadProductById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Products
WHERE Id=@id";
var product = connection.QueryFirst<Product>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> ReadProducts()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
// SQL-запрос для получения всех продуктов
var querySelect = "SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,115 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class StoreRepository : IStoreRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StoreRepository> _logger;
public StoreRepository(IConnectionString connectionString, ILogger<StoreRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStore(Store store)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Stores (Address)
VALUES (@Address)";
connection.Execute(queryInsert, store);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateStore(Store store)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Stores
SET
Address=@Address
WHERE Id=@Id";
connection.Execute(queryUpdate, store);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteStore(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Stores
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Store ReadStoreById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Stores
WHERE Id=@id";
var store = connection.QueryFirst<Store>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(store));
return store;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Store> ReadStores()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Stores";
var stores = connection.Query<Store>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(stores));
return stores;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,77 @@
using Dapper;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class SupplyRepository : ISupplyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplyRepository> _logger;
public SupplyRepository(IConnectionString connectionString, ILogger<SupplyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupply(Supply supply)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Supplies (StoreId, OperationDate, ProductId, Quantity)
VALUES (@StoreId, @OperationDate, @ProductId, @Quantity)";
connection.Execute(queryInsert, supply);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSupply(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Supplies
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Supply> ReadSupplies(DateTime? dateFrom = null, DateTime? dateTo = null, int? storeId = null, int? productId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Supplies";
var supplies = connection.Query<Supply>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supplies));
return supplies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

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