Почти готово

This commit is contained in:
Yunusov_Niyaz 2024-04-04 03:47:27 +04:00
parent 160af345c2
commit 2662170f28
94 changed files with 6549 additions and 52 deletions

View File

@ -3,7 +3,29 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34221.43
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sushi", "Sushi\Sushi.csproj", "{22ED226B-F4B4-4954-8BA1-C7AB04EB9885}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sushi", "Sushi\Sushi.csproj", "{22ED226B-F4B4-4954-8BA1-C7AB04EB9885}"
ProjectSection(ProjectDependencies) = postProject
{2C893C91-AF6B-4263-A53E-6D5DC638D4BF} = {2C893C91-AF6B-4263-A53E-6D5DC638D4BF}
{A55AC6AF-3A99-4C77-9695-2D1991560E37} = {A55AC6AF-3A99-4C77-9695-2D1991560E37}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBusinessLogic", "SushiBusinessLogic\SushiBusinessLogic.csproj", "{2C893C91-AF6B-4263-A53E-6D5DC638D4BF}"
ProjectSection(ProjectDependencies) = postProject
{73931D04-E462-43B0-9421-634BEE5C33AF} = {73931D04-E462-43B0-9421-634BEE5C33AF}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiDataModels", "SushiDataModels\SushiDataModels.csproj", "{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiContracts", "SushiContracts\SushiContracts.csproj", "{73931D04-E462-43B0-9421-634BEE5C33AF}"
ProjectSection(ProjectDependencies) = postProject
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10} = {EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiDatabaseImplement", "SushiDatabaseImplement\SushiDatabaseImplement.csproj", "{A55AC6AF-3A99-4C77-9695-2D1991560E37}"
ProjectSection(ProjectDependencies) = postProject
{73931D04-E462-43B0-9421-634BEE5C33AF} = {73931D04-E462-43B0-9421-634BEE5C33AF}
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10} = {EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +37,22 @@ Global
{22ED226B-F4B4-4954-8BA1-C7AB04EB9885}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22ED226B-F4B4-4954-8BA1-C7AB04EB9885}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22ED226B-F4B4-4954-8BA1-C7AB04EB9885}.Release|Any CPU.Build.0 = Release|Any CPU
{2C893C91-AF6B-4263-A53E-6D5DC638D4BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2C893C91-AF6B-4263-A53E-6D5DC638D4BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2C893C91-AF6B-4263-A53E-6D5DC638D4BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C893C91-AF6B-4263-A53E-6D5DC638D4BF}.Release|Any CPU.Build.0 = Release|Any CPU
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE1EB6E4-0B1B-456B-A40A-6D19DEF56B10}.Release|Any CPU.Build.0 = Release|Any CPU
{73931D04-E462-43B0-9421-634BEE5C33AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73931D04-E462-43B0-9421-634BEE5C33AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73931D04-E462-43B0-9421-634BEE5C33AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73931D04-E462-43B0-9421-634BEE5C33AF}.Release|Any CPU.Build.0 = Release|Any CPU
{A55AC6AF-3A99-4C77-9695-2D1991560E37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A55AC6AF-3A99-4C77-9695-2D1991560E37}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A55AC6AF-3A99-4C77-9695-2D1991560E37}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A55AC6AF-3A99-4C77-9695-2D1991560E37}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

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

View File

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

96
Sushi/Sushi/FormClient.Designer.cs generated Normal file
View File

@ -0,0 +1,96 @@
namespace Sushi
{
partial class FormClient
{
/// <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()
{
textBoxName = new TextBox();
labelName = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(110, 30);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(255, 27);
textBoxName.TabIndex = 0;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 30);
labelName.Name = "labelName";
labelName.Size = new Size(42, 20);
labelName.TabIndex = 2;
labelName.Text = "ФИО";
//
// buttonSave
//
buttonSave.Location = new Point(154, 93);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(271, 93);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormClient
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(390, 142);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelName);
Controls.Add(textBoxName);
Name = "FormClient";
Text = "Компонент";
Load += FormClient_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private Label labelName;
private Button buttonSave;
private Button buttonCancel;
}
}

82
Sushi/Sushi/FormClient.cs Normal file
View File

