Compare commits

...

3 Commits
main ... Lab02

Author SHA1 Message Date
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
65 changed files with 4795 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,26 @@
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"
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
};
}
}

View File

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

@ -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,138 @@
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();
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.Size = new Size(800, 28);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { товарыToolStripMenuItem, магазиныToolStripMenuItem, заказчикиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// товарыToolStripMenuItem
//
товарыToolStripMenuItem.Name = оварыToolStripMenuItem";
товарыToolStripMenuItem.Size = new Size(224, 26);
товарыToolStripMenuItem.Text = "Товары";
товарыToolStripMenuItem.Click += ProductsToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(224, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += StoresToolStripMenuItem_Click;
//
// заказчикиToolStripMenuItem
//
заказчикиToolStripMenuItem.Name = аказчикиToolStripMenuItem";
заказчикиToolStripMenuItem.Size = new Size(224, 26);
заказчикиToolStripMenuItem.Text = "Заказчики";
заказчикиToolStripMenuItem.Click += CustomersToolStripMenuItem_Click;
//
// операцииToolStripMenuItem
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { поставкаToolStripMenuItem, заказатьToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(95, 24);
операцииToolStripMenuItem.Text = "Операции";
//
// поставкаToolStripMenuItem
//
поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem";
поставкаToolStripMenuItem.Size = new Size(164, 26);
поставкаToolStripMenuItem.Text = "Поставить";
поставкаToolStripMenuItem.Click += SupplyToolStripMenuItem_Click;
//
// заказатьToolStripMenuItem
//
заказатьToolStripMenuItem.Name = аказатьToolStripMenuItem";
заказатьToolStripMenuItem.Size = new Size(164, 26);
заказатьToolStripMenuItem.Text = "Заказать";
заказатьToolStripMenuItem.Click += OrderToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(73, 24);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// FormOpticsStore
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.catwithglasses;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(800, 450);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
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;
}
}

View File

@ -0,0 +1,82 @@
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 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,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,129 @@
using ProjectOpticsStore.Entities.Enums;
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Repositories;
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;
// Получаем значения из ячеек
var productId = Convert.ToInt32(row.Cells["ColumnProduct"].Value);
var quantity = Convert.ToInt32(row.Cells["ColumnQuantity"].Value);
// Используем метод CreateElement для создания объектов Order_Product
list.Add(Order_Product.CreateElement(0, 0, productId, quantity));
}
return list;
}
}

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 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();
buttonDel = new Button();
buttonAdd = new Button();
dataGridViewOrders = new DataGridView();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewOrders).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 = 2;
//
// 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;
//
// 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 buttonDel;
private Button buttonAdd;
private DataGridView dataGridViewOrders;
}
}

View File

@ -0,0 +1,96 @@
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);
}
}
// Кнопка для удаления выбранного заказа
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var orderId))
{
return;
}
if (MessageBox.Show("Удалить заказ?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_orderRepository.DeleteOrder(orderId);
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,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,99 @@
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();
panelButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewSupplies).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 = 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;
//
// 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;
}
}

View File

@ -0,0 +1,48 @@

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();
}
}

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

@ -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,46 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<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="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,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,12 @@
namespace ProjectOpticsStore.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrders(
DateTime? dateFrom = null,
DateTime? dateTo = null,
int? customerId = null
);
void CreateOrder(Order order);
void DeleteOrder(int id);
}

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,13 @@
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);
}

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,92 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
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 void DeleteOrder(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Orders
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Order> ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? customerId = null)
{
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Orders";
var orders = connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
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,57 @@
using Dapper;
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 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"
}
}
]
}
}