Compare commits

...

5 Commits

60 changed files with 4165 additions and 13 deletions

View File

@ -0,0 +1,128 @@
namespace SushiBarView
{
partial class FormComponent
{
/// <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()
{
labelComponentName = new Label();
labelCost = new Label();
textBoxComponentName = new TextBox();
textBoxComponentCost = new TextBox();
buttonSaveComponent = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelComponentName
//
labelComponentName.AutoSize = true;
labelComponentName.Font = new Font("Candara", 12F);
labelComponentName.Location = new Point(20, 29);
labelComponentName.Margin = new Padding(4, 0, 4, 0);
labelComponentName.Name = "labelComponentName";
labelComponentName.Size = new Size(93, 24);
labelComponentName.TabIndex = 0;
labelComponentName.Text = "Название";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Font = new Font("Candara", 12F);
labelCost.Location = new Point(29, 111);
labelCost.Margin = new Padding(4, 0, 4, 0);
labelCost.Name = "labelCost";
labelCost.Size = new Size(53, 24);
labelCost.TabIndex = 1;
labelCost.Text = "Цена";
//
// textBoxComponentName
//
textBoxComponentName.Anchor = AnchorStyles.Top | AnchorStyles.Right;
textBoxComponentName.Location = new Point(134, 21);
textBoxComponentName.Name = "textBoxComponentName";
textBoxComponentName.Size = new Size(355, 32);
textBoxComponentName.TabIndex = 2;
//
// textBoxComponentCost
//
textBoxComponentCost.Anchor = AnchorStyles.Top | AnchorStyles.Right;
textBoxComponentCost.Location = new Point(134, 103);
textBoxComponentCost.Name = "textBoxComponentCost";
textBoxComponentCost.Size = new Size(355, 32);
textBoxComponentCost.TabIndex = 3;
//
// buttonSaveComponent
//
buttonSaveComponent.Anchor = AnchorStyles.Bottom;
buttonSaveComponent.Location = new Point(134, 161);
buttonSaveComponent.Name = "buttonSaveComponent";
buttonSaveComponent.Size = new Size(116, 39);
buttonSaveComponent.TabIndex = 4;
buttonSaveComponent.Text = "Сохранить";
buttonSaveComponent.UseVisualStyleBackColor = true;
buttonSaveComponent.Click += buttonSaveComponent_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom;
buttonCancel.Location = new Point(373, 161);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(116, 39);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormComponent
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(515, 230);
Controls.Add(buttonCancel);
Controls.Add(buttonSaveComponent);
Controls.Add(textBoxComponentCost);
Controls.Add(textBoxComponentName);
Controls.Add(labelCost);
Controls.Add(labelComponentName);
Font = new Font("Candara", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
Margin = new Padding(4);
Name = "FormComponent";
Text = "Компонент";
Load += FormComponents_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelComponentName;
private Label labelCost;
private TextBox textBoxComponentName;
private TextBox textBoxComponentCost;
private Button buttonSaveComponent;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,91 @@

using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using System.Windows.Forms;
namespace SushiBarView
{
public partial class FormComponent : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id
{
set { _id = value; }
}
public FormComponent(ILogger<FormComponent> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponents_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение компонента");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxComponentName.Text = view.ComponentName;
textBoxComponentCost.Text = view.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonSaveComponent_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxComponentName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение компонента");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxComponentName.Text,
Cost = Convert.ToDouble(textBoxComponentCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,123 @@
namespace SushiBarView
{
partial class FormComponents
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonAddComponent = new Button();
buttonUpdateComponent = new Button();
buttonRemoveComponent = new Button();
buttonRefreshComponents = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ActiveCaption;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(569, 521);
dataGridView.TabIndex = 0;
//
// buttonAddComponent
//
buttonAddComponent.Font = new Font("Candara", 12F);
buttonAddComponent.Location = new Point(637, 35);
buttonAddComponent.Name = "buttonAddComponent";
buttonAddComponent.Size = new Size(121, 46);
buttonAddComponent.TabIndex = 1;
buttonAddComponent.Text = "Добавить";
buttonAddComponent.UseVisualStyleBackColor = true;
buttonAddComponent.Click += buttonAddComponent_Click;
//
// buttonUpdateComponent
//
buttonUpdateComponent.Font = new Font("Candara", 12F);
buttonUpdateComponent.Location = new Point(637, 167);
buttonUpdateComponent.Name = "buttonUpdateComponent";
buttonUpdateComponent.Size = new Size(121, 46);
buttonUpdateComponent.TabIndex = 2;
buttonUpdateComponent.Text = "Изменить";
buttonUpdateComponent.UseVisualStyleBackColor = true;
buttonUpdateComponent.Click += buttonUpdateComponent_Click;
//
// buttonRemoveComponent
//
buttonRemoveComponent.Font = new Font("Candara", 12F);
buttonRemoveComponent.Location = new Point(637, 307);
buttonRemoveComponent.Name = "buttonRemoveComponent";
buttonRemoveComponent.Size = new Size(121, 46);
buttonRemoveComponent.TabIndex = 3;
buttonRemoveComponent.Text = "Удалить";
buttonRemoveComponent.UseVisualStyleBackColor = true;
buttonRemoveComponent.Click += buttonRemoveComponent_Click;
//
// buttonRefreshComponents
//
buttonRefreshComponents.Font = new Font("Candara", 12F);
buttonRefreshComponents.Location = new Point(637, 444);
buttonRefreshComponents.Name = "buttonRefreshComponents";
buttonRefreshComponents.Size = new Size(121, 46);
buttonRefreshComponents.TabIndex = 4;
buttonRefreshComponents.Text = "Обновить";
buttonRefreshComponents.UseVisualStyleBackColor = true;
buttonRefreshComponents.Click += buttonRefreshComponents_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 521);
Controls.Add(buttonRefreshComponents);
Controls.Add(buttonRemoveComponent);
Controls.Add(buttonUpdateComponent);
Controls.Add(buttonAddComponent);
Controls.Add(dataGridView);
Name = "FormComponents";
Text = "Компоненты";
Load += FormComponents_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAddComponent;
private Button buttonUpdateComponent;
private Button buttonRemoveComponent;
private Button buttonRefreshComponents;
}
}

View File

@ -0,0 +1,124 @@
using Microsoft.Extensions.Logging;
using SushiBar;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SushiBarView
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id
{
set { _id = value; }
}
public FormComponents(ILogger<FormComponents> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponents_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAddComponent_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpdateComponent_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
form.Id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonRemoveComponent_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ComponentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRefreshComponents_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

174
SushiBar/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,174 @@
namespace SushiBarView
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
ToolStripMenuItemRef = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem();
сушиToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonOrderIssued = new Button();
buttonRefreshOrders = new Button();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenuItemRef });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1140, 28);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// ToolStripMenuItemRef
//
ToolStripMenuItemRef.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, сушиToolStripMenuItem });
ToolStripMenuItemRef.Name = "ToolStripMenuItemRef";
ToolStripMenuItemRef.Size = new Size(117, 24);
ToolStripMenuItemRef.Text = "Справочники";
//
// компонентыToolStripMenuItem
//
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(182, 26);
компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click;
//
// сушиToolStripMenuItem
//
сушиToolStripMenuItem.Name = "сушиToolStripMenuItem";
сушиToolStripMenuItem.Size = new Size(182, 26);
сушиToolStripMenuItem.Text = "Суши";
сушиToolStripMenuItem.Click += сушиToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 27);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(849, 512);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(923, 63);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(171, 52);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += buttonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(923, 161);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(171, 52);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click_1;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(923, 253);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(171, 52);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += buttonOrderReady_Click_1;
//
// buttonOrderIssued
//
buttonOrderIssued.Location = new Point(923, 351);
buttonOrderIssued.Name = "buttonOrderIssued";
buttonOrderIssued.Size = new Size(171, 52);
buttonOrderIssued.TabIndex = 5;
buttonOrderIssued.Text = "Заказ выдан";
buttonOrderIssued.UseVisualStyleBackColor = true;
buttonOrderIssued.Click += buttonOrderIssued_Click;
//
// buttonRefreshOrders
//
buttonRefreshOrders.Location = new Point(923, 450);
buttonRefreshOrders.Name = "buttonRefreshOrders";
buttonRefreshOrders.Size = new Size(171, 52);
buttonRefreshOrders.TabIndex = 6;
buttonRefreshOrders.Text = "Обновить заказы";
buttonRefreshOrders.UseVisualStyleBackColor = true;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.FromArgb(210, 255, 210);
ClientSize = new Size(1140, 540);
Controls.Add(buttonRefreshOrders);
Controls.Add(buttonOrderIssued);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Суши Бар";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem ToolStripMenuItemRef;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonOrderIssued;
private Button buttonRefreshOrders;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem сушиToolStripMenuItem;
}
}

