Первая лабораторная работа. Доделано

This commit is contained in:
abazov73 2023-02-19 17:07:50 +04:00
parent d6debc4aaf
commit a18fb3fb4a
35 changed files with 2881 additions and 66 deletions

View File

@ -8,4 +8,34 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog" Version="5.1.2" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ConfectioneryBusinessLogic\ConfectioneryBusinessLogic.csproj" />
<ProjectReference Include="..\ConfectioneryContracts\ConfectioneryContracts.csproj" />
<ProjectReference Include="..\ConfectioneryDataModels\ConfectioneryDataModels.csproj" />
<ProjectReference Include="..\ConfectioneryListImplement\ConfectioneryListImplement.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

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

View File

@ -0,0 +1,145 @@
namespace Confectionery
{
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()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.comboBoxPastry = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.textBoxSum = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(71, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Изделие:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 47);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 20);
this.label2.TabIndex = 1;
this.label2.Text = "Количество:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 87);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 20);
this.label3.TabIndex = 2;
this.label3.Text = "Сумма:";
//
// comboBoxPastry
//
this.comboBoxPastry.FormattingEnabled = true;
this.comboBoxPastry.Location = new System.Drawing.Point(129, 6);
this.comboBoxPastry.Name = "comboBoxPastry";
this.comboBoxPastry.Size = new System.Drawing.Size(219, 28);
this.comboBoxPastry.TabIndex = 3;
this.comboBoxPastry.SelectedIndexChanged += new System.EventHandler(this.comboBoxPastry_SelectedIndexChanged);
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(129, 44);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(219, 27);
this.textBoxCount.TabIndex = 4;
this.textBoxCount.TextChanged += new System.EventHandler(this.textBoxCount_TextChanged);
//
// textBoxSum
//
this.textBoxSum.Location = new System.Drawing.Point(129, 84);
this.textBoxSum.Name = "textBoxSum";
this.textBoxSum.ReadOnly = true;
this.textBoxSum.Size = new System.Drawing.Size(219, 27);
this.textBoxSum.TabIndex = 5;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(142, 130);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(254, 130);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormCreateOrder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(377, 171);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxSum);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxPastry);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormCreateOrder";
this.Text = "Заказ";
this.Load += new System.EventHandler(this.FormCreateOrder_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private ComboBox comboBoxPastry;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,142 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Confectionery
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IPastryLogic _logicP;
private readonly IOrderLogic _logicO;
private List<PastryViewModel>? _list;
public int Id { get { return Convert.ToInt32(comboBoxPastry.SelectedValue); } set { comboBoxPastry.SelectedValue = value; } }
public IPastryModel? PastryModel
{
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 FormCreateOrder(ILogger<FormCreateOrder> logger, IPastryLogic logicP, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для заказа");
_list = _logicP.ReadList(null);
if (_list != null)
{
comboBoxPastry.DisplayMember = "PastryName";
comboBoxPastry.ValueMember = "Id";
comboBoxPastry.DataSource = _list;
comboBoxPastry.SelectedItem = null;
}
}
private void CalcSum()
{
if (comboBoxPastry.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxPastry.SelectedValue);
var product = _logicP.ReadElement(new PastrySearchModel { Id = id });
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void textBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void comboBoxPastry_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxPastry.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
PastryId = Convert.ToInt32(comboBoxPastry.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,119 @@
namespace Confectionery
{
partial class FormIngredient
{
/// <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.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelName = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxCost = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(254, 140);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 0;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(354, 140);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 1;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(12, 23);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 2;
this.labelName.Text = "Название:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(44, 59);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 20);
this.label1.TabIndex = 3;
this.label1.Text = "Цена:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(98, 20);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(350, 27);
this.textBoxName.TabIndex = 4;
//
// textBoxCost
//
this.textBoxCost.Location = new System.Drawing.Point(98, 56);
this.textBoxCost.Name = "textBoxCost";
this.textBoxCost.Size = new System.Drawing.Size(125, 27);
this.textBoxCost.TabIndex = 5;
//
// FormIngredient
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(455, 176);
this.Controls.Add(this.textBoxCost);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.label1);
this.Controls.Add(this.labelName);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Name = "FormIngredient";
this.Text = "Ингредиент";
this.Load += new System.EventHandler(this.FormIngredient_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private Label labelName;
private Label label1;
private TextBox textBoxName;
private TextBox textBoxCost;
}
}

View File

@ -0,0 +1,81 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace Confectionery
{
public partial class FormIngredient : Form
{
private readonly ILogger _logger;
private readonly IIngredientLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormIngredient(ILogger<FormIngredient> logger, IIngredientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
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 IngredientBindingModel
{
Id = _id ?? 0,
IngredientName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.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 FormIngredient_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new IngredientSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.IngredientName;
textBoxCost.Text = view.Cost.ToString();
}
}
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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,117 @@
namespace Confectionery
{
partial class FormIngredients
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(489, 449);
this.dataGridView.TabIndex = 0;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(522, 12);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(522, 69);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 2;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(522, 126);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(94, 29);
this.buttonDel.TabIndex = 3;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(522, 184);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 4;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// FormIngredients
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(628, 450);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormIngredients";
this.Text = "Ингредиенты";
this.Load += new System.EventHandler(this.FormIngredients_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDel;
private Button buttonRef;
}
}

View File

@ -0,0 +1,111 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Confectionery
{
public partial class FormIngredients : Form
{
private readonly ILogger _logger;
private readonly IIngredientLogic _logic;
public FormIngredients(ILogger<FormIngredients> logger, IIngredientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormIngredients_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["IngredientName"].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(FormIngredient));
if (service is FormIngredient 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(FormIngredient));
if (service is FormIngredient 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 IngredientBindingModel { 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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,177 @@
namespace Confectionery
{
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()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ингредиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button();
this.buttonTakeOrderInWork = new System.Windows.Forms.Button();
this.buttonOrderReady = new System.Windows.Forms.Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1238, 28);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ингредиентыToolStripMenuItem,
this.изделияToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.справочникиToolStripMenuItem.Text = "Справочники";
//
// ингредиентыToolStripMenuItem
//
this.ингредиентыToolStripMenuItem.Name = "ингредиентыToolStripMenuItem";
this.ингредиентыToolStripMenuItem.Size = new System.Drawing.Size(251, 26);
this.ингредиентыToolStripMenuItem.Text = "Ингредиенты";
this.ингредиентыToolStripMenuItem.Click += new System.EventHandler(this.ингредиентыToolStripMenuItem_Click);
//
// изделияToolStripMenuItem
//
this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(251, 26);
this.изделияToolStripMenuItem.Text = "Кондитерские изделия";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.изделияToolStripMenuItem_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(0, 31);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(991, 417);
this.dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(1016, 54);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(197, 29);
this.buttonCreateOrder.TabIndex = 2;
this.buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.UseVisualStyleBackColor = true;
this.buttonCreateOrder.Click += new System.EventHandler(this.buttonCreateOrder_Click);
//
// buttonTakeOrderInWork
//
this.buttonTakeOrderInWork.Location = new System.Drawing.Point(1016, 137);
this.buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
this.buttonTakeOrderInWork.Size = new System.Drawing.Size(197, 29);
this.buttonTakeOrderInWork.TabIndex = 3;
this.buttonTakeOrderInWork.Text = "Отдать на выполнение";
this.buttonTakeOrderInWork.UseVisualStyleBackColor = true;
this.buttonTakeOrderInWork.Click += new System.EventHandler(this.buttonTakeOrderInWork_Click);
//
// buttonOrderReady
//
this.buttonOrderReady.Location = new System.Drawing.Point(1016, 223);
this.buttonOrderReady.Name = "buttonOrderReady";
this.buttonOrderReady.Size = new System.Drawing.Size(197, 29);
this.buttonOrderReady.TabIndex = 4;
this.buttonOrderReady.Text = "Заказ готов";
this.buttonOrderReady.UseVisualStyleBackColor = true;
this.buttonOrderReady.Click += new System.EventHandler(this.buttonOrderReady_Click);
//
// buttonIssuedOrder
//
this.buttonIssuedOrder.Location = new System.Drawing.Point(1016, 308);
this.buttonIssuedOrder.Name = "buttonIssuedOrder";
this.buttonIssuedOrder.Size = new System.Drawing.Size(197, 29);
this.buttonIssuedOrder.TabIndex = 5;
this.buttonIssuedOrder.Text = "Заказ выдан";
this.buttonIssuedOrder.UseVisualStyleBackColor = true;
this.buttonIssuedOrder.Click += new System.EventHandler(this.buttonIssuedOrder_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(1016, 381);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(197, 29);
this.buttonRef.TabIndex = 6;
this.buttonRef.Text = "Обновить список";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1238, 450);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonIssuedOrder);
this.Controls.Add(this.buttonOrderReady);
this.Controls.Add(this.buttonTakeOrderInWork);
this.Controls.Add(this.buttonCreateOrder);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "FormMain";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ингредиентыToolStripMenuItem;
private ToolStripMenuItem изделияToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
}
}

View File

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

View File

@ -0,0 +1,63 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,117 @@
namespace Confectionery
{
partial class FormPastries
{
/// <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.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(523, 186);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 9;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(523, 128);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(94, 29);
this.buttonDel.TabIndex = 8;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(523, 71);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 7;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(523, 14);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(1, 2);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(489, 449);
this.dataGridView.TabIndex = 5;
//
// FormPastries
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(642, 450);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormPastries";
this.Text = "Кондитерские изделия";
this.Load += new System.EventHandler(this.FormPastries_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,112 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Confectionery
{
public partial class FormPastries : Form
{
private readonly ILogger _logger;
private readonly IPastryLogic _logic;
public FormPastries(ILogger<FormPastries> logger, IPastryLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormPastries_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["PastryIngredients"].Visible = false;
dataGridView.Columns["PastryName"].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(FormPastry));
if (service is FormPastry 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(FormPastry));
if (service is FormPastry 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 PastryBindingModel { 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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,238 @@
namespace Confectionery
{
partial class FormPastry
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxPrice = new System.Windows.Forms.TextBox();
this.groupBoxIngredients = new System.Windows.Forms.GroupBox();
this.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.PastryId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.IngredientName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxIngredients.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Название:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 39);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(86, 20);
this.label2.TabIndex = 1;
this.label2.Text = "Стоимость:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(98, 6);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(248, 27);
this.textBoxName.TabIndex = 2;
//
// textBoxPrice
//
this.textBoxPrice.Location = new System.Drawing.Point(98, 36);
this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.ReadOnly = true;
this.textBoxPrice.Size = new System.Drawing.Size(125, 27);
this.textBoxPrice.TabIndex = 3;
//
// groupBoxIngredients
//
this.groupBoxIngredients.Controls.Add(this.buttonRef);
this.groupBoxIngredients.Controls.Add(this.buttonDel);
this.groupBoxIngredients.Controls.Add(this.buttonUpd);
this.groupBoxIngredients.Controls.Add(this.buttonAdd);
this.groupBoxIngredients.Controls.Add(this.dataGridView);
this.groupBoxIngredients.Location = new System.Drawing.Point(12, 69);
this.groupBoxIngredients.Name = "groupBoxIngredients";
this.groupBoxIngredients.Size = new System.Drawing.Size(776, 334);
this.groupBoxIngredients.TabIndex = 4;
this.groupBoxIngredients.TabStop = false;
this.groupBoxIngredients.Text = "Ингрединеты";
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(635, 171);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(126, 29);
this.buttonRef.TabIndex = 4;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(635, 124);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(126, 29);
this.buttonDel.TabIndex = 3;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(635, 76);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(126, 29);
this.buttonUpd.TabIndex = 2;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(635, 26);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(126, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.PastryId,
this.IngredientName,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(6, 26);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(496, 308);
this.dataGridView.TabIndex = 0;
//
// PastryId
//
this.PastryId.HeaderText = "Id";
this.PastryId.MinimumWidth = 6;
this.PastryId.Name = "PastryId";
this.PastryId.ReadOnly = true;
this.PastryId.Visible = false;
this.PastryId.Width = 125;
//
// IngredientName
//
this.IngredientName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.IngredientName.HeaderText = "Название игредиента";
this.IngredientName.MinimumWidth = 6;
this.IngredientName.Name = "IngredientName";
this.IngredientName.ReadOnly = true;
//
// Count
//
this.Count.HeaderText = "Количество";
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
this.Count.ReadOnly = true;
this.Count.Width = 125;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(520, 409);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(126, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(662, 409);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(126, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormPastry
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.groupBoxIngredients);
this.Controls.Add(this.textBoxPrice);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormPastry";
this.Text = "Кондитерское изделие";
this.Load += new System.EventHandler(this.FormPastry_Load);
this.groupBoxIngredients.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBoxIngredients;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn PastryId;
private DataGridViewTextBoxColumn IngredientName;
private DataGridViewTextBoxColumn Count;
}
}

View File

@ -0,0 +1,212 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Confectionery
{
public partial class FormPastry : Form
{
private readonly ILogger _logger;
private readonly IPastryLogic _logic;
private int? _id;
private Dictionary<int, (IIngredientModel, int)> _pastryIngredients;
public int Id { set { _id = value; } }
public FormPastry(ILogger<FormPastry> logger, IPastryLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_pastryIngredients = new Dictionary<int, (IIngredientModel, int)>();
}
private void FormPastry_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new PastrySearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.PastryName;
textBoxPrice.Text = view.Price.ToString();
_pastryIngredients = view.PastryIngredients ?? new Dictionary<int, (IIngredientModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка ингредиентов изделия");
try
{
if (_pastryIngredients != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _pastryIngredients)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.IngredientName, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки ингредиентов изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormPastryIngredient));
if (service is FormPastryIngredient form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.IngredientModel == null)
{
return;
}
_logger.LogInformation("Добавление нового ингредиента: {IngredientName} - {Count}", form.IngredientModel.IngredientName, form.Count);
if (_pastryIngredients.ContainsKey(form.Id))
{
_pastryIngredients[form.Id] = (form.IngredientModel, form.Count);
}
else
{
_pastryIngredients.Add(form.Id, (form.IngredientModel, form.Count));
}
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormPastryIngredient));
if (service is FormPastryIngredient form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _pastryIngredients[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.IngredientModel == null)
{
return;
}
_logger.LogInformation("Изменение ингредиента: {IngredientName} - {Count}", form.IngredientModel.IngredientName, form.Count);
_pastryIngredients[form.Id] = (form.IngredientModel, form.Count);
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление ингредиента: {IngredientName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_pastryIngredients?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_pastryIngredients == null || _pastryIngredients.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new PastryBindingModel
{
Id = _id ?? 0,
PastryName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
PastryIngredients = _pastryIngredients
};
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 _pastryIngredients)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<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="PastryId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="IngredientName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,119 @@
namespace Confectionery
{
partial class FormPastryIngredient
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.comboBoxIngredient = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(95, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Ингредиент:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 53);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 20);
this.label2.TabIndex = 1;
this.label2.Text = "Количество:";
//
// comboBoxIngredient
//
this.comboBoxIngredient.FormattingEnabled = true;
this.comboBoxIngredient.Location = new System.Drawing.Point(113, 6);
this.comboBoxIngredient.Name = "comboBoxIngredient";
this.comboBoxIngredient.Size = new System.Drawing.Size(294, 28);
this.comboBoxIngredient.TabIndex = 2;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(111, 50);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(296, 27);
this.textBoxCount.TabIndex = 3;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(199, 92);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(313, 92);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormPastryIngredient
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(419, 133);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxIngredient);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormPastryIngredient";
this.Text = "Ингредиент кондитерского изделия";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private ComboBox comboBoxIngredient;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,77 @@
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Confectionery
{
public partial class FormPastryIngredient : Form
{
private readonly List<IngredientViewModel>? _list;
public int Id { get { return Convert.ToInt32(comboBoxIngredient.SelectedValue); } set { comboBoxIngredient.SelectedValue = value; } }
public IIngredientModel? IngredientModel
{
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 FormPastryIngredient(IIngredientLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxIngredient.DisplayMember = "IngredientName";
comboBoxIngredient.ValueMember = "Id";
comboBoxIngredient.DataSource = _list;
comboBoxIngredient.SelectedItem = null;
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxIngredient.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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,7 +1,18 @@
using ConfectioneryBusinessLogic.BusinessLogics;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryListImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace Confectionery
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +22,32 @@ namespace Confectionery
// 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<IIngredientStorage, IngredientStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPastryStorage, PastryStorage>();
services.AddTransient<IIngredientLogic, IngredientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPastryLogic, PastryLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormIngredient>();
services.AddTransient<FormIngredients>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormPastry>();
services.AddTransient<FormPastryIngredient>();
services.AddTransient<FormPastries>();
}
}
}

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Confectionery.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Confectionery.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

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

View File

@ -27,6 +27,8 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
@ -37,7 +39,7 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
public bool DeliveryOrder(OrderBindingModel model)
{
CheckModel(model);
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
@ -52,13 +54,15 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен в статус готовности перед выдачей!");
}
element.Status = OrderStatus.Выдан;
model.Status = OrderStatus.Выдан;
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool FinishOrder(OrderBindingModel model)
{
CheckModel(model);
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
@ -73,7 +77,8 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен в статус выполнения перед готовностью!");
}
element.Status = OrderStatus.Готов;
model.Status = OrderStatus.Готов;
_orderStorage.Update(model);
return true;
}
@ -92,7 +97,7 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
public bool TakeOrderInWork(OrderBindingModel model)
{
CheckModel(model);
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
@ -107,7 +112,8 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен в статус принятого перед его выполнением!");
}
element.Status = OrderStatus.Выполняется;
model.Status = OrderStatus.Выполняется;
_orderStorage.Update(model);
return true;
}

View File

@ -11,8 +11,4 @@
<ProjectReference Include="..\ConfectioneryDataModels\ConfectioneryDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Implements\" />
</ItemGroup>
</Project>

View File

@ -1,5 +1,7 @@
using System;
using ConfectioneryListImplement.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -8,6 +10,23 @@ namespace ConfectioneryListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Ingredient> Ingredients { get; set; }
public List<Order> Orders { get; set; }
public List<Pastry> Pastries { get; set; }
private DataListSingleton()
{
Ingredients = new List<Ingredient>();
Orders = new List<Order>();
Pastries = new List<Pastry>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,112 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryListImplement.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryListImplement.Implements
{
public class IngredientStorage : IIngredientStorage
{
private readonly DataListSingleton _source;
public IngredientStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<IngredientViewModel> GetFullList()
{
var result = new List<IngredientViewModel>();
foreach (var ingredient in _source.Ingredients)
{
result.Add(ingredient.GetViewModel);
}
return result;
}
public List<IngredientViewModel> GetFilteredList(IngredientSearchModel model)
{
var result = new List<IngredientViewModel>();
if (string.IsNullOrEmpty(model.IngredientName))
{
return result;
}
foreach (var ingredient in _source.Ingredients)
{
if (ingredient.IngredientName.Contains(model.IngredientName))
{
result.Add(ingredient.GetViewModel);
}
}
return result;
}
public IngredientViewModel? GetElement(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName) && !model.Id.HasValue)
{
return null;
}
foreach (var ingredient in _source.Ingredients)
{
if ((!string.IsNullOrEmpty(model.IngredientName) && ingredient.IngredientName == model.IngredientName) ||
(model.Id.HasValue && ingredient.Id == model.Id))
{
return ingredient.GetViewModel;
}
}
return null;
}
public IngredientViewModel? Insert(IngredientBindingModel model)
{
model.Id = 1;
foreach (var ingredient in _source.Ingredients)
{
if (model.Id <= ingredient.Id)
{
model.Id = ingredient.Id + 1;
}
}
var newIngredient = Ingredient.Create(model);
if (newIngredient == null)
{
return null;
}
_source.Ingredients.Add(newIngredient);
return newIngredient.GetViewModel;
}
public IngredientViewModel? Update(IngredientBindingModel model)
{
foreach (var ingredient in _source.Ingredients)
{
if (ingredient.Id == model.Id)
{
ingredient.Update(model);
return ingredient.GetViewModel;
}
}
return null;
}
public IngredientViewModel? Delete(IngredientBindingModel model)
{
for (int i = 0; i < _source.Ingredients.Count; ++i)
{
if (_source.Ingredients[i].Id == model.Id)
{
var element = _source.Ingredients[i];
_source.Ingredients.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,124 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConfectioneryListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AccessPastryStorage(order.GetViewModel));
}
return result;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AccessPastryStorage(order.GetViewModel));
}
}
return result;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return AccessPastryStorage(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
{
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return AccessPastryStorage(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return AccessPastryStorage(order.GetViewModel);
}
}
return null;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return AccessPastryStorage(element.GetViewModel);
}
}
return null;
}
public OrderViewModel AccessPastryStorage(OrderViewModel model)
{
foreach (var pastry in _source.Pastries)
{
if (pastry.Id == model.PastryId)
{
model.PastryName = pastry.PastryName;
break;
}
}
return model;
}
}
}

View File

@ -0,0 +1,111 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryListImplement.Implements
{
public class PastryStorage : IPastryStorage
{
private readonly DataListSingleton _source;
public PastryStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<PastryViewModel> GetFullList()
{
var result = new List<PastryViewModel>();
foreach (var pastry in _source.Pastries)
{
result.Add(pastry.GetViewModel);
}
return result;
}
public List<PastryViewModel> GetFilteredList(PastrySearchModel model)
{
var result = new List<PastryViewModel>();
if (string.IsNullOrEmpty(model.PastryName))
{
return result;
}
foreach (var pastry in _source.Pastries)
{
if (pastry.PastryName.Contains(model.PastryName))
{
result.Add(pastry.GetViewModel);
}
}
return result;
}
public PastryViewModel? GetElement(PastrySearchModel model)
{
if (string.IsNullOrEmpty(model.PastryName) && !model.Id.HasValue)
{
return null;
}
foreach (var pastry in _source.Pastries)
{
if ((!string.IsNullOrEmpty(model.PastryName) && pastry.PastryName == model.PastryName) ||
(model.Id.HasValue && pastry.Id == model.Id))
{
return pastry.GetViewModel;
}
}
return null;
}
public PastryViewModel? Insert(PastryBindingModel model)
{
model.Id = 1;
foreach (var pastry in _source.Pastries)
{
if (model.Id <= pastry.Id)
{
model.Id = pastry.Id + 1;
}
}
var newPastry = Pastry.Create(model);
if (newPastry == null)
{
return null;
}
_source.Pastries.Add(newPastry);
return newPastry.GetViewModel;
}
public PastryViewModel? Update(PastryBindingModel model)
{
foreach (var pastry in _source.Pastries)
{
if (pastry.Id == model.Id)
{
pastry.Update(model);
return pastry.GetViewModel;
}
}
return null;
}
public PastryViewModel? Delete(PastryBindingModel model)
{
for (int i = 0; i < _source.Pastries.Count; ++i)
{
if (_source.Pastries[i].Id == model.Id)
{
var element = _source.Pastries[i];
_source.Pastries.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -48,11 +48,8 @@ namespace ConfectioneryListImplement.Models
{
return;
}
PastryId = model.PastryId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateImplement = model.DateImplement;
if (model.DateImplement.HasValue) DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{