Compare commits

...

42 Commits
main ... Lab_3

Author SHA1 Message Date
37ab6a8ae1 сдана 2023-03-07 12:55:01 +04:00
a24cc96236 Lab_3 2023-03-05 19:31:05 +04:00
c7bcc08419 db models 2023-03-05 18:39:34 +04:00
9d02e98151 full 2023-02-20 15:26:09 +04:00
88555e8bdf Jewel Storage full 2023-02-20 15:18:44 +04:00
5a5f36b6b9 order Storage full 2023-02-20 15:17:37 +04:00
0732cc0ede component storage full 2023-02-20 15:09:55 +04:00
10092dcda3 dfs 2023-02-20 15:08:30 +04:00
0c874c7eeb Order done 2023-02-20 15:01:34 +04:00
8ba6501dca Program 2023-02-19 21:32:04 +04:00
ba692fed0c OrderStorage TODO 2023-02-19 21:22:52 +04:00
0f91591408 JewelStorage TODO 2023-02-19 21:21:55 +04:00
233c432ede Component Storage 2023-02-19 21:21:08 +04:00
c1fdf0b803 Comonent Storage TODO 2023-02-19 21:20:30 +04:00
ffd07d70da ComponentStorage 2023-02-19 21:19:11 +04:00
ec7dc9e65a DataFileSingleton 2023-02-19 21:10:27 +04:00
2f29c9b6bd DataFileSingleton 2023-02-19 21:09:56 +04:00
14f4dc4909 Order TODO 2023-02-19 21:04:03 +04:00
837aceeefc product 2023-02-19 21:02:22 +04:00
baf03fc366 component 2023-02-19 20:54:21 +04:00
92e0198a9b сдано! 2023-02-07 13:21:07 +04:00
9a7e0e839a full 2023-02-06 17:46:35 +04:00
db02f3c6d1 Jewel Storage_1 2023-02-06 16:31:17 +04:00
bed4ff1872 Order 2023-02-06 16:27:05 +04:00
3684e616dc orderLogic_1 2023-02-06 15:42:50 +04:00
311bcca65f JewelLogic_1 2023-02-06 15:27:10 +04:00
385a43b849 without tasks 2023-02-05 21:54:36 +04:00
8fa564fd6d Form create Order 2023-02-05 21:33:15 +04:00
2a1538068a form jewel 2023-02-05 21:19:21 +04:00
4af686a56b FormJewelComponent 2023-02-05 21:06:29 +04:00
4bc34bb8df form components 2023-02-05 20:58:56 +04:00
cfb7d9086c FormComponent 2023-02-05 20:14:00 +04:00
d3d8f5d7e7 ListImplements 2023-02-05 19:55:48 +04:00
92bee445c3 ListImplements 2023-02-05 19:55:32 +04:00
fb52c67682 Business Logic 2023-02-05 19:24:53 +04:00
8906aac95b deleted 2023-02-05 18:55:49 +04:00
226ebea674 Contracts 2023-02-05 18:55:08 +04:00
e1c0c1942e Проект с моделями 2023-02-05 18:01:09 +04:00
ec9e160673 Библиотека классов 2023-02-05 17:58:46 +04:00
2e3b7f6635 1 2023-02-05 17:43:06 +04:00
1c086e4d64 1 2023-02-05 17:41:50 +04:00
6f33a1199f 1 2023-02-05 17:40:39 +04:00
82 changed files with 5867 additions and 54 deletions

View File

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

119
JewelryStore/FormComponent.Designer.cs generated Normal file
View File

@ -0,0 +1,119 @@
namespace JewelryStore
{
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()
{
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelName = new System.Windows.Forms.Label();
this.labelCost = 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(554, 353);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 34);
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(676, 353);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(112, 34);
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(90, 113);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(94, 25);
this.labelName.TabIndex = 2;
this.labelName.Text = "Название:";
//
// labelCost
//
this.labelCost.AutoSize = true;
this.labelCost.Location = new System.Drawing.Point(90, 160);
this.labelCost.Name = "labelCost";
this.labelCost.Size = new System.Drawing.Size(57, 25);
this.labelCost.TabIndex = 3;
this.labelCost.Text = "Цена:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(212, 113);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(150, 31);
this.textBoxName.TabIndex = 4;
//
// textBoxCost
//
this.textBoxCost.Location = new System.Drawing.Point(212, 160);
this.textBoxCost.Name = "textBoxCost";
this.textBoxCost.Size = new System.Drawing.Size(150, 31);
this.textBoxCost.TabIndex = 5;
//
// FormComponent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.textBoxCost);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelCost);
this.Controls.Add(this.labelName);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Name = "FormComponent";
this.Text = "Компонент";
this.Load += new System.EventHandler(this.FormComponent_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private Label labelName;
private Label labelCost;
private TextBox textBoxName;
private TextBox textBoxCost;
}
}

View File

@ -0,0 +1,92 @@
using Microsoft.Extensions.Logging;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.SearchModels;
namespace JewelryStore
{
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;
textBoxCost.Text = view.Cost.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,
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 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>

116
JewelryStore/FormComponents.Designer.cs generated Normal file
View File

@ -0,0 +1,116 @@
namespace JewelryStore
{
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()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonChange = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 62;
this.dataGridView.RowTemplate.Height = 33;
this.dataGridView.Size = new System.Drawing.Size(459, 488);
this.dataGridView.TabIndex = 0;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(480, 25);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(112, 34);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonChange
//
this.buttonChange.Location = new System.Drawing.Point(481, 67);
this.buttonChange.Name = "buttonChange";
this.buttonChange.Size = new System.Drawing.Size(112, 34);
this.buttonChange.TabIndex = 2;
this.buttonChange.Text = "Изменить";
this.buttonChange.UseVisualStyleBackColor = true;
this.buttonChange.Click += new System.EventHandler(this.buttonChange_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(481, 107);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(112, 34);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(481, 147);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(112, 34);
this.buttonUpdate.TabIndex = 4;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// FormComponents
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(614, 488);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonChange);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormComponents";
this.Text = "Компоненты";
this.Load += new System.EventHandler(this.FormComponents_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonUpdate;
}
}

View File

@ -0,0 +1,121 @@

using JewelryStore;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.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 JewelryStore
{
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 buttonUpdate_Click(object sender, EventArgs e)
{
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 (!_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 buttonChange_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();
}
}
}
}
}
}