154
SushiBar/FormMain.cs Normal file
View File

@ -0,0 +1,154 @@
using Microsoft.Extensions.Logging;
using SushiBar;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SushiBarView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["SushiId"].Visible = false;
dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Произошла ошибка при загрузке заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void компонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void сушиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushis));
if(service is FormSushis formSushis) { formSushis.ShowDialog(); }
}
private void buttonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonTakeOrderInWork_Click_1(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ ${id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click_1(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ ${id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonOrderIssued_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ ${id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

126
SushiBar/FormMain.resx Normal file
View File

@ -0,0 +1,126 @@
<?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>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -0,0 +1,151 @@
namespace SushiBarView
{
partial class FormCreateOrder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelSushi = new Label();
labelCount = new Label();
labelSum = new Label();
textBoxCount = new TextBox();
textBoxSum = new TextBox();
comboBoxSushi = new ComboBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelSushi
//
labelSushi.AutoSize = true;
labelSushi.Location = new Point(30, 30);
labelSushi.Margin = new Padding(4, 0, 4, 0);
labelSushi.Name = "labelSushi";
labelSushi.Size = new Size(85, 24);
labelSushi.TabIndex = 0;
labelSushi.Text = "Изделие";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(30, 102);
labelCount.Margin = new Padding(4, 0, 4, 0);
labelCount.Name = "labelCount";
labelCount.Size = new Size(112, 24);
labelCount.TabIndex = 1;
labelCount.Text = "Количество";
//
// labelSum
//
labelSum.AutoSize = true;
labelSum.Location = new Point(30, 174);
labelSum.Margin = new Padding(4, 0, 4, 0);
labelSum.Name = "labelSum";
labelSum.Size = new Size(68, 24);
labelSum.TabIndex = 2;
labelSum.Text = "Сумма";
//
// textBoxCount
//
textBoxCount.Location = new Point(227, 94);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(326, 32);
textBoxCount.TabIndex = 3;
textBoxCount.TextChanged += textBoxCount_TextChanged;
//
// textBoxSum
//
textBoxSum.Enabled = false;
textBoxSum.Location = new Point(227, 166);
textBoxSum.Name = "textBoxSum";
textBoxSum.Size = new Size(326, 32);
textBoxSum.TabIndex = 4;
//
// comboBoxSushi
//
comboBoxSushi.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSushi.FormattingEnabled = true;
comboBoxSushi.Location = new Point(227, 22);
comboBoxSushi.Name = "comboBoxSushi";
comboBoxSushi.Size = new Size(326, 32);
comboBoxSushi.TabIndex = 5;
comboBoxSushi.SelectedIndexChanged += comboBoxSushi_SelectedIndexChanged;
//
// buttonSave
//
buttonSave.Location = new Point(227, 231);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(140, 49);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(413, 231);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(140, 49);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.FromArgb(192, 192, 255);
ClientSize = new Size(595, 302);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxSushi);
Controls.Add(textBoxSum);
Controls.Add(textBoxCount);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelSushi);
Font = new Font("Candara", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
Margin = new Padding(4);
Name = "FormCreateOrder";
Text = "Создание заказа";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelSushi;
private Label labelCount;
private Label labelSum;
private TextBox textBoxCount;
private TextBox textBoxSum;
private ComboBox comboBoxSushi;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,118 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
namespace SushiBarView
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logicSushi;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, ISushiLogic logicSushi, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicSushi = logicSushi;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для заказа");
try
{
var list = _logicSushi.ReadList(null);
if (list != null)
{
comboBoxSushi.DisplayMember = "SushiName";
comboBoxSushi.ValueMember = "Id";
comboBoxSushi.DataSource = list;
comboBoxSushi.SelectedItem = null;
_logger.LogInformation("Загрузка изделий для заказа");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// прописать логику
}
private void comboBoxSushi_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
private void textBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxSushi.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
SushiId = Convert.ToInt32(comboBoxSushi.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void CalcSum()
{
if (comboBoxSushi.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxSushi.SelectedValue);
var product = _logicSushi.ReadElement(new SushiSearchModel { Id = id });
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
}

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,7 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SushiBarBusinessLogic.BusinessLogic;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.StoragesContracts;
using SushiBarListImplements.Implements;
using SushiBarView;
namespace SushiBar
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +24,33 @@ namespace SushiBar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
//Application.Run(new Form1());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormSushi>();
services.AddTransient<FormSushiComponent>();
services.AddTransient<FormSushis>();
}
}
}

View File

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

View File

@ -3,7 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBar", "SushiBar.csproj", "{E1025CC0-5650-4509-93C8-BF4FA2D506E0}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarView", "SushiBarView.csproj", "{E1025CC0-5650-4509-93C8-BF4FA2D506E0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarDataModels", "..\SushiBarDataModels\SushiBarDataModels.csproj", "{98946D8E-A8FC-40DC-9FC8-BCBBC6BD6688}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarContracts", "..\SushiBarContracts\SushiBarContracts.csproj", "{0C8B928F-ACD2-4196-8F2B-5190914911D8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarBusinessLogic", "..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj", "{B4061C5A-A7C4-4F49-A1AC-083877203CD8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarListImplements", "..\SushiBarListImplements\SushiBarListImplements.csproj", "{BAA05DBA-C77F-4CF6-9998-4C150FA5797C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +23,22 @@ Global
{E1025CC0-5650-4509-93C8-BF4FA2D506E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E1025CC0-5650-4509-93C8-BF4FA2D506E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E1025CC0-5650-4509-93C8-BF4FA2D506E0}.Release|Any CPU.Build.0 = Release|Any CPU
{98946D8E-A8FC-40DC-9FC8-BCBBC6BD6688}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{98946D8E-A8FC-40DC-9FC8-BCBBC6BD6688}.Debug|Any CPU.Build.0 = Debug|Any CPU
{98946D8E-A8FC-40DC-9FC8-BCBBC6BD6688}.Release|Any CPU.ActiveCfg = Release|Any CPU
{98946D8E-A8FC-40DC-9FC8-BCBBC6BD6688}.Release|Any CPU.Build.0 = Release|Any CPU
{0C8B928F-ACD2-4196-8F2B-5190914911D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0C8B928F-ACD2-4196-8F2B-5190914911D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0C8B928F-ACD2-4196-8F2B-5190914911D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0C8B928F-ACD2-4196-8F2B-5190914911D8}.Release|Any CPU.Build.0 = Release|Any CPU
{B4061C5A-A7C4-4F49-A1AC-083877203CD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B4061C5A-A7C4-4F49-A1AC-083877203CD8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B4061C5A-A7C4-4F49-A1AC-083877203CD8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B4061C5A-A7C4-4F49-A1AC-083877203CD8}.Release|Any CPU.Build.0 = Release|Any CPU
{BAA05DBA-C77F-4CF6-9998-4C150FA5797C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAA05DBA-C77F-4CF6-9998-4C150FA5797C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAA05DBA-C77F-4CF6-9998-4C150FA5797C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAA05DBA-C77F-4CF6-9998-4C150FA5797C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj" />
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
<ProjectReference Include="..\SushiBarListImplements\SushiBarListImplements.csproj" />
</ItemGroup>
</Project>

247
SushiBar/Sushis/FormSushi.Designer.cs generated Normal file
View File

@ -0,0 +1,247 @@
namespace SushiBarView
{
partial class FormSushi
{
/// <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()
{
labelName = new Label();
labelPrice = new Label();
textBoxName = new TextBox();
textBoxPrice = new TextBox();
groupBoxComponents = new GroupBox();
buttonRefresh = new Button();
buttonDelete = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnName = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonSave = new Button();
buttonCancel = new Button();
groupBoxComponents.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(26, 16);
labelName.Margin = new Padding(2, 0, 2, 0);
labelName.Name = "labelName";
labelName.Size = new Size(79, 21);
labelName.TabIndex = 0;
labelName.Text = "Название";
//
// labelPrice
//
labelPrice.AutoSize = true;
labelPrice.Location = new Point(26, 53);
labelPrice.Margin = new Padding(2, 0, 2, 0);
labelPrice.Name = "labelPrice";
labelPrice.Size = new Size(90, 21);
labelPrice.TabIndex = 1;
labelPrice.Text = "Стоимость";
//
// textBoxName
//
textBoxName.Location = new Point(124, 9);
textBoxName.Margin = new Padding(2, 3, 2, 3);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(261, 28);
textBoxName.TabIndex = 2;
//
// textBoxPrice
//
textBoxPrice.Enabled = false;
textBoxPrice.Location = new Point(124, 53);
textBoxPrice.Margin = new Padding(2, 3, 2, 3);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.Size = new Size(261, 28);
textBoxPrice.TabIndex = 3;
//
// groupBoxComponents
//
groupBoxComponents.Controls.Add(buttonRefresh);
groupBoxComponents.Controls.Add(buttonDelete);
groupBoxComponents.Controls.Add(buttonUpdate);
groupBoxComponents.Controls.Add(buttonAdd);
groupBoxComponents.Controls.Add(dataGridView);
groupBoxComponents.Location = new Point(26, 94);
groupBoxComponents.Margin = new Padding(2, 3, 2, 3);
groupBoxComponents.Name = "groupBoxComponents";
groupBoxComponents.Padding = new Padding(2, 3, 2, 3);
groupBoxComponents.Size = new Size(674, 396);
groupBoxComponents.TabIndex = 5;
groupBoxComponents.TabStop = false;
groupBoxComponents.Text = "Компоненты";
//
// buttonRefresh
//
buttonRefresh.BackColor = Color.FromArgb(255, 192, 192);
buttonRefresh.Location = new Point(483, 330);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(127, 47);
buttonRefresh.TabIndex = 9;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = false;
buttonRefresh.Click += ButtonRef_Click;
//
// buttonDelete
//
buttonDelete.BackColor = Color.FromArgb(255, 192, 192);
buttonDelete.Location = new Point(483, 228);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(127, 47);
buttonDelete.TabIndex = 8;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = false;
buttonDelete.Click += ButtonDel_Click;
//
// buttonUpdate
//
buttonUpdate.BackColor = Color.FromArgb(255, 192, 192);
buttonUpdate.Location = new Point(483, 125);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(127, 47);
buttonUpdate.TabIndex = 7;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = false;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.BackColor = Color.FromArgb(255, 192, 192);
buttonAdd.Location = new Point(483, 27);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(127, 47);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = false;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.BackgroundColor = Color.FromArgb(255, 192, 192);
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount });
dataGridView.Location = new Point(13, 27);
dataGridView.Margin = new Padding(2, 3, 2, 3);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(381, 350);
dataGridView.TabIndex = 5;
//
// ColumnId
//
ColumnId.HeaderText = "id";
ColumnId.MinimumWidth = 6;
ColumnId.Name = "ColumnId";
ColumnId.Visible = false;
//
// ColumnName
//
ColumnName.HeaderText = "Компонент";
ColumnName.MinimumWidth = 6;
ColumnName.Name = "ColumnName";
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
//
// buttonSave
//
buttonSave.BackColor = Color.FromArgb(255, 192, 192);
buttonSave.Location = new Point(428, 521);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(127, 47);
buttonSave.TabIndex = 10;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = false;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.BackColor = Color.FromArgb(255, 192, 192);
buttonCancel.Location = new Point(572, 520);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(127, 47);
buttonCancel.TabIndex = 11;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = false;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSushi
//
AutoScaleDimensions = new SizeF(9F, 21F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.Cornsilk;
ClientSize = new Size(723, 580);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBoxComponents);
Controls.Add(textBoxPrice);
Controls.Add(textBoxName);
Controls.Add(labelPrice);
Controls.Add(labelName);
Font = new Font("Candara", 10.2F, FontStyle.Regular, GraphicsUnit.Point, 204);
Margin = new Padding(3, 4, 3, 4);
Name = "FormSushi";
Text = "Суши";
Load += FormSushi_Load;
groupBoxComponents.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelPrice;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBoxComponents;
private Button buttonRefresh;
private Button buttonDelete;
private Button buttonUpdate;
private Button buttonAdd;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,204 @@
using Microsoft.Extensions.Logging;
using SushiBar;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormSushi : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _sushiComponents;
public int Id { set { _id = value; } }
public FormSushi(ILogger<FormSushi> logger, ISushiLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_sushiComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormSushi_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new SushiSearchModel{ Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.SushiName;
textBoxPrice.Text = view.Price.ToString();
_sushiComponents = view.SushiComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_sushiComponents != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _sushiComponents)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushiComponent));
if (service is FormSushiComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}",
form.ComponentModel.ComponentName, form.Count);
if (_sushiComponents.ContainsKey(form.Id))
{
_sushiComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_sushiComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushiComponent));
if (service is FormSushiComponent form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _sushiComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count} ",
form.ComponentModel.ComponentName, form.Count);
_sushiComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: { ComponentName} - { Count}",
dataGridView.SelectedRows[0].Cells[1].Value);
_sushiComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (_sushiComponents == null || _sushiComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new SushiBindingModel
{
Id = _id ?? 0,
SushiName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
SushiComponents = _sushiComponents
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _sushiComponents)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

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

View File

@ -0,0 +1,137 @@
namespace SushiBarView
{
partial class FormSushiComponent
{
/// <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()
{
labelComponent = new Label();
labelCountComponent = new Label();
buttonSave = new Button();
textBoxComponentCount = new TextBox();
comboBoxComponent = new ComboBox();
buttonCancel = new Button();
SuspendLayout();
//
// labelComponent
//
labelComponent.AutoSize = true;
labelComponent.Location = new Point(35, 39);
labelComponent.Margin = new Padding(4, 0, 4, 0);
labelComponent.Name = "labelComponent";
labelComponent.Size = new Size(107, 24);
labelComponent.TabIndex = 0;
labelComponent.Text = "Компонент";
//
// labelCountComponent
//
labelCountComponent.AutoSize = true;
labelCountComponent.Location = new Point(35, 128);
labelCountComponent.Margin = new Padding(4, 0, 4, 0);
labelCountComponent.Name = "labelCountComponent";
labelCountComponent.Size = new Size(112, 24);
labelCountComponent.TabIndex = 1;
labelCountComponent.Text = "Количество";
//
// buttonSave
//
buttonSave.BackColor = Color.Green;
buttonSave.BackgroundImageLayout = ImageLayout.Center;
buttonSave.Cursor = Cursors.Hand;
buttonSave.ForeColor = SystemColors.ControlLightLight;
buttonSave.Location = new Point(205, 197);
buttonSave.Margin = new Padding(4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(132, 54);
buttonSave.TabIndex = 2;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = false;
buttonSave.Click += ButtonSave_Click;
//
// textBoxComponentCount
//
textBoxComponentCount.Location = new Point(205, 125);
textBoxComponentCount.Margin = new Padding(4);
textBoxComponentCount.Name = "textBoxComponentCount";
textBoxComponentCount.Size = new Size(293, 32);
textBoxComponentCount.TabIndex = 3;
//
// comboBoxComponent
//
comboBoxComponent.Cursor = Cursors.Hand;
comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(205, 36);
comboBoxComponent.Margin = new Padding(4);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(293, 32);
comboBoxComponent.TabIndex = 4;
//
// buttonCancel
//
buttonCancel.BackColor = Color.Green;
buttonCancel.BackgroundImageLayout = ImageLayout.Center;
buttonCancel.Cursor = Cursors.Hand;
buttonCancel.ForeColor = SystemColors.ControlLightLight;
buttonCancel.Location = new Point(362, 197);
buttonCancel.Margin = new Padding(4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(136, 54);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = false;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSushiComponent
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.FromArgb(210, 255, 200);
ClientSize = new Size(542, 280);
Controls.Add(buttonCancel);
Controls.Add(comboBoxComponent);
Controls.Add(textBoxComponentCount);
Controls.Add(buttonSave);
Controls.Add(labelCountComponent);
Controls.Add(labelComponent);
Font = new Font("Candara", 12F, FontStyle.Regular, GraphicsUnit.Point, 204);
Margin = new Padding(4);
Name = "FormSushiComponent";
Text = "Компонент изделия";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelComponent;
private Label labelCountComponent;
private Button buttonSave;
private TextBox textBoxComponentCount;
private ComboBox comboBoxComponent;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,80 @@
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormSushiComponent : Form
{
private readonly List<ComponentViewModel>? _list;
public int Id
{
get
{
return Convert.ToInt32(comboBoxComponent.SelectedValue);
}
set
{
comboBoxComponent.SelectedValue = value;
}
}
public IComponentModel? ComponentModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxComponentCount.Text); }
set
{ textBoxComponentCount.Text = value.ToString(); }
}
public FormSushiComponent(IComponentLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxComponent.DisplayMember = "ComponentName";
comboBoxComponent.ValueMember = "Id";
comboBoxComponent.DataSource = _list;
comboBoxComponent.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxComponentCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComponent.SelectedValue == null)
{
MessageBox.Show("Выберите компонент", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,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>

123
SushiBar/Sushis/FormSushis.Designer.cs generated Normal file
View File

@ -0,0 +1,123 @@
namespace SushiBarView
{
partial class FormSushis
{
/// <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()
{
buttonRefreshSushi = new Button();
buttonRemoveSushi = new Button();
buttonUpdateSushi = new Button();
buttonAddSushi = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRefreshSushi
//
buttonRefreshSushi.Font = new Font("Candara", 12F);
buttonRefreshSushi.Location = new Point(658, 424);
buttonRefreshSushi.Name = "buttonRefreshSushi";
buttonRefreshSushi.Size = new Size(121, 46);
buttonRefreshSushi.TabIndex = 9;
buttonRefreshSushi.Text = "Обновить";
buttonRefreshSushi.UseVisualStyleBackColor = true;
buttonRefreshSushi.Click += buttonRefreshSushis_Click;
//
// buttonRemoveSushi
//
buttonRemoveSushi.Font = new Font("Candara", 12F);
buttonRemoveSushi.Location = new Point(658, 287);
buttonRemoveSushi.Name = "buttonRemoveSushi";
buttonRemoveSushi.Size = new Size(121, 46);
buttonRemoveSushi.TabIndex = 8;
buttonRemoveSushi.Text = "Удалить";
buttonRemoveSushi.UseVisualStyleBackColor = true;
buttonRemoveSushi.Click += buttonRemoveSushi_Click;
//
// buttonUpdateSushi
//
buttonUpdateSushi.Font = new Font("Candara", 12F);
buttonUpdateSushi.Location = new Point(658, 147);
buttonUpdateSushi.Name = "buttonUpdateSushi";
buttonUpdateSushi.Size = new Size(121, 46);
buttonUpdateSushi.TabIndex = 7;
buttonUpdateSushi.Text = "Изменить";
buttonUpdateSushi.UseVisualStyleBackColor = true;
buttonUpdateSushi.Click += buttonUpdateSushi_Click;
//
// buttonAddSushi
//
buttonAddSushi.Font = new Font("Candara", 12F);
buttonAddSushi.Location = new Point(658, 15);
buttonAddSushi.Name = "buttonAddSushi";
buttonAddSushi.Size = new Size(121, 46);
buttonAddSushi.TabIndex = 6;
buttonAddSushi.Text = "Добавить";
buttonAddSushi.UseVisualStyleBackColor = true;
buttonAddSushi.Click += buttonAddSushi_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.DarkSalmon;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(569, 509);
dataGridView.TabIndex = 5;
//
// FormSushis
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(851, 509);
Controls.Add(buttonRefreshSushi);
Controls.Add(buttonRemoveSushi);
Controls.Add(buttonUpdateSushi);
Controls.Add(buttonAddSushi);
Controls.Add(dataGridView);
Name = "FormSushis";
Text = "Суши";
Load += FormSushis_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonRefreshSushi;
private Button buttonRemoveSushi;
private Button buttonUpdateSushi;
private Button buttonAddSushi;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,122 @@
using Microsoft.Extensions.Logging;
using SushiBar;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SushiBarView
{
public partial class FormSushis : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logic;
private int? _id;
public int Id
{
set { _id = value; }
}
public FormSushis(ILogger<FormSushis> logger, ISushiLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormSushis_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["SushiComponents"].Visible = false;
}
_logger.LogInformation("Загрузка списка суш");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки суш");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAddSushi_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushi));
if (service is FormSushi form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpdateSushi_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormSushi));
if (service is FormSushi form)
{
form.Id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonRemoveSushi_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new SushiBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRefreshSushis_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

16
SushiBar/nlog.config Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="https://www.nlog-project.org/schenas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="log-${shortdate}.log"></target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile"></logger>
</rules>
</nlog>
</configuration>

View File

@ -0,0 +1,113 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace SushiBarBusinessLogic.BusinessLogic
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> logger, IComponentStorage componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{ Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}.Id:{ Id}", model.ComponentName, model.Id);
var element = _componentStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_componentStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ComponentName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ComponentName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id: { Id}",
model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel {
ComponentName = model.ComponentName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,124 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using Microsoft.Extensions.Logging;
using SushiBarDataModels.Enums;
namespace SushiBarBusinessLogic.BusinessLogic
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus orderStatus)
{
CheckModel(model, false);
var order = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (order == null)
{
_logger.LogWarning("Change status operation failed. Order not found");
return false;
}
if (order.Status + 1 != orderStatus)
{
_logger.LogWarning("Change status operation failed. Incorrect new status: {orderStatus}. Current status: {Status}",
orderStatus, order.Status);
return false;
}
model.SushiId = order.SushiId;
model.Count = order.Count;
model.Sum = order.Sum;
model.DateCreate = order.DateCreate;
model.Status = orderStatus;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = order.DateImplement;
}
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Change status operation failed");
return false;
}
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (!withParams) return;
if (model.SushiId <= 0)
throw new ArgumentNullException("Неверный идентификатор суши", nameof(model.SushiId));
if (model.Count <= 0)
throw new ArgumentNullException("Количество суш в заказе не может быть меньше нуля или равно нулю", nameof(model.Count));
if (model.Sum <= 0)
throw new ArgumentNullException("Стоимость заказа не может быть меньше нуля", nameof(model.Sum));
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
throw new ArithmeticException("Заказ должен быть выдан позже, чем был создан");
_logger.LogInformation("Sushi. SushiId:{SushiId}. Count:{ Count}. Sum:{ Sum}. Id: { Id}",
model.SushiId, model.Count, model.Sum, model.Id);
}
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,109 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace SushiBarBusinessLogic.BusinessLogic
{
public class SushiLogic : ISushiLogic
{
private readonly ILogger _logger;
private readonly ISushiStorage _sushiStorage;
public SushiLogic(ILogger<SushiLogic> logger, ISushiStorage sushiStorage)
{
_logger = logger;
_sushiStorage = sushiStorage;
}
public List<SushiViewModel>? ReadList(SushiSearchModel? model)
{
_logger.LogInformation("ReadList. SushiName:{SushiName}. Id:{ Id}", model?.SushiName, model?.Id);
var list = model == null ? _sushiStorage.GetFullList() : _sushiStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public SushiViewModel? ReadElement(SushiSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. SushiName:{SushiName}.Id:{ Id}", model.SushiName, model.Id);
var element = _sushiStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(SushiBindingModel model)
{
CheckModel(model);
if (_sushiStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(SushiBindingModel model)
{
CheckModel(model);
if (_sushiStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(SushiBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_sushiStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(SushiBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.SushiName))
{
throw new ArgumentNullException("Нет названия компонента", nameof(model.SushiName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена продукта должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Sushi. SushiName:{SushiName}. Price:{ Price}. Id: { Id}",
model.SushiName, model.Price, model.Id);
var element = _sushiStorage.GetElement(new SushiSearchModel{SushiName = model.SushiName});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,11 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModel
{
public class ComponentBindingModel : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using SushiBarDataModels;
using SushiBarDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarContracts.BindingModel
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int SushiId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModel
{
public class SushiBindingModel : ISushiModel
{
public int Id { get; set; }
public string SushiName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> SushiComponents { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{
List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model);
bool Update(ComponentBindingModel model);
bool Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface ISushiLogic
{
List<SushiViewModel>? ReadList(SushiSearchModel? model);
SushiViewModel? ReadElement(SushiSearchModel model);
bool Create(SushiBindingModel model);
bool Update(SushiBindingModel model);
bool Delete(SushiBindingModel model);
}
}

View File

@ -0,0 +1,9 @@

namespace SushiBarContracts.SearchModel
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarContracts.SearchModel
{
public class OrderSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarContracts.SearchModel
{
public class SushiSearchModel
{
public int? Id { get; set; }
public string? SushiName { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);
ComponentViewModel? Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface ISushiStorage
{
List<SushiViewModel> GetFullList();
List<SushiViewModel> GetFilteredList(SushiSearchModel model);
SushiViewModel? GetElement(SushiSearchModel model);
SushiViewModel? Insert(SushiBindingModel model);
SushiViewModel? Update(SushiBindingModel model);
SushiViewModel? Delete(SushiBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarDataModels\SushiBarDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using System.ComponentModel;
using SushiBarDataModels.Models;
namespace SushiBarContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,38 @@
using System.ComponentModel;
using SushiBarDataModels.Models;
using SushiBarDataModels.Enums;
using SushiBarDataModels;
namespace SushiBarContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int SushiId { get; set; }
[DisplayName("Изделие")]
public string SushiName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,23 @@
using System.ComponentModel;
using SushiBarDataModels.Models;
namespace SushiBarContracts.ViewModels
{
public class SushiViewModel : ISushiModel
{
public int Id { get; set; }
[DisplayName("Название изделия")]
public string SushiName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> SushiComponents
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarDataModels.Models
{
public interface IComponentModel
{
string ComponentName { get; }
double Cost { get; }
}
}

View File

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

View File

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

View File

@ -0,0 +1,9 @@
namespace SushiBarDataModels.Models
{
public interface ISushiModel : IId
{
string SushiName { get; }
double Price { get; }
Dictionary<int, (IComponentModel, int)> SushiComponents { get; }
}
}

View File

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

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,27 @@
using SushiBarListImplements.Models;
namespace SushiBarListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Sushi> Sushis { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Sushis = new List<Sushi>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,102 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarListImplement;
using SushiBarListImplements.Models;
namespace SushiBarListImplements.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataListSingleton _source;
public ComponentStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
var result = new List<ComponentViewModel>();
foreach (var component in _source.Components)
{
result.Add(component.GetViewModel);
}
return result;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
var result = new List<ComponentViewModel>();
if (string.IsNullOrEmpty(model.ComponentName))
{
return result;
}
foreach (var component in _source.Components)
{
if (component.ComponentName.Contains(model.ComponentName))
{
result.Add(component.GetViewModel);
}
}
return result;
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
foreach (var component in _source.Components)
{
if (!string.IsNullOrEmpty(model.ComponentName) && component.ComponentName == model.ComponentName ||
model.Id.HasValue && component.Id == model.Id)
{
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = 1;
foreach (var component in _source.Components)
{
if (model.Id <= component.Id)
{
model.Id = component.Id + 1;
}
}
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
_source.Components.Add(newComponent);
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
foreach (var component in _source.Components)
{
if (component.Id == model.Id)
{
component.Update(model);
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
for (int i = 0; i < _source.Components.Count; ++i)
{
if (_source.Components[i].Id == model.Id)
{
var element = _source.Components[i];
_source.Components.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,122 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarListImplement;
using SushiBarListImplements.Models;
namespace SushiBarListImplements.Implements
{
public class OrderStorage : IOrderStorage
{
private DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AddSushiName(order.GetViewModel));
}
return result;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(order.GetViewModel);
}
}
return result;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
return AddSushiName(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
{
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return AddSushiName(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return AddSushiName(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return AddSushiName(element.GetViewModel);
}
}
return null;
}
private OrderViewModel AddSushiName(OrderViewModel model)
{
foreach (var sushi in _source.Sushis)
{
if (sushi.Id == model.SushiId)
{
model.SushiName = sushi.SushiName;
return model;
}
}
return model;
}
}
}

View File

@ -0,0 +1,109 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarListImplement;
using SushiBarListImplements.Models;
namespace SushiBarListImplements.Implements
{
public class SushiStorage : ISushiStorage
{
private DataListSingleton _source;
public SushiStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<SushiViewModel> GetFullList()
{
var result = new List<SushiViewModel>();
foreach (var order in _source.Sushis)
{
result.Add(order.GetViewModel);
}
return result;
}
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
{
var result = new List<SushiViewModel>();
if (string.IsNullOrEmpty(model.SushiName))
{
return result;
}
foreach (var sushi in _source.Sushis)
{
if (sushi.SushiName.Contains(model.SushiName))
{
result.Add(sushi.GetViewModel);
}
}
return result;
}
public SushiViewModel? GetElement(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName) && !model.Id.HasValue)
{
return null;
}
foreach (var sushi in _source.Sushis)
{
if (!string.IsNullOrEmpty(model.SushiName) && sushi.SushiName == model.SushiName ||
model.Id.HasValue && sushi.Id == model.Id)
{
return sushi.GetViewModel;
}
}
return null;
}
public SushiViewModel? Insert(SushiBindingModel model)
{
model.Id = 1;
foreach (var sushi in _source.Sushis)
{
if (model.Id <= sushi.Id)
{
model.Id = sushi.Id + 1;
}
}
var newSushi = Sushi.Create(model);
if (newSushi == null)
{
return null;
}
_source.Sushis.Add(newSushi);
return newSushi.GetViewModel;
}
public SushiViewModel? Update(SushiBindingModel model)
{
foreach (var sushi in _source.Sushis)
{
if (sushi.Id == model.Id)
{
sushi.Update(model);
return sushi.GetViewModel;
}
}
return null;
}
public SushiViewModel? Delete(SushiBindingModel model)
{
for (int i = 0; i < _source.Sushis.Count; ++i)
{
if (_source.Sushis[i].Id == model.Id)
{
var element = _source.Sushis[i];
_source.Sushis.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,41 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarListImplements.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,62 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using SushiBarDataModels;
using SushiBarDataModels.Enums;
namespace SushiBarListImplements.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int SushiId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; }
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
SushiId = model.SushiId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
SushiId = model.SushiId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
SushiId = SushiId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,49 @@
using SushiBarContracts.BindingModel;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarListImplements.Models
{
public class Sushi : ISushiModel
{
public int Id { get; private set; }
public string SushiName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, (IComponentModel, int)> SushiComponents
{
get;
private set;
} = new Dictionary<int, (IComponentModel, int)>();
public static Sushi? Create(SushiBindingModel? model)
{
if (model == null)
{
return null;
}
return new Sushi()
{
Id = model.Id,
SushiName = model.SushiName,
Price = model.Price,
SushiComponents = model.SushiComponents
};
}
public void Update(SushiBindingModel? model)
{
if (model == null)
{
return;
}
SushiName = model.SushiName;
Price = model.Price;
SushiComponents = model.SushiComponents;
}
public SushiViewModel GetViewModel => new()
{
Id = Id,
SushiName = SushiName,
Price = Price,
SushiComponents = SushiComponents
};
}
}

View File

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