@ -0,0 +1,82 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.SearchModels;
namespace Sushi
{
public partial class FormClient : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormClient(ILogger<FormClient> logger, IClientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormClient_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение компонента");
var view = _logic.ReadElement(new ClientSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ClientName;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение компонента");
try
{
var model = new ClientBindingModel
{
Id = _id ?? 0,
ClientName = textBoxName.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();
}
}
}

120
Sushi/Sushi/FormClient.resx Normal file
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>

115
Sushi/Sushi/FormClients.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace Sushi
{
partial class FormClients
{
/// <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();
buttonAdd = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(2, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(503, 452);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(581, 38);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(159, 55);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonChange
//
buttonChange.Location = new Point(581, 123);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(159, 55);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(581, 212);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(159, 55);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(581, 313);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(159, 55);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormClients
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormClients";
Text = "Компоненты";
Load += FormClients_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,99 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
namespace Sushi
{
public partial class FormClients : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public FormClients(ILogger<FormClients> logger, IClientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormClients_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["ClientName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClient));
if (service is FormClient form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClient));
if (service is FormClient form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
LoadData();
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ClientBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_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>

118
Sushi/Sushi/FormComponent.Designer.cs generated Normal file
View File

@ -0,0 +1,118 @@
namespace Sushi
{
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()
{
textBoxName = new TextBox();
textBoxPrice = new TextBox();
labelName = new Label();
labelCost = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(110, 12);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(255, 27);
textBoxName.TabIndex = 0;
//
// textBoxPrice
//
textBoxPrice.Location = new Point(110, 60);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.Size = new Size(162, 27);
textBoxPrice.TabIndex = 1;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(16, 15);
labelName.Name = "labelName";
labelName.Size = new Size(77, 20);
labelName.TabIndex = 2;
labelName.Text = "Название";
//
// labelPhone
//
labelCost.AutoSize = true;
labelCost.Location = new Point(16, 63);
labelCost.Name = "labelPhone";
labelCost.Size = new Size(45, 20);
labelCost.TabIndex = 3;
labelCost.Text = "Цена";
//
// buttonSave
//
buttonSave.Location = new Point(154, 93);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(271, 93);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(390, 142);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelCost);
Controls.Add(labelName);
Controls.Add(textBoxPrice);
Controls.Add(textBoxName);
Name = "FormComponent";
Text = "Компонент";
Load += FormComponent_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private TextBox textBoxPrice;
private Label labelName;
private Label labelCost;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,84 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.SearchModels;
namespace Sushi
{
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 FormComponent_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ComponentName;
textBoxPrice.Text = view.ComponentPrice.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Ñîõðàíåíèå êîìïîíåíòà");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxName.Text,
ComponentPrice = Convert.ToInt32(textBoxPrice.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();
}
}
}

115
Sushi/Sushi/FormComponents.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace Sushi
{
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();
buttonAdd = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(2, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(503, 452);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(581, 38);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(159, 55);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonChange
//
buttonChange.Location = new Point(581, 123);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(159, 55);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(581, 212);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(159, 55);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(581, 313);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(159, 55);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormComponents";
Text = "Компоненты";
Load += FormComponents_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,99 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
namespace Sushi
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
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 ButtonAdd_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 ButtonUpd_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 ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ComponentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_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>

145
Sushi/Sushi/FormCreateOrder.Designer.cs generated Normal file
View File

@ -0,0 +1,145 @@
namespace Sushi
{
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()
{
comboBoxSushi = new ComboBox();
comboBoxClient = new ComboBox();
comboBoxEmployee = new ComboBox();
labelSushi = new Label();
labelClient = new Label();
labelEmployee = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// comboBoxSushi
//
comboBoxSushi.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSushi.FormattingEnabled = true;
comboBoxSushi.Location = new Point(130, 19);
comboBoxSushi.Name = "comboBoxSushi";
comboBoxSushi.Size = new Size(353, 28);
comboBoxSushi.TabIndex = 0;
//
// comboBoxClient
//
comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxClient.FormattingEnabled = true;
comboBoxClient.Location = new Point(130, 53);
comboBoxClient.Name = "comboBoxClient";
comboBoxClient.Size = new Size(353, 28);
comboBoxClient.TabIndex = 0;
//
// comboBoxEmployee
//
comboBoxEmployee.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxEmployee.Location = new Point(130, 87);
comboBoxEmployee.Name = "comboBoxEmployee";
comboBoxEmployee.Size = new Size(353, 28);
comboBoxEmployee.TabIndex = 8;
//
// labelSushi
//
labelSushi.AutoSize = true;
labelSushi.Location = new Point(21, 22);
labelSushi.Name = "labelSushi";
labelSushi.Size = new Size(54, 20);
labelSushi.TabIndex = 3;
labelSushi.Text = "Услуга";
//
// labelClient
//
labelClient.AutoSize = true;
labelClient.Location = new Point(21, 56);
labelClient.Name = "labelClient";
labelClient.Size = new Size(58, 20);
labelClient.TabIndex = 3;
labelClient.Text = "Клиент";
//
// labelEmployee
//
labelEmployee.AutoSize = true;
labelEmployee.Location = new Point(21, 90);
labelEmployee.Name = "labelEmployee";
labelEmployee.Size = new Size(60, 20);
labelEmployee.TabIndex = 3;
labelEmployee.Text = "Мастер";
//
// buttonSave
//
buttonSave.Location = new Point(278, 157);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(93, 26);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(386, 157);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(97, 26);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormCreateAppointment
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(515, 202);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelSushi);
Controls.Add(comboBoxSushi);
Controls.Add(labelEmployee);
Controls.Add(comboBoxEmployee);
Controls.Add(labelClient);
Controls.Add(comboBoxClient);
Name = "FormCreateOrder";
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxSushi;
private ComboBox comboBoxClient;
private ComboBox comboBoxEmployee;
private Label labelSushi;
private Label labelClient;
private Label labelEmployee;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,140 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.BusinessLogicsContracts;
using SushiContracts.SearchModels;
namespace Sushi
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logicS;
private readonly IOrderLogic _logicO;
private readonly IClientLogic _logicC;
private readonly IEmployeeLogic _logicE;
private int? _id;
public int Id { set { _id = value; } }
public FormCreateOrder(ILogger<FormCreateOrder> logger, ISushiLogic logicS, IOrderLogic logicO, IClientLogic logicC, IEmployeeLogic logicE)
{
InitializeComponent();
_logger = logger;
_logicS = logicS;
_logicO = logicO;
_logicC = logicC;
_logicE = logicE;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка блюда для заказа");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxSushi.DisplayMember = "SushiName";
comboBoxSushi.ValueMember = "Id";
comboBoxSushi.DataSource = list;
comboBoxSushi.SelectedItem = null;
}
var listC = _logicC.ReadList(null);
if (listC != null)
{
comboBoxClient.DisplayMember = "ClientName";
comboBoxClient.ValueMember = "Id";
comboBoxClient.DataSource = listC;
comboBoxClient.SelectedItem = null;
}
var listE = _logicE.ReadList(null);
if (listE != null)
{
comboBoxEmployee.DisplayMember = "EmployeeName";
comboBoxEmployee.ValueMember = "Id";
comboBoxEmployee.DataSource = listE;
comboBoxEmployee.SelectedItem = null;
}
_logger.LogInformation("Блюдо загружено");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки блюда");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
//private void CalcSum()
//{
// if (comboBoxRepair.SelectedValue != null &&
// !string.IsNullOrEmpty(textBoxCount.Text))
// {
// try
// {
// int id = Convert.ToInt32(comboBoxRepair.SelectedValue);
// var repair = _logicS.ReadElement(new SushiSearchModel
// {
// Id
// = id
// });
// int count = Convert.ToInt32(textBoxCount.Text);
// textBoxSum.Text = Math.Round(count * (repair?.Price ?? 0),
// 2).ToString();
// _logger.LogInformation("Расчет суммы заказа");
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка расчета суммы заказа");
// MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
// }
// }
//}
//private void TextBoxCount_TextChanged(object sender, EventArgs e)
//{
// CalcSum();
//}
//private void TextBoxSum_TextChanged(object sender, EventArgs e)
//{
// CalcSum();
//}
//private void ComboBoxRepair_SelectedIndexChanged(object sender, EventArgs e)
//{
// CalcSum();
//}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxSushi.SelectedValue == null || comboBoxClient.SelectedValue == null || comboBoxEmployee.SelectedValue == null)
{
MessageBox.Show("Выберите компьютер", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.Create(new OrderBindingModel
{
SushiId = Convert.ToInt32(comboBoxSushi.SelectedValue),
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
EmployeeId = Convert.ToInt32(comboBoxEmployee.SelectedValue),
Time = DateTime.UtcNow
});
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>

140
Sushi/Sushi/FormEmployee.Designer.cs generated Normal file
View File

@ -0,0 +1,140 @@
namespace Sushi
{
partial class FormEmployee
{
/// <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()
{
textBoxName = new TextBox();
textBoxPhone = new TextBox();
textBoxPosition = new TextBox();
labelPosition = new Label();
labelName = new Label();
labelPhone = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(110, 12);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(255, 27);
textBoxName.TabIndex = 0;
//
// textBoxPhone
//
textBoxPhone.Location = new Point(110, 56);
textBoxPhone.Name = "textBoxPhone";
textBoxPhone.Size = new Size(162, 27);
textBoxPhone.TabIndex = 1;
//
// textBoxPosition
//
textBoxPosition.Location = new Point(110, 102);
textBoxPosition.Name = "textBoxPosition";
textBoxPosition.Size = new Size(255, 27);
textBoxPosition.TabIndex = 6;
//
// labelPosition
//
labelPosition.AutoSize = true;
labelPosition.Location = new Point(16, 109);
labelPosition.Name = "labelPosition";
labelPosition.Size = new Size(86, 20);
labelPosition.TabIndex = 7;
labelPosition.Text = "Должность";
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(16, 15);
labelName.Name = "labelName";
labelName.Size = new Size(42, 20);
labelName.TabIndex = 2;
labelName.Text = "ФИО";
//
// labelPhone
//
labelPhone.AutoSize = true;
labelPhone.Location = new Point(16, 63);
labelPhone.Name = "labelPhone";
labelPhone.Size = new Size(69, 20);
labelPhone.TabIndex = 3;
labelPhone.Text = "Телефон";
//
// buttonSave
//
buttonSave.Location = new Point(171, 135);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(271, 135);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormEmployee
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(390, 178);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelPhone);
Controls.Add(labelName);
Controls.Add(textBoxPhone);
Controls.Add(textBoxName);
Controls.Add(textBoxPosition);
Controls.Add(labelPosition);
Name = "FormEmployee";
Text = "Сотрудник";
Load += FormEmployee_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private TextBox textBoxPhone;
private TextBox textBoxPosition;
private Label labelName;
private Label labelPhone;
private Label labelPosition;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,86 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.SearchModels;
namespace Sushi
{
public partial class FormEmployee : Form
{
private readonly ILogger _logger;
private readonly IEmployeeLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormEmployee(ILogger<FormEmployee> logger, IEmployeeLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormEmployee_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение компонента");
var view = _logic.ReadElement(new EmployeeSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.EmployeeName;
textBoxPhone.Text = view.EmployeePhone.ToString();
textBoxPosition.Text = view.EmployeePosition;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение компонента");
try
{
var model = new EmployeeBindingModel
{
Id = _id ?? 0,
EmployeeName = textBoxName.Text,
EmployeePhone = Convert.ToInt64(textBoxPhone.Text),
EmployeePosition = textBoxPosition.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>

115
Sushi/Sushi/FormEmployees.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace Sushi
{
partial class FormEmployees
{
/// <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();
buttonAdd = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(2, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(503, 452);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(581, 38);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(159, 55);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonChange
//
buttonChange.Location = new Point(581, 123);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(159, 55);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(581, 212);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(159, 55);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(581, 313);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(159, 55);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormComponents";
Text = "Компоненты";
Load += FormEmployees_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,99 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
namespace Sushi
{
public partial class FormEmployees : Form
{
private readonly ILogger _logger;
private readonly IEmployeeLogic _logic;
public FormEmployees(ILogger<FormEmployees> logger, IEmployeeLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormEmployees_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["EmployeeName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEmployee));
if (service is FormEmployee form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEmployee));
if (service is FormEmployee form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
LoadData();
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new EmployeeBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_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>

177
Sushi/Sushi/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,177 @@
namespace Sushi
{
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()
{
menuStrip = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem();
услугиToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
мастераToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreate = new Button();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1209, 28);
menuStrip.TabIndex = 0;
menuStrip.Text = "Меню справочников";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, услугиToolStripMenuItem, клиентыToolStripMenuItem, мастераToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// компонентыToolStripMenuItem
//
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(224, 26);
компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += ComponentsStripMenuItem_Click;
//
// услугиToolStripMenuItem
//
услугиToolStripMenuItem.Name = "услугиToolStripMenuItem";
услугиToolStripMenuItem.Size = new Size(224, 26);
услугиToolStripMenuItem.Text = "Блюда";
услугиToolStripMenuItem.Click += ServicesStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(224, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += ClientsStripMenuItem_Click;
//
// мастераToolStripMenuItem
//
мастераToolStripMenuItem.Name = астераToolStripMenuItem";
мастераToolStripMenuItem.Size = new Size(224, 26);
мастераToolStripMenuItem.Text = "Мастера";
мастераToolStripMenuItem.Click += EmployeesStripMenuItem_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(6, 32);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(970, 419);
dataGridView.TabIndex = 1;
//
// buttonCreate
//
buttonCreate.Location = new Point(999, 46);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(187, 37);
buttonCreate.TabIndex = 2;
buttonCreate.Text = "Создать заказ";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += CreateCreateButton_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(999, 123);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(187, 37);
buttonUpdate.TabIndex = 3;
buttonUpdate.Text = "Отдать на выполнение";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(999, 196);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(187, 37);
buttonDelete.TabIndex = 4;
buttonDelete.Text = "Заказ готов";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(999, 272);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(187, 37);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить список";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += RefreshButton_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1209, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonCreate);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Суши";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem услугиToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem мастераToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreate;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonRefresh;
}
}

142
Sushi/Sushi/FormMain.cs Normal file
View File

@ -0,0 +1,142 @@
using Sushi;
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicsContracts;
namespace Sushi
{
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 ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ClientsStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void EmployeesStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEmployees));
if (service is FormEmployees form)
{
form.ShowDialog();
}
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _OrderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ServiceId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["EmployeeId"].Visible = false;
dataGridView.Columns["ServiceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ServicesStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushies));
if (service is FormSushies form)
{
form.ShowDialog();
}
}
private void CreateCreateButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
LoadData();
}
}
}
private void ButtonDelete_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 (!_OrderLogic.Delete(new OrderBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

123
Sushi/Sushi/FormMain.resx Normal file
View File

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

231
Sushi/Sushi/FormSushi.Designer.cs generated Normal file
View File

@ -0,0 +1,231 @@
namespace Sushi
{
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();
labelCost = new Label();
groupBoxComponents = new GroupBox();
buttonRefresh = new Button();
buttonDelete = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridViewComponents = new DataGridView();
textBoxName = new TextBox();
textBoxCost = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
ColumnId = new DataGridViewTextBoxColumn();
ComponentNameColumn = new DataGridViewTextBoxColumn();
CountColumn = new DataGridViewTextBoxColumn();
groupBoxComponents.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewComponents).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(25, 18);
labelName.Name = "labelName";
labelName.Size = new Size(80, 20);
labelName.TabIndex = 0;
labelName.Text = "Название:";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(25, 58);
labelCost.Name = "labelCost";
labelCost.Size = new Size(86, 20);
labelCost.TabIndex = 1;
labelCost.Text = "Стоимость:";
//
// groupBoxComponents
//
groupBoxComponents.Controls.Add(buttonRefresh);
groupBoxComponents.Controls.Add(buttonDelete);
groupBoxComponents.Controls.Add(buttonUpdate);
groupBoxComponents.Controls.Add(buttonAdd);
groupBoxComponents.Controls.Add(dataGridViewComponents);
groupBoxComponents.Location = new Point(12, 97);
groupBoxComponents.Name = "groupBoxComponents";
groupBoxComponents.Size = new Size(776, 303);
groupBoxComponents.TabIndex = 2;
groupBoxComponents.TabStop = false;
groupBoxComponents.Text = "Компоненты";
//
// buttonRefresh
//
buttonRefresh.Location = new Point(634, 191);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(94, 29);
buttonRefresh.TabIndex = 7;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(634, 142);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(94, 29);
buttonDelete.TabIndex = 6;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(634, 92);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(94, 29);
buttonUpdate.TabIndex = 5;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(634, 44);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(94, 29);
buttonAdd.TabIndex = 4;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewComponents
//
dataGridViewComponents.BackgroundColor = Color.White;
dataGridViewComponents.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewComponents.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ComponentNameColumn, CountColumn });
dataGridViewComponents.Location = new Point(13, 23);
dataGridViewComponents.Name = "dataGridViewComponents";
dataGridViewComponents.RowHeadersWidth = 51;
dataGridViewComponents.RowTemplate.Height = 29;
dataGridViewComponents.Size = new Size(573, 274);
dataGridViewComponents.TabIndex = 0;
//
// textBoxName
//
textBoxName.Location = new Point(117, 18);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(404, 27);
textBoxName.TabIndex = 1;
//
// textBoxCost
//
textBoxCost.Location = new Point(117, 58);
textBoxCost.Name = "textBoxCost";
textBoxCost.ReadOnly = true;
textBoxCost.Size = new Size(229, 27);
textBoxCost.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(546, 406);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(646, 406);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// ColumnId
//
ColumnId.HeaderText = "Идентификатор";
ColumnId.MinimumWidth = 6;
ColumnId.Name = "ColumnId";
ColumnId.Visible = false;
ColumnId.Width = 125;
//
// ComponentNameColumn
//
ComponentNameColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ComponentNameColumn.HeaderText = "Компонент";
ComponentNameColumn.MinimumWidth = 320;
ComponentNameColumn.Name = "ComponentNameColumn";
//
// CountColumn
//
CountColumn.HeaderText = "Количество";
CountColumn.MinimumWidth = 6;
CountColumn.Name = "CountColumn";
CountColumn.Width = 200;
//
// FormSushi
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCost);
Controls.Add(textBoxName);
Controls.Add(groupBoxComponents);
Controls.Add(labelCost);
Controls.Add(labelName);
Name = "FormSushi";
StartPosition = FormStartPosition.CenterScreen;
Text = "Ремонт";
Load += FormSushi_Load;
groupBoxComponents.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewComponents).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelCost;
private GroupBox groupBoxComponents;
private DataGridView dataGridViewComponents;
private Button buttonRefresh;
private Button buttonDelete;
private Button buttonUpdate;
private Button buttonAdd;
private TextBox textBoxName;
private TextBox textBoxCost;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ComponentNameColumn;
private DataGridViewTextBoxColumn CountColumn;
}
}

212
Sushi/Sushi/FormSushi.cs Normal file
View File

@ -0,0 +1,212 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicsContracts;
using SushiContracts.SearchModels;
using SushiDataModels;
namespace Sushi
{
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;
textBoxCost.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)
{
dataGridViewComponents.Rows.Clear();
foreach (var pc in _SushiComponents)
{
dataGridViewComponents.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 });
}
textBoxCost.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 (dataGridViewComponents.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormSushiComponent));
if (service is FormSushiComponent form)
{
int id =
Convert.ToInt32(dataGridViewComponents.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 (dataGridViewComponents.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: { ComponentName} - { Count}", dataGridViewComponents.SelectedRows[0].Cells[1].Value);
_SushiComponents?.Remove(Convert.ToInt32(dataGridViewComponents.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(textBoxCost.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(textBoxCost.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?.ComponentPrice ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

129
Sushi/Sushi/FormSushi.resx Normal file
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="ComponentNameColumn.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="CountColumn.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

120
Sushi/Sushi/FormSushiComponent.Designer.cs generated Normal file
View File

@ -0,0 +1,120 @@
namespace Sushi
{
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();
labelCount = new Label();
comboBoxComponent = new ComboBox();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelComponent
//
labelComponent.AutoSize = true;
labelComponent.Location = new Point(20, 23);
labelComponent.Name = "labelComponent";
labelComponent.Size = new Size(91, 20);
labelComponent.TabIndex = 0;
labelComponent.Text = "Компонент:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(20, 70);
labelCount.Name = "labelCount";
labelCount.Size = new Size(93, 20);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// comboBoxComponent
//
comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(124, 23);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(301, 28);
comboBoxComponent.TabIndex = 2;
//
// textBoxCount
//
textBoxCount.Location = new Point(124, 70);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(301, 27);
textBoxCount.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(231, 118);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(331, 118);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormRepairComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(439, 160);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(comboBoxComponent);
Controls.Add(labelCount);
Controls.Add(labelComponent);
Name = "FormRepairComponent";
StartPosition = FormStartPosition.CenterScreen;
Text = "Компонент ремонта";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelComponent;
private Label labelCount;
private ComboBox comboBoxComponent;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,75 @@

using SushiContracts.BusinessLogicContracts;
using SushiContracts.ViewModels;
using SushiDataModels;
namespace Sushi
{
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(textBoxCount.Text); }
set
{ textBoxCount.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(textBoxCount.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>

116
Sushi/Sushi/FormSushies.Designer.cs generated Normal file
View File

@ -0,0 +1,116 @@
namespace Sushi
{
partial class FormSushies
{
/// <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();
buttonAdd = new Button();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 2);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(593, 450);
dataGridView.TabIndex = 1;
//
// buttonAdd
//
buttonAdd.Location = new Point(638, 38);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(120, 39);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(638, 94);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(120, 39);
buttonUpdate.TabIndex = 3;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(638, 151);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(120, 39);
buttonDelete.TabIndex = 4;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(638, 211);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(120, 39);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// FormSushies
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormSushies";
StartPosition = FormStartPosition.CenterScreen;
Text = "Суши";
Load += FormSushies_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonRefresh;
}
}

106
Sushi/Sushi/FormSushies.cs Normal file
View File

@ -0,0 +1,106 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicsContracts;
namespace Sushi
{
public partial class FormSushies : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logic;
public FormSushies(ILogger<FormSushies> logger, ISushiLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormSushies_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 ButtonAdd_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 ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushi));
if (service is FormSushi form)
{
var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление ремонта");
try
{
if (!_logic.Delete(new SushiBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления ремонта");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_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>

View File

@ -1,9 +1,24 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SushiBusinessLogic;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.BusinessLogicsContracts;
using SushiContracts.StorageContracts;
using SushiContracts.StoragesContracts;
using SushiDatabaseImplement.implements;
using SushiDatabaseImplement.Implements;
using SushiShopBusinessLogic;
using SushiShopDatabaseImplement.Implements;
namespace Sushi
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
@ -11,7 +26,38 @@ namespace Sushi
// 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>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<IEmployeeLogic, EmployeeLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IEmployeeStorage, EmployeeStorage>();
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormClient>();
services.AddTransient<FormClients>();
services.AddTransient<FormEmployee>();
services.AddTransient<FormEmployees>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormSushies>();
services.AddTransient<FormMain>();
services.AddTransient<FormSushiComponent>();
}
}
}

View File

@ -8,4 +8,22 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBusinessLogic\SushiBusinessLogic.csproj" />
<ProjectReference Include="..\SushiContracts\SushiContracts.csproj" />
<ProjectReference Include="..\SushiDatabaseImplement\SushiDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,111 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
namespace SushiBusinessLogic
{
public class ClientLogic : IClientLogic
{
public readonly ILogger _logger;
public readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{
_logger = logger;
_clientStorage = clientStorage;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{
_logger.LogInformation("ReadList. ClientName:{ClientName}.Id:{ Id}", model?.ClientName, model?.Id);
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ClientViewModel? ReadElement(ClientSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ClientName:{ClientName}.Id:{ Id}", model.ClientName, model.Id);
var element = _clientStorage.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(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public bool Update(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(ClientBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ClientName))
{
throw new ArgumentNullException("Нет имени клиента",
nameof(model.ClientName));
}
_logger.LogInformation("Client. ClientName:{ClientName}. Id: { Id}", model.ClientName, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel
{
ClientName = model.ClientName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Клиент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,109 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
using Microsoft.Extensions.Logging;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.StorageContracts;
namespace SushiShopBusinessLogic
{
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.ComponentPrice <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.ComponentPrice));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id: { Id}", model.ComponentName, model.ComponentPrice, 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,115 @@
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace SushiBusinessLogic
{
public class EmployeeLogic : IEmployeeLogic
{
public readonly ILogger _logger;
public readonly IEmployeeStorage _employeeStorage;
public EmployeeLogic(ILogger<EmployeeLogic> logger, IEmployeeStorage employeeStorage)
{
_logger = logger;
_employeeStorage = employeeStorage;
}
public List<EmployeeViewModel>? ReadList(EmployeeSearchModel? model)
{
_logger.LogInformation("ReadList. EmployeeName:{EmployeeName}.Id:{ Id}", model?.EmployeeName, model?.Id);
var list = model == null ? _employeeStorage.GetFullList() : _employeeStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public EmployeeViewModel? ReadElement(EmployeeSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. EmployeeName:{EmployeeName}.Id:{ Id}", model.EmployeeName, model.Id);
var element = _employeeStorage.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(EmployeeBindingModel model)
{
CheckModel(model);
if (_employeeStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(EmployeeBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_employeeStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public bool Update(EmployeeBindingModel model)
{
CheckModel(model);
if (_employeeStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(EmployeeBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.EmployeeName))
{
throw new ArgumentNullException("Нет имени сотрудника",
nameof(model.EmployeeName));
}
if (model.EmployeePhone < 80000000000)
{
throw new ArgumentNullException("Введен некорректный номер телефона", nameof(model.EmployeePhone));
}
_logger.LogInformation("employee. EmployeeName:{EmployeeName}.EmployeePhone:{ EmployeePhone}. Id: { Id}", model.EmployeeName, model.EmployeePhone, model.Id);
var element = _employeeStorage.GetElement(new EmployeeSearchModel
{
EmployeeName = model.EmployeeName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Сотрудник с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,107 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicsContracts;
using SushiContracts.SearchModels;
using SushiContracts.StoragesContracts;
using SushiContracts.ViewModels;
using SushiDataModels.Enums;
namespace SushiBusinessLogic
{
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 OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.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(OrderBindingModel model)
{
CheckModel(model);
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(OrderBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_orderStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public bool Update(OrderBindingModel model)
{
CheckModel(model);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update 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.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
}
_logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id);
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiContracts\SushiContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,113 @@
using Microsoft.Extensions.Logging;
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicsContracts;
using SushiContracts.SearchModels;
using SushiContracts.StoragesContracts;
using SushiContracts.ViewModels;
namespace SushiBusinessLogic
{
public class SushiLogic : ISushiLogic
{
private readonly ILogger _logger;
private readonly ISushiStorage _DishStorage;
public SushiLogic(ILogger<SushiLogic> logger, ISushiStorage DishStorage)
{
_logger = logger;
_DishStorage = DishStorage;
}
public List<SushiViewModel>? ReadList(SushiSearchModel? model)
{
_logger.LogInformation("ReadList. DishName:{DishName}. Id:{ Id}", model?.SushiName, model?.Id);
var list = model == null ? _DishStorage.GetFullList() :
_DishStorage.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. DishName:{DishName}.Id:{ Id}", model.SushiName, model.Id);
var element = _DishStorage.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 (_DishStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(SushiBindingModel model)
{
CheckModel(model);
if (_DishStorage.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 (_DishStorage.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("Нет названия блюдаs",
nameof(model.SushiName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена блюдо должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Dish. Dish:{Dish}. Price:{ Price }. Id: { Id}", model.SushiName, model.Price, model.Id);
var element = _DishStorage.GetElement(new SushiSearchModel
{
SushiName = model.SushiName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,10 @@
using SushiDataModels;
namespace SushiContracts.BindingModels
{
public class ClientBindingModel : IClientModel
{
public int Id { get; set; }
public string ClientName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,13 @@
using SushiDataModels;
namespace SushiContracts.BindingModels
{
public class ComponentBindingModel : IComponentModel
{
public string ComponentName { get; set; } = string.Empty;
public int ComponentPrice { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using SushiDataModels;
namespace SushiContracts.BindingModels
{
public class EmployeeBindingModel : IEmployeeModel
{
public string EmployeeName { get; set; } = string.Empty;
public string EmployeePosition { get; set; } = string.Empty;
public long EmployeePhone { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using SushiDataModels.Enums;
using SushiDataModels;
namespace SushiContracts.BindingModels
{
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 int ClientId { get; set; }
public int EmployeeId { get; set; }
public DateTime Time { 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 SushiDataModels;
namespace SushiContracts.BindingModels
{
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 SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.BusinessLogicContracts
{
public interface IClientLogic
{
List<ClientViewModel>? ReadList(ClientSearchModel? model);
ClientViewModel? ReadElement(ClientSearchModel model);
bool Create(ClientBindingModel model);
bool Update(ClientBindingModel model);
bool Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.BusinessLogicContracts
{
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 SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.BusinessLogicContracts
{
public interface IEmployeeLogic
{
List<EmployeeViewModel>? ReadList(EmployeeSearchModel? model);
EmployeeViewModel? ReadElement(EmployeeSearchModel model);
bool Create(EmployeeBindingModel model);
bool Update(EmployeeBindingModel model);
bool Delete(EmployeeBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool Create(OrderBindingModel model);
bool Update(OrderBindingModel model);
bool Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.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,8 @@
namespace SushiContracts.SearchModels
{
public class ClientSearchModel
{
public int? Id { get; set; }
public string? ClientName { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiContracts.SearchModels
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiContracts.SearchModels
{
public class EmployeeSearchModel
{
public int? Id { get; set; }
public string? EmployeeName { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace SushiContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
}
}

View File

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

View File

@ -0,0 +1,16 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.StorageContracts
{
public interface IClientStorage
{
List<ClientViewModel> GetFullList();
List<ClientViewModel> GetFilteredList(ClientSearchModel model);
ClientViewModel? GetElement(ClientSearchModel model);
ClientViewModel? Insert(ClientBindingModel model);
ClientViewModel? Update(ClientBindingModel model);
ClientViewModel? Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.StorageContracts
{
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 SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.StorageContracts
{
public interface IEmployeeStorage
{
List<EmployeeViewModel> GetFullList();
List<EmployeeViewModel> GetFilteredList(EmployeeSearchModel model);
EmployeeViewModel? GetElement(EmployeeSearchModel model);
EmployeeViewModel? Insert(EmployeeBindingModel model);
EmployeeViewModel? Update(EmployeeBindingModel model);
EmployeeViewModel? Delete(EmployeeBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.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,17 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.ViewModels;
namespace SushiContracts.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,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiDataModels\SushiDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
using SushiDataModels;
using System.ComponentModel;
namespace SushiContracts.ViewModels
{
public class ClientViewModel : IClientModel
{
public int Id { get; set; }
[DisplayName("Имя")]
public string ClientName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,16 @@
using SushiDataModels;
using System.ComponentModel;
namespace SushiContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public int ComponentPrice { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using SushiDataModels;
using System.ComponentModel;
namespace SushiContracts.ViewModels
{
public class EmployeeViewModel : IEmployeeModel
{
public int Id { get; set; }
[DisplayName("Имя")]
public string EmployeeName { get; set; } = string.Empty;
[DisplayName("Должность")]
public string EmployeePosition { get; set; } = string.Empty;
[DisplayName("Телефон")]
public long EmployeePhone { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using SushiDataModels;
using SushiDataModels.Enums;
using System.ComponentModel;
namespace SushiContracts.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,15 @@
using SushiDataModels;
using System.ComponentModel;
namespace SushiContracts.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,7 @@
namespace SushiDataModels
{
public interface IClientModel : IId
{
string ClientName { get; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiDataModels
{
public interface IComponentModel : IId
{
string ComponentName { get; }
int ComponentPrice { get; }
}
}

View File

@ -0,0 +1,9 @@
namespace SushiDataModels
{
public interface IEmployeeModel : IId
{
string EmployeeName { get; }
string EmployeePosition { get; }
long EmployeePhone { get; }
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,77 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
using SushiDatabaseImplement.Models;
using SushiDatabaseImplement;
namespace SushiDatabaseImplement.Implements
{
public class ClientStorage : IClientStorage
{
public List<ClientViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Clients.Select(x => x.GetViewModel).ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.ClientName))
{
return new();
}
using var context = new SushiDatabase();
return context.Clients.Where(x => x.ClientName.Contains(model.ClientName)).Select(x => x.GetViewModel).ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.ClientName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return context.Clients.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ClientName) && x.ClientName == model.ClientName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
using var context = new SushiDatabase();
context.Clients.Add(newClient);
context.SaveChanges();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new SushiDatabase();
var client = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,76 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
using SushiDatabaseImplement.Models;
namespace SushiDatabaseImplement.implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Components.Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new SushiDatabase();
return context.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return context.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new SushiDatabase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new SushiDatabase();
var client = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,76 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
using SushiDatabaseImplement.Models;
namespace SushiDatabaseImplement.Implements
{
public class EmployeeStorage : IEmployeeStorage
{
public List<EmployeeViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Employees.Select(x => x.GetViewModel).ToList();
}
public List<EmployeeViewModel> GetFilteredList(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.EmployeeName))
{
return new();
}
using var context = new SushiDatabase();
return context.Employees.Where(x => x.EmployeeName.Contains(model.EmployeeName)).Select(x => x.GetViewModel).ToList();
}
public EmployeeViewModel? GetElement(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.EmployeeName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return context.Employees.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EmployeeName) && x.EmployeeName == model.EmployeeName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public EmployeeViewModel? Insert(EmployeeBindingModel model)
{
var newEmployee = Employee.Create(model);
if (newEmployee == null)
{
return null;
}
using var context = new SushiDatabase();
context.Employees.Add(newEmployee);
context.SaveChanges();
return newEmployee.GetViewModel;
}
public EmployeeViewModel? Update(EmployeeBindingModel model)
{
using var context = new SushiDatabase();
var client = context.Employees.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public EmployeeViewModel? Delete(EmployeeBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Employees.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Employees.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,95 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StoragesContracts;
using SushiContracts.ViewModels;
using SushiDatabaseImplement;
using SushiShopDatabaseImplement.Models;
namespace SushiShopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Orders
.Select(x => AccessSushisStorage(x.GetViewModel))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new SushiDatabase();
return context.Orders
.Where(x => x.Id == model.Id)
.Select(x => AccessSushisStorage(x.GetViewModel))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return AccessSushisStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel);
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new SushiDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessSushisStorage(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SushiDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessSushisStorage(order.GetViewModel);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return AccessSushisStorage(element.GetViewModel);
}
return null;
}
public static OrderViewModel AccessSushisStorage(OrderViewModel model)
{
if (model == null)
return null;
using var context = new SushiDatabase();
foreach (var Sushis in context.Sushies)
{
if (Sushis.Id == model.SushiId)
{
model.SushiName = Sushis.SushiName;
break;
}
}
return model;
}
}
}

View File

@ -0,0 +1,107 @@
using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StoragesContracts;
using SushiContracts.ViewModels;
using SushiShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using SushiDatabaseImplement;
using SushiDatabaseImplement.Models;
namespace SushiShopDatabaseImplement.Implements
{
public class SushiStorage : ISushiStorage
{
public List<SushiViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Sushies
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName))
{
return new();
}
using var context = new SushiDatabase();
return context.Sushies
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.SushiName.Contains(model.SushiName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public SushiViewModel? GetElement(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return context.Sushies
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SushiName) &&
x.SushiName == model.SushiName) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public SushiViewModel? Insert(SushiBindingModel model)
{
using var context = new SushiDatabase();
var newSushi = Sushi.Create(context, model);
if (newSushi == null)
{
return null;
}
context.Sushies.Add(newSushi);
context.SaveChanges();
return newSushi.GetViewModel;
}
public SushiViewModel? Update(SushiBindingModel model)
{
using var context = new SushiDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var Sushi = context.Sushies.FirstOrDefault(rec =>
rec.Id == model.Id);
if (Sushi == null)
{
return null;
}
Sushi.Update(model);
context.SaveChanges();
Sushi.UpdateComponents(context, model);
transaction.Commit();
return Sushi.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public SushiViewModel? Delete(SushiBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Sushies
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Sushies.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,238 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SushiDatabaseImplement;
#nullable disable
namespace SushiDatabaseImplement.Migrations
{
[DbContext(typeof(SushiDatabase))]
[Migration("20240403234311_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("SushiDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("ComponentPrice")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("EmployeeName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<long>("EmployeePhone")
.HasColumnType("bigint");
b.Property<string>("EmployeePosition")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Sushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("SushiName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Sushies");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("EmployeeId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.HasIndex("SushiId");
b.ToTable("Orders");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.SushiComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("SushiId");
b.ToTable("SushiComponents");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("SushiDatabaseImplement.Models.Client", null)
.WithMany("Order")
.HasForeignKey("ClientId");
b.HasOne("SushiDatabaseImplement.Models.Employee", null)
.WithMany("Order")
.HasForeignKey("EmployeeId");
b.HasOne("SushiDatabaseImplement.Models.Sushi", null)
.WithMany("Order")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.SushiComponent", b =>
{
b.HasOne("SushiDatabaseImplement.Models.Component", "Component")
.WithMany("SushiComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Components")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Client", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Component", b =>
{
b.Navigation("SushiComponents");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Employee", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Components");
b.Navigation("Order");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,181 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SushiDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClientName = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
ComponentPrice = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EmployeeName = table.Column<string>(type: "nvarchar(max)", nullable: false),
EmployeePhone = table.Column<long>(type: "bigint", nullable: false),
EmployeePosition = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Sushies",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sushies", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
SushiId = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: true),
EmployeeId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Employees_EmployeeId",
column: x => x.EmployeeId,
principalTable: "Employees",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Sushies_SushiId",
column: x => x.SushiId,
principalTable: "Sushies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SushiComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SushiComponents", x => x.Id);
table.ForeignKey(
name: "FK_SushiComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SushiComponents_Sushies_SushiId",
column: x => x.SushiId,
principalTable: "Sushies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_EmployeeId",
table: "Orders",
column: "EmployeeId");
migrationBuilder.CreateIndex(
name: "IX_Orders_SushiId",
table: "Orders",
column: "SushiId");
migrationBuilder.CreateIndex(
name: "IX_SushiComponents_ComponentId",
table: "SushiComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_SushiComponents_SushiId",
table: "SushiComponents",
column: "SushiId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "SushiComponents");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Employees");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Sushies");
}
}
}

View File

@ -0,0 +1,235 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SushiDatabaseImplement;
#nullable disable
namespace SushiDatabaseImplement.Migrations
{
[DbContext(typeof(SushiDatabase))]
partial class SushiDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("SushiDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("ComponentPrice")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("EmployeeName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<long>("EmployeePhone")
.HasColumnType("bigint");
b.Property<string>("EmployeePosition")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Sushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("SushiName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Sushies");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("EmployeeId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.HasIndex("SushiId");
b.ToTable("Orders");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.SushiComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("SushiId");
b.ToTable("SushiComponents");
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("SushiDatabaseImplement.Models.Client", null)
.WithMany("Order")
.HasForeignKey("ClientId");
b.HasOne("SushiDatabaseImplement.Models.Employee", null)
.WithMany("Order")
.HasForeignKey("EmployeeId");
b.HasOne("SushiDatabaseImplement.Models.Sushi", null)
.WithMany("Order")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("SushiShopDatabaseImplement.Models.SushiComponent", b =>
{
b.HasOne("SushiDatabaseImplement.Models.Component", "Component")
.WithMany("SushiComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Components")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Client", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Component", b =>
{
b.Navigation("SushiComponents");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Employee", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Components");
b.Navigation("Order");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,56 @@
using SushiContracts.BindingModels;
using SushiContracts.ViewModels;
using SushiDataModels;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SushiShopDatabaseImplement.Models;
namespace SushiDatabaseImplement.Models
{
public class Client : IClientModel
{
public int Id { get; private set; }
[Required]
public string ClientName { get; private set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Order> Order { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new Client()
{
Id = model.Id,
ClientName = model.ClientName,
};
}
public static Client Create(ClientViewModel model)
{
return new Client()
{
Id = model.Id,
ClientName = model.ClientName,
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientName = model.ClientName;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientName = ClientName
};
}
}

View File

@ -0,0 +1,62 @@
using SushiContracts.BindingModels;
using SushiContracts.ViewModels;
using SushiDataModels;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SushiShopDatabaseImplement.Models;
namespace SushiDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public int ComponentPrice { get; private set; }
[ForeignKey("ComponentId")]
public virtual List<SushiComponent> SushiComponents { get; set; } = new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
ComponentPrice = model.ComponentPrice
};
}
public static Component Create(ComponentViewModel model)
{
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
ComponentPrice = model.ComponentPrice
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
ComponentPrice = model.ComponentPrice;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
ComponentPrice = ComponentPrice
};
}
}

View File

@ -0,0 +1,74 @@
using SushiContracts.BindingModels;
using SushiContracts.BusinessLogicContracts;
using SushiContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SushiDataModels;
using SushiShopDatabaseImplement.Models;
namespace SushiDatabaseImplement.Models
{
public class Employee : IEmployeeModel
{
public int Id { get; private set; }
[Required]
public string EmployeeName { get; private set; } = string.Empty;
[Required]
public long EmployeePhone { get; private set; }
[Required]
public string EmployeePosition { get; private set; } = string.Empty;
[ForeignKey("EmployeeId")]
public virtual List<Order> Order { get; set; } = new();
public static Employee? Create(EmployeeBindingModel model)
{
if (model == null)
{
return null;
}
return new Employee()
{
Id = model.Id,
EmployeeName = model.EmployeeName,
EmployeePhone = model.EmployeePhone,
EmployeePosition = model.EmployeePosition
};
}
public static Employee Create(EmployeeViewModel model)
{
return new Employee()
{
Id = model.Id,
EmployeeName = model.EmployeeName,
EmployeePhone = model.EmployeePhone,
EmployeePosition = model.EmployeePosition
};
}
public void Update(EmployeeBindingModel model)
{
if (model == null)
{
return;
}
EmployeeName = model.EmployeeName;
EmployeePhone = model.EmployeePhone;
EmployeePosition = model.EmployeePosition;
}
public EmployeeViewModel GetViewModel => new()
{
Id = Id,
EmployeeName = EmployeeName,
EmployeePhone = EmployeePhone,
EmployeePosition = EmployeePosition
};
}
}

View File

@ -0,0 +1,62 @@
using SushiContracts.BindingModels;
using SushiContracts.ViewModels;
using SushiDataModels.Enums;
using System.ComponentModel.DataAnnotations;
namespace SushiShopDatabaseImplement.Models
{
public class Order
{
public int Id { get; private set; }
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; }
[Required]
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
[Required]
public int SushiId { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
SushiId = model.SushiId,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
SushiId = SushiId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
};
}
}

View File

@ -0,0 +1,88 @@
using SushiContracts.BindingModels;
using SushiContracts.ViewModels;
using SushiDataModels;
using SushiShopDatabaseImplement.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SushiDatabaseImplement.Models
{
public class Sushi : ISushiModel
{
public int Id { get; set; }
[Required]
public string SushiName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _sushiComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> SushiComponents
{
get
{
if (_sushiComponents == null)
{
_sushiComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _sushiComponents;
}
}
[ForeignKey("SushiId")]
public virtual List<Order> Order { get; set; } = new();
[ForeignKey("SushiId")]
public virtual List<SushiComponent> Components { get; set; } = new();
public static Sushi Create(SushiDatabase context, SushiBindingModel model)
{
return new Sushi()
{
Id = model.Id,
SushiName = model.SushiName,
Price = model.Price,
Components = model.SushiComponents.Select(x => new SushiComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(SushiBindingModel model)
{
SushiName = model.SushiName;
Price = model.Price;
}
public SushiViewModel GetViewModel => new()
{
Id = Id,
SushiName = SushiName,
Price = Price,
SushiComponents = SushiComponents
};
public void UpdateComponents(SushiDatabase context, SushiBindingModel model)
{
var SushiComponents = context.SushiComponents.Where(rec => rec.SushiId == model.Id).ToList();
if (SushiComponents != null && Components.Count > 0)
{
context.SushiComponents.RemoveRange(SushiComponents.Where(rec => !model.SushiComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in Components)
{
updateComponent.Count = model.SushiComponents[updateComponent.ComponentId].Item2;
model.SushiComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var sushi = context.Sushies.First(x => x.Id == Id);
foreach (var pc in model.SushiComponents)
{
context.SushiComponents.Add(new SushiComponent
{
Sushi = sushi,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_sushiComponents = null;
}
}
}

View File

@ -0,0 +1,18 @@
using SushiDatabaseImplement.Models;
using System.ComponentModel.DataAnnotations;
namespace SushiShopDatabaseImplement.Models
{
public class SushiComponent
{
public int Id { get; set; }
[Required]
public int SushiId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Sushi Sushi { get; set; } = new();
}
}

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using SushiDatabaseImplement.Models;
using SushiShopDatabaseImplement.Models;
namespace SushiDatabaseImplement
{
public class SushiDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=SushiDataBase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"
);
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Client> Clients { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Sushi> Sushies { set; get; }
public virtual DbSet<SushiComponent> SushiComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiContracts\SushiContracts.csproj" />
</ItemGroup>
</Project>