144
JewelryStore/FormCreateOrder.Designer.cs generated Normal file
View File

@ -0,0 +1,144 @@
namespace JewelryStore
{
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.comboBoxJewel = new System.Windows.Forms.ComboBox();
this.labelJewel = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.labelSum = new System.Windows.Forms.Label();
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();
//
// comboBoxJewel
//
this.comboBoxJewel.FormattingEnabled = true;
this.comboBoxJewel.Location = new System.Drawing.Point(115, 14);
this.comboBoxJewel.Name = "comboBoxJewel";
this.comboBoxJewel.Size = new System.Drawing.Size(250, 33);
this.comboBoxJewel.TabIndex = 0;
//
// labelJewel
//
this.labelJewel.AutoSize = true;
this.labelJewel.Location = new System.Drawing.Point(12, 22);
this.labelJewel.Name = "labelJewel";
this.labelJewel.Size = new System.Drawing.Size(80, 25);
this.labelJewel.TabIndex = 1;
this.labelJewel.Text = "Изделие";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(12, 67);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(107, 25);
this.labelCount.TabIndex = 2;
this.labelCount.Text = "Количество";
//
// labelSum
//
this.labelSum.AutoSize = true;
this.labelSum.Location = new System.Drawing.Point(12, 118);
this.labelSum.Name = "labelSum";
this.labelSum.Size = new System.Drawing.Size(67, 25);
this.labelSum.TabIndex = 3;
this.labelSum.Text = "Сумма";
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(115, 64);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(250, 31);
this.textBoxCount.TabIndex = 4;
this.textBoxCount.TextChanged += new System.EventHandler(this.textBoxCount_TextChanged);
//
// textBoxSum
//
this.textBoxSum.Location = new System.Drawing.Point(115, 115);
this.textBoxSum.Name = "textBoxSum";
this.textBoxSum.ReadOnly = true;
this.textBoxSum.Size = new System.Drawing.Size(250, 31);
this.textBoxSum.TabIndex = 5;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(31, 161);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 34);
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(253, 161);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(112, 34);
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(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(401, 207);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxSum);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.labelSum);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelJewel);
this.Controls.Add(this.comboBoxJewel);
this.Name = "FormCreateOrder";
this.Text = "Заказ";
this.Load += new System.EventHandler(this.OrderForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboBoxJewel;
private Label labelJewel;
private Label labelCount;
private Label labelSum;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,127 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.SearchModels;
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 JewelryStore
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IJewelLogic _logicP;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IJewelLogic logicP, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
}
private void OrderForm_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка драгоценностей для заказа");
try
{
var list = _logicP.ReadList(null);
if (list != null)
{
comboBoxJewel.DisplayMember = "Драгоценность";
comboBoxJewel.ValueMember = "Id";
comboBoxJewel.DataSource = list.Select(c => c.JewelName).ToList();
comboBoxJewel.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка драгоценностей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (comboBoxJewel.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxJewel.SelectedIndex) + 1;
var Jewel = _logicP.ReadElement(new JewelSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (Jewel?.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 buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxJewel.SelectedValue == null)
{
MessageBox.Show("Выберите драгоценность", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
JewelId = Convert.ToInt32(comboBoxJewel.SelectedIndex) + 1,
JewelName = comboBoxJewel.SelectedValue.ToString(),
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,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>

232
JewelryStore/FormJewel.Designer.cs generated Normal file
View File

@ -0,0 +1,232 @@
namespace JewelryStore
{
partial class FormJewel
{
/// <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.labelName = new System.Windows.Forms.Label();
this.labelPrice = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxPrice = new System.Windows.Forms.TextBox();
this.groupBoxComponent = new System.Windows.Forms.GroupBox();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonChange = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnComponent = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.groupBoxComponent.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(19, 19);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(94, 25);
this.labelName.TabIndex = 0;
this.labelName.Text = "Название:";
//
// labelPrice
//
this.labelPrice.AutoSize = true;
this.labelPrice.Location = new System.Drawing.Point(19, 59);
this.labelPrice.Name = "labelPrice";
this.labelPrice.Size = new System.Drawing.Size(108, 25);
this.labelPrice.TabIndex = 1;
this.labelPrice.Text = "Стоимость: ";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(119, 16);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(340, 31);
this.textBoxName.TabIndex = 2;
//
// textBoxPrice
//
this.textBoxPrice.Location = new System.Drawing.Point(119, 53);
this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.Size = new System.Drawing.Size(150, 31);
this.textBoxPrice.TabIndex = 3;
//
// groupBoxComponent
//
this.groupBoxComponent.Controls.Add(this.buttonUpdate);
this.groupBoxComponent.Controls.Add(this.buttonDelete);
this.groupBoxComponent.Controls.Add(this.buttonChange);
this.groupBoxComponent.Controls.Add(this.buttonAdd);
this.groupBoxComponent.Controls.Add(this.dataGridView);
this.groupBoxComponent.Location = new System.Drawing.Point(14, 108);
this.groupBoxComponent.Name = "groupBoxComponent";
this.groupBoxComponent.Size = new System.Drawing.Size(763, 330);
this.groupBoxComponent.TabIndex = 4;
this.groupBoxComponent.TabStop = false;
this.groupBoxComponent.Text = "Компоненты";
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(604, 164);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(112, 34);
this.buttonUpdate.TabIndex = 4;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(604, 124);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(112, 34);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// buttonChange
//
this.buttonChange.Location = new System.Drawing.Point(602, 81);
this.buttonChange.Name = "buttonChange";
this.buttonChange.Size = new System.Drawing.Size(112, 34);
this.buttonChange.TabIndex = 2;
this.buttonChange.Text = "Изменить";
this.buttonChange.UseVisualStyleBackColor = true;
this.buttonChange.Click += new System.EventHandler(this.buttonChange_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(602, 35);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(112, 34);
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.ID,
this.ColumnComponent,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(25, 30);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 62;
this.dataGridView.RowTemplate.Height = 33;
this.dataGridView.Size = new System.Drawing.Size(554, 281);
this.dataGridView.TabIndex = 0;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(431, 452);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 34);
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(562, 454);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(112, 34);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// ID
//
this.ID.HeaderText = "Column1";
this.ID.MinimumWidth = 8;
this.ID.Name = "ID";
this.ID.Visible = false;
this.ID.Width = 150;
//
// ColumnComponent
//
this.ColumnComponent.HeaderText = "Компонент";
this.ColumnComponent.MinimumWidth = 8;
this.ColumnComponent.Name = "ColumnComponent";
this.ColumnComponent.Width = 150;
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 8;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 150;
//
// FormJewel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 495);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.groupBoxComponent);
this.Controls.Add(this.textBoxPrice);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelPrice);
this.Controls.Add(this.labelName);
this.Name = "FormJewel";
this.Text = "Драгоценность";
this.Load += new System.EventHandler(this.FormJewel_Load);
this.groupBoxComponent.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelName;
private Label labelPrice;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBoxComponent;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonChange;
private Button buttonAdd;
private DataGridView dataGridView;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn ColumnComponent;
private DataGridViewTextBoxColumn ColumnCount;
}
}

228
JewelryStore/FormJewel.cs Normal file
View File

@ -0,0 +1,228 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.SearchModels;
using JewelryStoreDataModels.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 JewelryStore
{
public partial class FormJewel : Form
{
private readonly ILogger _logger;
private readonly IJewelLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _JewelComponents;
public int Id { set { _id = value; } }
public FormJewel(ILogger<FormJewel> logger, IJewelLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_JewelComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormJewel_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка драгоценности");
try
{
var view = _logic.ReadElement(new JewelSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.JewelName;
textBoxPrice.Text = view.Price.ToString();
_JewelComponents = view.JewelComponents ?? 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 (_JewelComponents != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _JewelComponents)
{
dataGridView.Rows.Add(new object[] { pc.Key,pc.Value.Item1.ComponentName, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент драгоценности");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormJewelComponent));
if (service is FormJewelComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
if (_JewelComponents.ContainsKey(form.Id))
{
_JewelComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_JewelComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
}
}
}
private void buttonChange_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormJewelComponent));
if (service is FormJewelComponent form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _JewelComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
_JewelComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
}
}
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: { ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_JewelComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonUpdate_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 (_JewelComponents == null || _JewelComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение драгоценности");
try
{
var model = new JewelBindingModel
{
Id = _id ?? 0,
JewelName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
JewelComponents = _JewelComponents
};
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 _JewelComponents)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

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="ID.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 JewelryStore
{
partial class FormJewelComponent
{
/// <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.comboBoxComponent = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.labelComponent = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// comboBoxComponent
//
this.comboBoxComponent.FormattingEnabled = true;
this.comboBoxComponent.Location = new System.Drawing.Point(148, 10);
this.comboBoxComponent.Name = "comboBoxComponent";
this.comboBoxComponent.Size = new System.Drawing.Size(182, 33);
this.comboBoxComponent.TabIndex = 0;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(150, 53);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(150, 31);
this.textBoxCount.TabIndex = 1;
//
// labelComponent
//
this.labelComponent.AutoSize = true;
this.labelComponent.Location = new System.Drawing.Point(16, 18);
this.labelComponent.Name = "labelComponent";
this.labelComponent.Size = new System.Drawing.Size(103, 25);
this.labelComponent.TabIndex = 2;
this.labelComponent.Text = "Компонент";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(16, 57);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(112, 25);
this.labelCount.TabIndex = 3;
this.labelCount.Text = "Количество ";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(75, 99);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 34);
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(206, 99);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(112, 34);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отменить";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormJewelComponent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(426, 142);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelComponent);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxComponent);
this.Name = "FormJewelComponent";
this.Text = "Компонент драгоценности";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboBoxComponent;
private TextBox textBoxCount;
private Label labelComponent;
private Label labelCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,92 @@
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.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 JewelryStore
{
public partial class FormJewelComponent : 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 FormJewelComponent(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,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>

121
JewelryStore/FormJewels.Designer.cs generated Normal file
View File

@ -0,0 +1,121 @@
namespace JewelryStore
{
partial class FormJewels
{
/// <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.AddButton = new System.Windows.Forms.Button();
this.ChangeButton = new System.Windows.Forms.Button();
this.DeleteButton = new System.Windows.Forms.Button();
this.UpdateButton = 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(1, 2);
this.DataGridView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 62;
this.DataGridView.RowTemplate.Height = 25;
this.DataGridView.Size = new System.Drawing.Size(597, 547);
this.DataGridView.TabIndex = 0;
//
// AddButton
//
this.AddButton.Location = new System.Drawing.Point(615, 12);
this.AddButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(171, 39);
this.AddButton.TabIndex = 1;
this.AddButton.Text = "Добавить";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// ChangeButton
//
this.ChangeButton.Location = new System.Drawing.Point(615, 110);
this.ChangeButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.ChangeButton.Name = "ChangeButton";
this.ChangeButton.Size = new System.Drawing.Size(171, 39);
this.ChangeButton.TabIndex = 2;
this.ChangeButton.Text = "Изменить";
this.ChangeButton.UseVisualStyleBackColor = true;
this.ChangeButton.Click += new System.EventHandler(this.ChangeButton_Click);
//
// DeleteButton
//
this.DeleteButton.Location = new System.Drawing.Point(615, 209);
this.DeleteButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.DeleteButton.Name = "DeleteButton";
this.DeleteButton.Size = new System.Drawing.Size(171, 39);
this.DeleteButton.TabIndex = 3;
this.DeleteButton.Text = "Удалить";
this.DeleteButton.UseVisualStyleBackColor = true;
this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click);
//
// UpdateButton
//
this.UpdateButton.Location = new System.Drawing.Point(615, 310);
this.UpdateButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.UpdateButton.Name = "UpdateButton";
this.UpdateButton.Size = new System.Drawing.Size(171, 39);
this.UpdateButton.TabIndex = 4;
this.UpdateButton.Text = "Обновить";
this.UpdateButton.UseVisualStyleBackColor = true;
this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click);
//
// FormJewels
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(805, 563);
this.Controls.Add(this.UpdateButton);
this.Controls.Add(this.DeleteButton);
this.Controls.Add(this.ChangeButton);
this.Controls.Add(this.AddButton);
this.Controls.Add(this.DataGridView);
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.Name = "FormJewels";
this.Text = "Драгоценности";
this.Load += new System.EventHandler(this.FormJewels_Load);
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button AddButton;
private Button ChangeButton;
private Button DeleteButton;
private Button UpdateButton;
}
}

123
JewelryStore/FormJewels.cs Normal file
View File

@ -0,0 +1,123 @@
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;
using JewelryStore;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
namespace JewelryStore
{
public partial class FormJewels : Form //TODO
{
private readonly ILogger _logger;
private readonly IJewelLogic _logic;
public FormJewels(ILogger<FormJewels> logger, IJewelLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["JewelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["JewelComponents"].Visible = false;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormJewel));
if (service is FormJewel form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormJewel));
if (service is FormJewel form)
{
form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_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 JewelBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void FormJewels_Load(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>

176
JewelryStore/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,176 @@
namespace JewelryStore
{
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.buttonReady = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonToWork = new System.Windows.Forms.Button();
this.buttonPut = new System.Windows.Forms.Button();
this.buttonRefresh = new System.Windows.Forms.Button();
this.menuStrip = 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();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// buttonReady
//
this.buttonReady.Location = new System.Drawing.Point(1273, 225);
this.buttonReady.Name = "buttonReady";
this.buttonReady.Size = new System.Drawing.Size(215, 34);
this.buttonReady.TabIndex = 3;
this.buttonReady.Text = "Заказ готов";
this.buttonReady.UseVisualStyleBackColor = true;
this.buttonReady.Click += new System.EventHandler(this.buttonReady_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(9, 52);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 62;
this.dataGridView.RowTemplate.Height = 33;
this.dataGridView.Size = new System.Drawing.Size(1227, 386);
this.dataGridView.TabIndex = 0;
//
// buttonCreate
//
this.buttonCreate.Location = new System.Drawing.Point(1273, 52);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(215, 34);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать заказ";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// buttonToWork
//
this.buttonToWork.Location = new System.Drawing.Point(1273, 137);
this.buttonToWork.Name = "buttonToWork";
this.buttonToWork.Size = new System.Drawing.Size(215, 34);
this.buttonToWork.TabIndex = 2;
this.buttonToWork.Text = "Отдать на выполнение";
this.buttonToWork.UseVisualStyleBackColor = true;
this.buttonToWork.Click += new System.EventHandler(this.buttonToWork_Click);
//
// buttonPut
//
this.buttonPut.Location = new System.Drawing.Point(1273, 308);
this.buttonPut.Name = "buttonPut";
this.buttonPut.Size = new System.Drawing.Size(215, 34);
this.buttonPut.TabIndex = 4;
this.buttonPut.Text = "Заказ выдан";
this.buttonPut.UseVisualStyleBackColor = true;
this.buttonPut.Click += new System.EventHandler(this.buttonPut_Click);
//
// buttonRefresh
//
this.buttonRefresh.Location = new System.Drawing.Point(1273, 389);
this.buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.Size = new System.Drawing.Size(215, 34);
this.buttonRefresh.TabIndex = 5;
this.buttonRefresh.Text = "Обновить список";
this.buttonRefresh.UseVisualStyleBackColor = true;
this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click);
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1530, 33);
this.menuStrip.TabIndex = 6;
this.menuStrip.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(139, 29);
this.справочникиToolStripMenuItem.Text = "Справочники";
//
// компонентыToolStripMenuItem
//
this.компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(240, 34);
this.компонентыToolStripMenuItem.Text = "Компоненты";
this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.компонентыToolStripMenuItem_Click);
//
// изделияToolStripMenuItem
//
this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(240, 34);
this.изделияToolStripMenuItem.Text = "Драгоценности";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.драгоценностиToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1530, 450);
this.Controls.Add(this.buttonRefresh);
this.Controls.Add(this.buttonPut);
this.Controls.Add(this.buttonReady);
this.Controls.Add(this.buttonToWork);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMain";
this.Text = "Изготовление Драгоценностей";
this.Load += new System.EventHandler(this.FormMain_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private DataGridView dataGridView;
private Button buttonCreate;
private Button buttonToWork;
private Button buttonPut;
private Button buttonRefresh;
private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem изделияToolStripMenuItem;
private Button buttonReady;
}
}

193
JewelryStore/FormMain.cs Normal file
View File

@ -0,0 +1,193 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreDataModels.Enums;
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 JewelryStore
{
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["JewelId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void компонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void драгоценностиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormJewels));
if (service is FormJewels form)
{
form.ShowDialog();
}
}
private void buttonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void buttonToWork_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,
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonReady_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,
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonPut_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,
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
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 buttonRefresh_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="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -8,4 +8,25 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<JewelReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<JewelReference Include="NLog.Extensions.Logging" Version="5.2.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JewelryStoreBusinessLogic\JewelryStoreBusinessLogic.csproj" />
<ProjectReference Include="..\JewelryStoreContracts\JewelryStoreContracts.csproj" />
<ProjectReference Include="..\JewelryStoreDatabaseImplement\JewelryStoreDatabaseImplement.csproj" />
<ProjectReference Include="..\JewelryStoreFileImplement\JewelryStoreFileImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -3,7 +3,19 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33122.133
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JewelryStore", "JewelryStore.csproj", "{F1AEB85A-E5E1-4B07-8D6B-E46870480FFA}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStore", "JewelryStore.csproj", "{F1AEB85A-E5E1-4B07-8D6B-E46870480FFA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStoreContracts", "..\JewelryStoreContracts\JewelryStoreContracts.csproj", "{763B1FD7-7D30-4689-869C-1FEAD240B29B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStoreDataModels", "..\JewelryStoreDataModels\JewelryStoreDataModels.csproj", "{84BF2156-F821-46F4-8EED-F371084C0129}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStoreBusinessLogic", "..\JewelryStoreBusinessLogic\JewelryStoreBusinessLogic.csproj", "{DA57067F-F3ED-4B1C-B56F-52856FC2E93D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStoreListImplement", "..\JewelryStoreListImplement\JewelryStoreListImplement.csproj", "{B8C8AA30-FC16-4331-B456-CD16C3C97B25}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JewelryStoreFileImplement", "..\JewelryStoreFileImplement\JewelryStoreFileImplement.csproj", "{2906CD1C-4D78-4329-A2E9-8B67E624DD92}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JewelryStoreDatabaseImplement", "..\JewelryStoreDatabaseImplement\JewelryStoreDatabaseImplement.csproj", "{672057E7-DCAE-4B6B-A3EF-39690E577C9D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +27,30 @@ Global
{F1AEB85A-E5E1-4B07-8D6B-E46870480FFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1AEB85A-E5E1-4B07-8D6B-E46870480FFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1AEB85A-E5E1-4B07-8D6B-E46870480FFA}.Release|Any CPU.Build.0 = Release|Any CPU
{763B1FD7-7D30-4689-869C-1FEAD240B29B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{763B1FD7-7D30-4689-869C-1FEAD240B29B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{763B1FD7-7D30-4689-869C-1FEAD240B29B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{763B1FD7-7D30-4689-869C-1FEAD240B29B}.Release|Any CPU.Build.0 = Release|Any CPU
{84BF2156-F821-46F4-8EED-F371084C0129}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84BF2156-F821-46F4-8EED-F371084C0129}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84BF2156-F821-46F4-8EED-F371084C0129}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84BF2156-F821-46F4-8EED-F371084C0129}.Release|Any CPU.Build.0 = Release|Any CPU
{DA57067F-F3ED-4B1C-B56F-52856FC2E93D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DA57067F-F3ED-4B1C-B56F-52856FC2E93D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DA57067F-F3ED-4B1C-B56F-52856FC2E93D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DA57067F-F3ED-4B1C-B56F-52856FC2E93D}.Release|Any CPU.Build.0 = Release|Any CPU
{B8C8AA30-FC16-4331-B456-CD16C3C97B25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B8C8AA30-FC16-4331-B456-CD16C3C97B25}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B8C8AA30-FC16-4331-B456-CD16C3C97B25}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B8C8AA30-FC16-4331-B456-CD16C3C97B25}.Release|Any CPU.Build.0 = Release|Any CPU
{2906CD1C-4D78-4329-A2E9-8B67E624DD92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2906CD1C-4D78-4329-A2E9-8B67E624DD92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2906CD1C-4D78-4329-A2E9-8B67E624DD92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2906CD1C-4D78-4329-A2E9-8B67E624DD92}.Release|Any CPU.Build.0 = Release|Any CPU
{672057E7-DCAE-4B6B-A3EF-39690E577C9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{672057E7-DCAE-4B6B-A3EF-39690E577C9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{672057E7-DCAE-4B6B-A3EF-39690E577C9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{672057E7-DCAE-4B6B-A3EF-39690E577C9D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,17 +1,56 @@
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreBusinessLogic.BusinessLogics;
using JewelryStoreDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using System.Drawing;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace JewelryStore
{
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()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
// 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<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IJewelStorage, JewelStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IJewelLogic, JewelLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormJewel>();
services.AddTransient<FormJewelComponent>();
services.AddTransient<FormJewels>();
}
}
}

View File

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

View File

@ -0,0 +1,120 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreBusinessLogic.BusinessLogics
{
public class JewelLogic : IJewelLogic // TODO реализовать интерфейс идентично componentLogic
{
private readonly ILogger _logger;
private readonly IJewelStorage _jewelStorage;
public JewelLogic(ILogger<JewelLogic> logger, IJewelStorage jewelStorage)
{
_logger = logger;
_jewelStorage= jewelStorage;
}
public bool Create(JewelBindingModel model)
{
CheckModel(model);
if (_jewelStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(JewelBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_jewelStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public JewelViewModel? ReadElement(JewelSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. JewelName:{JewelName}.Id:{ Id}", model.JewelName, model.Id);
var element = _jewelStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<JewelViewModel>? ReadList(JewelSearchModel? model)
{
_logger.LogInformation("ReadList. JewelName:{JeweltName}.Id:{ Id}", model?.JewelName, model?.Id);
var list = model == null ? _jewelStorage.GetFullList() : _jewelStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(JewelBindingModel model)
{
CheckModel(model);
if (_jewelStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(JewelBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.JewelName))
{
throw new ArgumentNullException("Нет названия драгоценности",
nameof(model.JewelName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена драгоценности должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Jewel. JewelName:{JewelName}. Price:{ Price}. Id: { Id}", model.JewelName, model.Price, model.Id);
var element = _jewelStorage.GetElement(new JewelSearchModel
{
JewelName = model.JewelName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Драгоценность с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,130 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic //TODO реализовать интерфейс
{
// Класс с логикой для заказов будет отвечать за получение списка заказов,
//создания заказа и смены его статусов.Следует учитывать, что у заказа можно
//менять статус на новый, если его текущий статус предшествует новому
//(например, в статус «Готов» можно переводить, если заказ находится в статусе
//«Выполняется»).
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool DeliveryOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Готов) return false;
model.Status = OrderStatus.Выдан;
model.DateImplement = DateTime.Now;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool FinishOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Выполняется) return false;
model.Status = OrderStatus.Готов;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. OrderId:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Принят) return false;
model.Status = OrderStatus.Выполняется;
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.JewelId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор драгоценности", nameof(model.JewelId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество драгоценностей в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. JewelId: { JewelId}", model.Id, model.Sum, model.JewelId);
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<JewelReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<JewelReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JewelryStoreContracts\JewelryStoreContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreDataModels.Models;
namespace JewelryStoreContracts.BindingModels
{
public class ComponentBindingModel : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.BindingModels
{
public class JewelBindingModel : IJewelModel
{
public int Id { get; set; }
public string JewelName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> JewelComponents { get; set;} = new();
}
}

View File

@ -0,0 +1,23 @@
using JewelryStoreDataModels.Enums;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int JewelId { get; set; }
public string JewelName { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{
List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model);
bool Update(ComponentBindingModel model);
bool Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.BusinessLogicsContracts
{
public interface IJewelLogic
{
List<JewelViewModel>? ReadList(JewelSearchModel? model);
JewelViewModel? ReadElement(JewelSearchModel model);
bool Create(JewelBindingModel model);
bool Update(JewelBindingModel model);
bool Delete(JewelBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\JewelryStoreDataModels\JewelryStoreDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.SearchModels
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.SearchModels
{
public class JewelSearchModel
{
public int? Id { get; set; }
public string? JewelName { get; set; }
}
}

View File

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

View File

@ -0,0 +1,22 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.StoragesContracts
{
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);
ComponentViewModel? Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
namespace JewelryStoreContracts.StoragesContracts
{
public interface IJewelStorage
{
List<JewelViewModel> GetFullList();
List<JewelViewModel> GetFilteredList(JewelSearchModel model);
JewelViewModel? GetElement(JewelSearchModel model);
JewelViewModel? Insert(JewelBindingModel model);
JewelViewModel? Update(JewelBindingModel model);
JewelViewModel? Delete(JewelBindingModel model);
}
}

View File

@ -0,0 +1,22 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.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,19 @@
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.ViewModels
{
public class JewelViewModel : IJewelModel
{
public int Id { get; set; }
[DisplayName("Название драгоценности")]
public string JewelName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> JewelComponents
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,33 @@
using JewelryStoreDataModels.Enums;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int JewelId { get; set; }
[DisplayName("Драгоценность")]
public string JewelName { 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,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDataModels.Enums
{
public enum OrderStatus
{
Неизвестен = -1,
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3
}
}

View File

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

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDataModels.Models
{
public interface IComponentModel : IId
{
string ComponentName { get; }
double Cost { get; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDataModels.Models
{
public interface IJewelModel : IId
{
string JewelName { get; }
double Price { get; }
Dictionary<int, (IComponentModel, int)> JewelComponents { get; }
}
}

View File

@ -0,0 +1,24 @@
using JewelryStoreDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDataModels.Models
{
public interface IOrderModel : IId
{
int JewelId { get; }
string JewelName { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -0,0 +1,98 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new JewelryStoreDataBase();
var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new JewelryStoreDataBase();
return context.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new JewelryStoreDataBase();
return context.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFullList()
{
using var context = new JewelryStoreDataBase();
return context.Components.Select(x => x.GetViewModel).ToList();
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new JewelryStoreDataBase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new JewelryStoreDataBase();
var component = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}

View File

@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace JewelryStoreDatabaseImplement.Implements
{
public class JewelStorage : IJewelStorage
{
public JewelViewModel? Delete(JewelBindingModel model)
{
using var context = new JewelryStoreDataBase();
var element = context.Jewels.Include(x => x.Components).FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Jewels.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public JewelViewModel? GetElement(JewelSearchModel model)
{
if (string.IsNullOrEmpty(model.JewelName) && !model.Id.HasValue)
{
return null;
}
using var context = new JewelryStoreDataBase();
return context.Jewels.Include(x => x.Components).ThenInclude(x => x.Component).FirstOrDefault(x => (!string.IsNullOrEmpty(model.JewelName) && x.JewelName == model.JewelName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<JewelViewModel> GetFilteredList(JewelSearchModel model)
{
if (string.IsNullOrEmpty(model.JewelName))
{
return new();
}
using var context = new JewelryStoreDataBase();
return context.Jewels.Include(x => x.Components).ThenInclude(x => x.Component).Where(x => x.JewelName.Contains(model.JewelName)).ToList().Select(x => x.GetViewModel).ToList();
}
public List<JewelViewModel> GetFullList()
{
using var context = new JewelryStoreDataBase();
return context.Jewels.Include(x => x.Components).ThenInclude(x => x.Component).ToList().Select(x => x.GetViewModel).ToList();
}
public JewelViewModel? Insert(JewelBindingModel model)
{
using var context = new JewelryStoreDataBase();
var newJewel = Jewel.Create(context, model);
if (newJewel == null)
{
return null;
}
context.Jewels.Add(newJewel);
context.SaveChanges();
return newJewel.GetViewModel;
}
public JewelViewModel? Update(JewelBindingModel model)
{
using var context = new JewelryStoreDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var jewel = context.Jewels.FirstOrDefault(rec => rec.Id == model.Id);
if (jewel == null)
{
return null;
}
jewel.Update(model);
context.SaveChanges();
jewel.UpdateComponents(context, model);
transaction.Commit();
return jewel.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDatabaseImplement.Models;
namespace JewelryStoreDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new JewelryStoreDataBase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new JewelryStoreDataBase();
return context.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new JewelryStoreDataBase();
return context.Orders.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new JewelryStoreDataBase();
return context.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new JewelryStoreDataBase();
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new JewelryStoreDataBase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreDatabaseImplement.Models;
namespace JewelryStoreDatabaseImplement
{
public class JewelryStoreDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-H890EHR\SQLEXPRESS;Initial Catalog=JewelryStoreDatabaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Jewel> Jewels { set; get; }
public virtual DbSet<JewelComponent> JewelComponents { 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>
<ProjectReference Include="..\JewelryStoreContracts\JewelryStoreContracts.csproj" />
<ProjectReference Include="..\JewelryStoreDataModels\JewelryStoreDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,175 @@
// <auto-generated />
using System;
using JewelryStoreDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace JewelryStoreDatabaseImplement.Migrations
{
[DbContext(typeof(JewelryStoreDataBase))]
[Migration("20230305150151_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("JewelryStoreDatabaseImplement.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<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Jewels");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", 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>("JewelId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("JewelId");
b.ToTable("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("JewelId")
.HasColumnType("int");
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("JewelId");
b.ToTable("Orders");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Component", "Component")
.WithMany("JewelComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Components")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Orders")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Component", b =>
{
b.Navigation("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,126 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace JewelryStoreDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
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),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Jewels",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
JewelName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Jewels", x => x.Id);
});
migrationBuilder.CreateTable(
name: "JewelComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
JewelId = 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_JewelComponents", x => x.Id);
table.ForeignKey(
name: "FK_JewelComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_JewelComponents_Jewels_JewelId",
column: x => x.JewelId,
principalTable: "Jewels",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
JewelId = table.Column<int>(type: "int", nullable: false),
JewelName = table.Column<string>(type: "nvarchar(max)", nullable: false),
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)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Jewels_JewelId",
column: x => x.JewelId,
principalTable: "Jewels",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_JewelComponents_ComponentId",
table: "JewelComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_JewelComponents_JewelId",
table: "JewelComponents",
column: "JewelId");
migrationBuilder.CreateIndex(
name: "IX_Orders_JewelId",
table: "Orders",
column: "JewelId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "JewelComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Jewels");
}
}
}

View File

@ -0,0 +1,175 @@
// <auto-generated />
using System;
using JewelryStoreDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace JewelryStoreDatabaseImplement.Migrations
{
[DbContext(typeof(JewelryStoreDataBase))]
[Migration("20230305150722_InitialCreate_1")]
partial class InitialCreate_1
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("JewelryStoreDatabaseImplement.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<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Jewels");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", 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>("JewelId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("JewelId");
b.ToTable("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("JewelId")
.HasColumnType("int");
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("JewelId");
b.ToTable("Orders");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Component", "Component")
.WithMany("JewelComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Components")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Orders")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Component", b =>
{
b.Navigation("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace JewelryStoreDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate_1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -0,0 +1,172 @@
// <auto-generated />
using System;
using JewelryStoreDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace JewelryStoreDatabaseImplement.Migrations
{
[DbContext(typeof(JewelryStoreDataBase))]
partial class JewelryStoreDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("JewelryStoreDatabaseImplement.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<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Jewels");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", 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>("JewelId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("JewelId");
b.ToTable("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("JewelId")
.HasColumnType("int");
b.Property<string>("JewelName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("JewelId");
b.ToTable("Orders");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.JewelComponent", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Component", "Component")
.WithMany("JewelComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Components")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b =>
{
b.HasOne("JewelryStoreDatabaseImplement.Models.Jewel", "Jewel")
.WithMany("Orders")
.HasForeignKey("JewelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Jewel");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Component", b =>
{
b.Navigation("JewelComponents");
});
modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Jewel", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,61 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDatabaseImplement.Models;
using JewelryStoreDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace JewelryStoreDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<JewelComponent> JewelComponents { get; set; } = new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component Create(ComponentViewModel model)
{
return new Component
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,106 @@
using JewelryStoreDataModels.Models;
using JewelryStoreContracts.ViewModels;
using JewelryStoreContracts.BindingModels;
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;
namespace JewelryStoreDatabaseImplement.Models
{
public class Jewel : IJewelModel
{
public int Id { get; set; }
[Required]
public string JewelName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _jewelComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> JewelComponents
{
get
{
if (_jewelComponents == null)
{
_jewelComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
}
return _jewelComponents;
}
}
[ForeignKey("JewelId")]
public virtual List<JewelComponent> Components { get; set; } = new();
[ForeignKey("JewelId")]
public virtual List<Order> Orders { get; set; } = new();
public static Jewel Create(JewelryStoreDataBase context, JewelBindingModel model)
{
return new Jewel()
{
Id = model.Id,
JewelName = model.JewelName,
Price = model.Price,
Components = model.JewelComponents.Select(x => new JewelComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(JewelBindingModel model)
{
JewelName = model.JewelName;
Price = model.Price;
}
public JewelViewModel GetViewModel => new()
{
Id = Id,
JewelName = JewelName,
Price = Price,
JewelComponents = JewelComponents
};
public void UpdateComponents(JewelryStoreDataBase context, JewelBindingModel model)
{
var jewelComponents = context.JewelComponents.Where(rec => rec.JewelId == model.Id).ToList();
if (jewelComponents != null && jewelComponents.Count > 0)
{ // удалили те, которых нет в модели
context.JewelComponents.RemoveRange(jewelComponents.Where(rec => !model.JewelComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in jewelComponents)
{
updateComponent.Count = model.JewelComponents[updateComponent.ComponentId].Item2;
model.JewelComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var jewel = context.Jewels.First(x => x.Id == Id);
foreach (var pc in model.JewelComponents)
{
context.JewelComponents.Add(new JewelComponent
{
Jewel = jewel,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_jewelComponents = null;
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreDatabaseImplement.Models
{
public class JewelComponent
{
public int Id { get; set; }
[Required]
public int JewelId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Jewel Jewel { get; set; } = new();
}
}

View File

@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.ViewModels;
using JewelryStoreContracts.BindingModels;
using JewelryStoreDataModels.Models;
using JewelryStoreDataModels.Enums;
using System.ComponentModel.DataAnnotations;
namespace JewelryStoreDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int JewelId { get; private set; }
public string JewelName { get; private set; } = string.Empty;
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public virtual Jewel Jewel { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
JewelId = model.JewelId,
JewelName = model.JewelName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
JewelId = model.JewelId;
JewelName = model.JewelName;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
JewelId = JewelId,
JewelName = JewelName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,54 @@
using JewelryStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace JewelryStoreFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string JewelFileName = "Jewel.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Jewel> Jewels { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName,"Components", x => x.GetXElement);
public void SaveJewels() => SaveData(Jewels, JewelFileName, "Jewels", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>Component.Create(x)!)!;
Jewels = LoadData(JewelFileName, "Jewel", x => Jewel.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName,data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,88 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton _source;
public ComponentStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return _source.Components.Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return _source.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;
}
return _source.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = _source.Components.Count > 0 ? _source.Components.Max(x =>x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
_source.Components.Add(newComponent);
_source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = _source.Components.FirstOrDefault(x => x.Id ==model.Id);
if (component == null)
{
return null;
}
component.Update(model);
_source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = _source.Components.FirstOrDefault(x => x.Id ==model.Id);
if (element != null)
{
_source.Components.Remove(element);
_source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,88 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreFileImplement.Implements
{
public class JewelStorage : IJewelStorage // TODO Lab_2
{
private readonly DataFileSingleton _source;
public JewelStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<JewelViewModel> GetFullList()
{
return _source.Jewels.Select(x => x.GetViewModel).ToList();
}
public List<JewelViewModel> GetFilteredList(JewelSearchModel
model)
{
if (string.IsNullOrEmpty(model.JewelName))
{
return new();
}
return _source.Jewels
.Where(x => x.JewelName.Contains(model.JewelName))
.Select(x => x.GetViewModel)
.ToList();
}
public JewelViewModel? GetElement(JewelSearchModel model)
{
if (string.IsNullOrEmpty(model.JewelName) && !model.Id.HasValue)
{
return null;
}
return _source.Jewels
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.JewelName) && x.JewelName == model.JewelName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public JewelViewModel? Insert(JewelBindingModel model)
{
model.Id = _source.Jewels.Count > 0 ? _source.Jewels.Max(x => x.Id) + 1 : 1;
var newJewel = Jewel.Create(model);
if (newJewel == null)
{
return null;
}
_source.Jewels.Add(newJewel);
_source.SaveJewels();
return newJewel.GetViewModel;
}
public JewelViewModel? Update(JewelBindingModel model)
{
var component = _source.Jewels.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
_source.SaveJewels();
return component.GetViewModel;
}
public JewelViewModel? Delete(JewelBindingModel model)
{
var element = _source.Jewels.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Jewels.Remove(element);
_source.SaveJewels();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,94 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreFileImplement.Implements
{
public class OrderStorage : IOrderStorage // TODO Lab_2
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Orders.Remove(element);
source.SaveOrders();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return order.GetViewModel;
}
}
}

View File

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

View File

@ -0,0 +1,71 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace JewelryStoreFileImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,95 @@
using JewelryStoreDataModels.Models;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
using System.Xml.Linq;
namespace JewelryStoreFileImplement.Models
{
public class Jewel: IJewelModel
{
public int Id { get; private set; }
public string JewelName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _productComponents = null;
public Dictionary<int, (IComponentModel, int)> JewelComponents
{
get
{
if (_productComponents == null)
{
var source = DataFileSingleton.GetInstance();
_productComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _productComponents;
}
}
public static Jewel? Create(JewelBindingModel model)
{
if (model == null)
{
return null;
}
return new Jewel()
{
Id = model.Id,
JewelName = model.JewelName,
Price = model.Price,
Components = model.JewelComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Jewel? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Jewel()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
JewelName = element.Element("JewelName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("JewelComponents")!.Elements("JewelComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(JewelBindingModel model)
{
if (model == null)
{
return;
}
JewelName = model.JewelName;
Price = model.Price;
Components = model.JewelComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_productComponents = null;
}
public JewelViewModel GetViewModel => new()
{
Id = Id,
JewelName = JewelName,
Price = Price,
JewelComponents = JewelComponents
};
public XElement GetXElement => new("Jewel",
new XAttribute("Id", Id),
new XElement("JewelName", JewelName),
new XElement("Price", Price.ToString()),
new XElement("JewelComponents", Components.Select(x =>new XElement("JewelComponent",new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -0,0 +1,112 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.Enums;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace JewelryStoreFileImplement.Models
{
public class Order : IOrderModel
{
public int JewelId { get; private set; }
public string JewelName { get; private set; } = string.Empty;
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
JewelId = model.JewelId,
JewelName = model.JewelName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
JewelId = Convert.ToInt32(element.Element("JewelId")!.Value),
JewelName = element.Element("JewelName")!.Value,
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null)
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
return order;
}
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
JewelId = model.JewelId;
JewelName = model.JewelName;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
JewelId = JewelId,
JewelName = JewelName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("JewelName", JewelName),
new XElement("JewelId", JewelId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
}

View File

@ -0,0 +1,31 @@
using JewelryStoreListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Jewel> Jewels { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Jewels = new List<Jewel>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

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

View File

@ -0,0 +1,112 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreListImplement.Implements
{
public class JewelStorage : IJewelStorage // TODO реализовать интерфейс
{
private readonly DataListSingleton _source;
public JewelStorage()
{
_source = DataListSingleton.GetInstance();
}
public JewelViewModel? Delete(JewelBindingModel model)
{
for (int i = 0; i < _source.Jewels.Count; ++i)
{
if (_source.Jewels[i].Id == model.Id)
{
var element = _source.Jewels[i];
_source.Jewels.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public JewelViewModel? GetElement(JewelSearchModel model)
{
if (string.IsNullOrEmpty(model.JewelName) && !model.Id.HasValue)
{
return null;
}
foreach (var jewel in _source.Jewels)
{
if ((!string.IsNullOrEmpty(model.JewelName) &&
jewel.JewelName == model.JewelName) ||
(model.Id.HasValue && jewel.Id == model.Id))
{
return jewel.GetViewModel;
}
}
return null;
}
public List<JewelViewModel> GetFilteredList(JewelSearchModel model)
{
var result = new List<JewelViewModel>();
if (string.IsNullOrEmpty(model.JewelName))
{
return result;
}
foreach (var jewel in _source.Jewels)
{
if (jewel.JewelName.Contains(model.JewelName))
{
result.Add(jewel.GetViewModel);
}
}
return result;
}
public List<JewelViewModel> GetFullList()
{
var result = new List<JewelViewModel>();
foreach (var jewel in _source.Jewels)
{
result.Add(jewel.GetViewModel);
}
return result;
}
public JewelViewModel? Insert(JewelBindingModel model)
{
model.Id = 1;
foreach (var jewel in _source.Jewels)
{
if (model.Id <= jewel.Id)
{
model.Id = jewel.Id + 1;
}
}
var newJewel = Jewel.Create(model);
if (newJewel == null)
{
return null;
}
_source.Jewels.Add(newJewel);
return newJewel.GetViewModel;
}
public JewelViewModel? Update(JewelBindingModel model)
{
foreach (var jewel in _source.Jewels)
{
if (jewel.Id == model.Id)
{
jewel.Update(model);
return jewel.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,110 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreListImplement.Implements
{
public class OrderStorage : IOrderStorage // TODO реализовать интерфейс
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
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 element.GetViewModel;
}
}
return null;
}
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 order.GetViewModel;
}
}
return null;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (model == null)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(order.GetViewModel);
}
}
return result;
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(order.GetViewModel);
}
return result;
}
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 newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return order.GetViewModel;
}
}
return null;
}
}
}

View File

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

View File

@ -0,0 +1,47 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreListImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,55 @@
using JewelryStoreDataModels.Models;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
namespace JewelryStoreListImplement.Models
{
public class Jewel: IJewelModel
{
public int Id { get; private set; }
public string JewelName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, (IComponentModel, int)> JewelComponents
{
get;
private set;
} = new Dictionary<int, (IComponentModel, int)>();
public static Jewel? Create(JewelBindingModel? model)
{
if (model == null)
{
return null;
}
return new Jewel()
{
Id = model.Id,
JewelName = model.JewelName,
Price = model.Price,
JewelComponents = model.JewelComponents
};
}
public void Update(JewelBindingModel? model)
{
if (model == null)
{
return;
}
JewelName = model.JewelName;
Price = model.Price;
JewelComponents = model.JewelComponents;
}
public JewelViewModel GetViewModel => new()
{
Id = Id,
JewelName = JewelName,
Price = Price,
JewelComponents = JewelComponents
};
}
}

View File

@ -0,0 +1,73 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewelryStoreDataModels.Enums;
using JewelryStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewelryStoreListImplement.Models
{
public class Order : IOrderModel // TODO Класс для модели сущности «Заказ» разработать самостоятельно
{
public int JewelId { get; private set; }
public string JewelName { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
JewelId = model.JewelId,
JewelName = model.JewelName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
JewelId = model.JewelId;
JewelName = model.JewelName;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
JewelId = JewelId,
JewelName = JewelName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}