diff --git a/SecuritySystem/SecuritySystem.sln b/SecuritySystem/SecuritySystem.sln index 1221d84..000b33c 100644 --- a/SecuritySystem/SecuritySystem.sln +++ b/SecuritySystem/SecuritySystem.sln @@ -5,6 +5,14 @@ VisualStudioVersion = 17.7.34031.279 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecuritySystem", "SecuritySystem\SecuritySystem.csproj", "{0548AE9D-59FF-4288-A519-85FF31627D7E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecuritySystemDataModels", "SecuritySystemDataModels\SecuritySystemDataModels.csproj", "{0A4860B4-91DC-4174-A4A5-789729F0E206}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecuritySystemBusinessLogiс", "SecuritySystemBusinessLogiс\SecuritySystemBusinessLogiс.csproj", "{4A8ECDB2-CD12-4A42-8580-C75F044851A0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecuritySystemContracts", "SecuritySystemContracts\SecuritySystemContracts.csproj", "{96317F35-0916-4563-B898-069D6EC0B303}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecuritySystemListImplement", "SecuritySystemListImplement\SecuritySystemListImplement.csproj", "{EEFB1807-2668-4DBF-80A0-06594D2C811C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +23,22 @@ Global {0548AE9D-59FF-4288-A519-85FF31627D7E}.Debug|Any CPU.Build.0 = Debug|Any CPU {0548AE9D-59FF-4288-A519-85FF31627D7E}.Release|Any CPU.ActiveCfg = Release|Any CPU {0548AE9D-59FF-4288-A519-85FF31627D7E}.Release|Any CPU.Build.0 = Release|Any CPU + {0A4860B4-91DC-4174-A4A5-789729F0E206}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A4860B4-91DC-4174-A4A5-789729F0E206}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A4860B4-91DC-4174-A4A5-789729F0E206}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A4860B4-91DC-4174-A4A5-789729F0E206}.Release|Any CPU.Build.0 = Release|Any CPU + {4A8ECDB2-CD12-4A42-8580-C75F044851A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4A8ECDB2-CD12-4A42-8580-C75F044851A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4A8ECDB2-CD12-4A42-8580-C75F044851A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4A8ECDB2-CD12-4A42-8580-C75F044851A0}.Release|Any CPU.Build.0 = Release|Any CPU + {96317F35-0916-4563-B898-069D6EC0B303}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {96317F35-0916-4563-B898-069D6EC0B303}.Debug|Any CPU.Build.0 = Debug|Any CPU + {96317F35-0916-4563-B898-069D6EC0B303}.Release|Any CPU.ActiveCfg = Release|Any CPU + {96317F35-0916-4563-B898-069D6EC0B303}.Release|Any CPU.Build.0 = Release|Any CPU + {EEFB1807-2668-4DBF-80A0-06594D2C811C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EEFB1807-2668-4DBF-80A0-06594D2C811C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EEFB1807-2668-4DBF-80A0-06594D2C811C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EEFB1807-2668-4DBF-80A0-06594D2C811C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/SecuritySystem/SecuritySystem/Form1.Designer.cs b/SecuritySystem/SecuritySystem/Form1.Designer.cs deleted file mode 100644 index 241ccba..0000000 --- a/SecuritySystem/SecuritySystem/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace SecuritySystem -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - 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 - } -} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/Form1.cs b/SecuritySystem/SecuritySystem/Form1.cs deleted file mode 100644 index b9d425d..0000000 --- a/SecuritySystem/SecuritySystem/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace SecuritySystem -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormCreateOrder.Designer.cs b/SecuritySystem/SecuritySystem/FormCreateOrder.Designer.cs new file mode 100644 index 0000000..b30278b --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormCreateOrder.Designer.cs @@ -0,0 +1,148 @@ +namespace SecuritySystem +{ + partial class FormCreateOrder + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonCancel = new Button(); + buttonSave = new Button(); + textBoxSum = new TextBox(); + textBoxCount = new TextBox(); + comboBoxSecure = new ComboBox(); + labelSum = new Label(); + labelCount = new Label(); + labelSecure = new Label(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(302, 115); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 15; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(205, 115); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 14; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // textBoxSum + // + textBoxSum.Location = new Point(149, 81); + textBoxSum.Margin = new Padding(3, 2, 3, 2); + textBoxSum.Name = "textBoxSum"; + textBoxSum.Size = new Size(244, 23); + textBoxSum.TabIndex = 13; + // + // textBoxCount + // + textBoxCount.Location = new Point(149, 49); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(244, 23); + textBoxCount.TabIndex = 12; + textBoxCount.TextChanged += TextBoxCount_TextChanged; + // + // comboBoxSecure + // + comboBoxSecure.FormattingEnabled = true; + comboBoxSecure.Location = new Point(149, 15); + comboBoxSecure.Margin = new Padding(3, 2, 3, 2); + comboBoxSecure.Name = "comboBoxSecure"; + comboBoxSecure.Size = new Size(244, 23); + comboBoxSecure.TabIndex = 11; + comboBoxSecure.SelectedIndexChanged += ComboBoxSecure_SelectedIndexChanged; + // + // labelSum + // + labelSum.AutoSize = true; + labelSum.Location = new Point(25, 84); + labelSum.Name = "labelSum"; + labelSum.Size = new Size(48, 15); + labelSum.TabIndex = 10; + labelSum.Text = "Сумма:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(25, 51); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 9; + labelCount.Text = "Количество:"; + // + // labelSecure + // + labelSecure.AutoSize = true; + labelSecure.Location = new Point(25, 17); + labelSecure.Name = "labelSecure"; + labelSecure.Size = new Size(56, 15); + labelSecure.TabIndex = 8; + labelSecure.Text = "Изделие:"; + // + // FormCreateOrder + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(419, 152); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxSum); + Controls.Add(textBoxCount); + Controls.Add(comboBoxSecure); + Controls.Add(labelSum); + Controls.Add(labelCount); + Controls.Add(labelSecure); + Name = "FormCreateOrder"; + Text = "Заказ"; + Load += FormCreateOrder_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSave; + private TextBox textBoxSum; + private TextBox textBoxCount; + private ComboBox comboBoxSecure; + private Label labelSum; + private Label labelCount; + private Label labelSecure; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormCreateOrder.cs b/SecuritySystem/SecuritySystem/FormCreateOrder.cs new file mode 100644 index 0000000..f30ffe6 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormCreateOrder.cs @@ -0,0 +1,146 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemDataModels.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 SecuritySystem +{ + public partial class FormCreateOrder : Form + { + private readonly ILogger _logger; + + private readonly ISecureLogic _logicM; + + private readonly IOrderLogic _logicO; + + public FormCreateOrder(ILogger logger, ISecureLogic logicM, IOrderLogic logicO) + { + InitializeComponent(); + + _logger = logger; + _logicM = logicM; + _logicO = logicO; + } + + private void FormCreateOrder_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для заказа"); + + try + { + var list = _logicM.ReadList(null); + + if (list != null) + { + comboBoxSecure.DisplayMember = "SecureName"; + comboBoxSecure.ValueMember = "Id"; + comboBoxSecure.DataSource = list; + comboBoxSecure.SelectedItem = null; + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий для заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void CalcSum() + { + if (comboBoxSecure.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) + { + try + { + int id = Convert.ToInt32(comboBoxSecure.SelectedValue); + + var secure = _logicM.ReadElement(new SecureSearchModel + { + Id = id + }); + + int count = Convert.ToInt32(textBoxCount.Text); + + textBoxSum.Text = Math.Round(count * (secure?.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 ComboBoxSecure_SelectedIndexChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (comboBoxSecure.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Создание заказа"); + + try + { + var operationResult = _logicO.CreateOrder(new OrderBindingModel + { + SecureId = Convert.ToInt32(comboBoxSecure.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text), + Sum = Convert.ToDouble(textBoxSum.Text) + }); + + if (!operationResult) + { + throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/Form1.resx b/SecuritySystem/SecuritySystem/FormCreateOrder.resx similarity index 93% rename from SecuritySystem/SecuritySystem/Form1.resx rename to SecuritySystem/SecuritySystem/FormCreateOrder.resx index 1af7de1..af32865 100644 --- a/SecuritySystem/SecuritySystem/Form1.resx +++ b/SecuritySystem/SecuritySystem/FormCreateOrder.resx @@ -1,17 +1,17 @@  - diff --git a/SecuritySystem/SecuritySystem/FormMain.Designer.cs b/SecuritySystem/SecuritySystem/FormMain.Designer.cs new file mode 100644 index 0000000..e87a235 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormMain.Designer.cs @@ -0,0 +1,178 @@ +namespace SecuritySystem +{ + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonRef = new Button(); + buttonIssuedOrder = new Button(); + buttonOrderReady = new Button(); + buttonTakeOrderInWork = new Button(); + buttonCreateOrder = new Button(); + dataGridView = new DataGridView(); + menuStrip1 = new MenuStrip(); + toolStripMenuItem = new ToolStripMenuItem(); + SensorToolStripMenuItem = new ToolStripMenuItem(); + SecureToolStripMenuItem = new ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + menuStrip1.SuspendLayout(); + SuspendLayout(); + // + // buttonRef + // + buttonRef.Location = new Point(887, 282); + buttonRef.Margin = new Padding(3, 2, 3, 2); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(206, 22); + buttonRef.TabIndex = 12; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(887, 227); + buttonIssuedOrder.Margin = new Padding(3, 2, 3, 2); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(206, 22); + buttonIssuedOrder.TabIndex = 11; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonOrderReady + // + buttonOrderReady.Location = new Point(887, 170); + buttonOrderReady.Margin = new Padding(3, 2, 3, 2); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(206, 22); + buttonOrderReady.TabIndex = 10; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = true; + buttonOrderReady.Click += ButtonOrderReady_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Location = new Point(887, 112); + buttonTakeOrderInWork.Margin = new Padding(3, 2, 3, 2); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(206, 22); + buttonTakeOrderInWork.TabIndex = 9; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = true; + buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(887, 55); + buttonCreateOrder.Margin = new Padding(3, 2, 3, 2); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(206, 22); + buttonCreateOrder.TabIndex = 8; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(10, 32); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(820, 302); + dataGridView.TabIndex = 7; + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Padding = new Padding(5, 2, 0, 2); + menuStrip1.Size = new Size(1135, 24); + menuStrip1.TabIndex = 13; + menuStrip1.Text = "menuStrip1"; + // + // toolStripMenuItem + // + toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SensorToolStripMenuItem, SecureToolStripMenuItem }); + toolStripMenuItem.Name = "toolStripMenuItem"; + toolStripMenuItem.Size = new Size(94, 20); + toolStripMenuItem.Text = "Справочники"; + // + // SensorToolStripMenuItem + // + SensorToolStripMenuItem.Name = "SensorToolStripMenuItem"; + SensorToolStripMenuItem.Size = new Size(180, 22); + SensorToolStripMenuItem.Text = "Заготовки"; + SensorToolStripMenuItem.Click += SensorToolStripMenuItem_Click; + // + // SecureToolStripMenuItem + // + SecureToolStripMenuItem.Name = "SecureToolStripMenuItem"; + SecureToolStripMenuItem.Size = new Size(180, 22); + SecureToolStripMenuItem.Text = "Изделия"; + SecureToolStripMenuItem.Click += SecureToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1135, 338); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + Name = "FormMain"; + Text = "SecuritySystem"; + Load += FormMain_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonRef; + private Button buttonIssuedOrder; + private Button buttonOrderReady; + private Button buttonTakeOrderInWork; + private Button buttonCreateOrder; + private DataGridView dataGridView; + private MenuStrip menuStrip1; + private ToolStripMenuItem toolStripMenuItem; + private ToolStripMenuItem SensorToolStripMenuItem; + private ToolStripMenuItem SecureToolStripMenuItem; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormMain.cs b/SecuritySystem/SecuritySystem/FormMain.cs new file mode 100644 index 0000000..9d81a3a --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormMain.cs @@ -0,0 +1,186 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemDataModels.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 SecuritySystem +{ + public partial class FormMain : Form + { + private readonly ILogger _logger; + + private readonly IOrderLogic _orderLogic; + + public FormMain(ILogger 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["SecureId"].Visible = false; + } + + _logger.LogInformation(" "); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void SensorToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSensors)); + + if (service is FormSensors form) + { + form.ShowDialog(); + } + } + + private void SecureToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSecures)); + + if (service is FormSecures form) + { + form.ShowDialog(); + } + } + + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + + } + + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation(" {id}. ' '", id); + + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception(" . ."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation(" {id}. ''", id); + + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception(" . ."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation(" {id}. ''", id); + + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + + if (!operationResult) + { + throw new Exception(" . ."); + } + + _logger.LogInformation(" {id} ", id); + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormMain.resx b/SecuritySystem/SecuritySystem/FormMain.resx new file mode 100644 index 0000000..a0623c8 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormMain.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecure.Designer.cs b/SecuritySystem/SecuritySystem/FormSecure.Designer.cs new file mode 100644 index 0000000..c54b7e7 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecure.Designer.cs @@ -0,0 +1,239 @@ +namespace SecuritySystem +{ + partial class FormSecure + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + groupBoxSensor = new GroupBox(); + buttonRef = new Button(); + buttonDel = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); + dataGridView = new DataGridView(); + ColumnID = new DataGridViewTextBoxColumn(); + ColumnName = new DataGridViewTextBoxColumn(); + ColumnPrice = new DataGridViewTextBoxColumn(); + textBoxPrice = new TextBox(); + textBoxName = new TextBox(); + labelCost = new Label(); + labelName = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + groupBoxSensor.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // groupBoxSensor + // + groupBoxSensor.Controls.Add(buttonRef); + groupBoxSensor.Controls.Add(buttonDel); + groupBoxSensor.Controls.Add(buttonUpd); + groupBoxSensor.Controls.Add(buttonAdd); + groupBoxSensor.Controls.Add(dataGridView); + groupBoxSensor.Location = new Point(23, 92); + groupBoxSensor.Margin = new Padding(3, 2, 3, 2); + groupBoxSensor.Name = "groupBoxSensor"; + groupBoxSensor.Padding = new Padding(3, 2, 3, 2); + groupBoxSensor.Size = new Size(496, 225); + groupBoxSensor.TabIndex = 11; + groupBoxSensor.TabStop = false; + groupBoxSensor.Text = "Заготовки"; + // + // buttonRef + // + buttonRef.Location = new Point(397, 147); + buttonRef.Margin = new Padding(3, 2, 3, 2); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(82, 22); + buttonRef.TabIndex = 4; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonDel + // + buttonDel.Location = new Point(397, 109); + buttonDel.Margin = new Padding(3, 2, 3, 2); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(82, 22); + buttonDel.TabIndex = 3; + buttonDel.Text = "Удалить"; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonUpd + // + buttonUpd.Location = new Point(397, 71); + buttonUpd.Margin = new Padding(3, 2, 3, 2); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(82, 22); + buttonUpd.TabIndex = 2; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(397, 32); + buttonAdd.Margin = new Padding(3, 2, 3, 2); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(82, 22); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnID, ColumnName, ColumnPrice }); + dataGridView.Location = new Point(5, 20); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(382, 201); + dataGridView.TabIndex = 0; + // + // ColumnID + // + ColumnID.HeaderText = "Id"; + ColumnID.MinimumWidth = 6; + ColumnID.Name = "ColumnID"; + ColumnID.Visible = false; + ColumnID.Width = 125; + // + // ColumnName + // + ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnName.HeaderText = "Название"; + ColumnName.MinimumWidth = 6; + ColumnName.Name = "ColumnName"; + // + // ColumnPrice + // + ColumnPrice.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnPrice.HeaderText = "Количество"; + ColumnPrice.MinimumWidth = 6; + ColumnPrice.Name = "ColumnPrice"; + // + // textBoxPrice + // + textBoxPrice.Location = new Point(119, 59); + textBoxPrice.Margin = new Padding(3, 2, 3, 2); + textBoxPrice.Name = "textBoxPrice"; + textBoxPrice.Size = new Size(172, 23); + textBoxPrice.TabIndex = 10; + // + // textBoxName + // + textBoxName.Location = new Point(119, 18); + textBoxName.Margin = new Padding(3, 2, 3, 2); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(291, 23); + textBoxName.TabIndex = 9; + // + // labelCost + // + labelCost.AutoSize = true; + labelCost.Location = new Point(23, 61); + labelCost.Name = "labelCost"; + labelCost.Size = new Size(70, 15); + labelCost.TabIndex = 8; + labelCost.Text = "Стоимость:"; + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(23, 20); + labelName.Name = "labelName"; + labelName.Size = new Size(62, 15); + labelName.TabIndex = 7; + labelName.Text = "Название:"; + // + // buttonCancel + // + buttonCancel.Location = new Point(404, 334); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 13; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(301, 334); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(83, 22); + buttonSave.TabIndex = 12; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormSecure + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(542, 375); + Controls.Add(groupBoxSensor); + Controls.Add(textBoxPrice); + Controls.Add(textBoxName); + Controls.Add(labelCost); + Controls.Add(labelName); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Name = "FormSecure"; + Text = "Изделие"; + Click += FormSecure_Load; + groupBoxSensor.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private GroupBox groupBoxSensor; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnID; + private DataGridViewTextBoxColumn ColumnName; + private DataGridViewTextBoxColumn ColumnPrice; + private TextBox textBoxPrice; + private TextBox textBoxName; + private Label labelCost; + private Label labelName; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecure.cs b/SecuritySystem/SecuritySystem/FormSecure.cs new file mode 100644 index 0000000..0d19bbb --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecure.cs @@ -0,0 +1,246 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemDataModels.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 SecuritySystem +{ + public partial class FormSecure : Form + { + private readonly ILogger _logger; + + private readonly ISecureLogic _logic; + + private int? _id; + + private Dictionary _secureSensors; + + public int Id { set { _id = value; } } + + public FormSecure(ILogger logger, ISecureLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + _secureSensors = new Dictionary(); + } + + private void FormSecure_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); + + try + { + var view = _logic.ReadElement(new SecureSearchModel { Id = _id.Value }); + + if (view != null) + { + textBoxName.Text = view.SecureName; + textBoxPrice.Text = view.Price.ToString(); + _secureSensors = view.SecureSensors ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка заготовок для изделия"); + + try + { + if (_secureSensors != null) + { + dataGridView.Rows.Clear(); + + foreach (var awp in _secureSensors) + { + dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.SensorName, awp.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(FormSecureSensor)); + + if (service is FormSecureSensor form) + { + if (form.ShowDialog() == DialogResult.OK) + { + if (form.SensorModel == null) + { + return; + } + + _logger.LogInformation("Добавление новой заготовки:{SensorName} - {Count}", form.SensorModel.SensorName, form.Count); + + if (_secureSensors.ContainsKey(form.Id)) + { + _secureSensors[form.Id] = (form.SensorModel, form.Count); + } + else + { + _secureSensors.Add(form.Id, (form.SensorModel, form.Count)); + } + + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSecureSensor)); + + if (service is FormSecureSensor form) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _secureSensors[id].Item2; + + if (form.ShowDialog() == DialogResult.OK) + { + if (form.SensorModel == null) + { + return; + } + + _logger.LogInformation("Изменение компонента:{SensorName} - {Count}", form.SensorModel.SensorName, form.Count); + _secureSensors[form.Id] = (form.SensorModel, form.Count); + + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + try + { + _logger.LogInformation("Удаление заготовки:{SensorName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _secureSensors?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + LoadData(); + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (_secureSensors == null || _secureSensors.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + _logger.LogInformation("Сохранение изделия"); + + try + { + var model = new SecureBindingModel + { + Id = _id ?? 0, + SecureName = textBoxName.Text, + Price = Convert.ToDouble(textBoxPrice.Text), + SecureSensors = _secureSensors + }; + + 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(); + } + + //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) + private double CalcPrice() + { + double price = 0; + + foreach (var elem in _secureSensors) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } + + return Math.Round(price * 1.1, 2); + } + } +} diff --git a/SecuritySystem/SecuritySystem/FormSecure.resx b/SecuritySystem/SecuritySystem/FormSecure.resx new file mode 100644 index 0000000..7dc5109 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecure.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecureSensor.Designer.cs b/SecuritySystem/SecuritySystem/FormSecureSensor.Designer.cs new file mode 100644 index 0000000..b1e40db --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecureSensor.Designer.cs @@ -0,0 +1,122 @@ +namespace SecuritySystem +{ + partial class FormSecureSensor + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonCancel = new Button(); + buttonSave = new Button(); + textBoxCount = new TextBox(); + comboBoxSensor = new ComboBox(); + labelCount = new Label(); + labelSensor = new Label(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(318, 85); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 11; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(215, 85); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 10; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // textBoxCount + // + textBoxCount.Location = new Point(145, 54); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(280, 23); + textBoxCount.TabIndex = 9; + // + // comboBoxSensor + // + comboBoxSensor.FormattingEnabled = true; + comboBoxSensor.Location = new Point(145, 19); + comboBoxSensor.Margin = new Padding(3, 2, 3, 2); + comboBoxSensor.Name = "comboBoxSensor"; + comboBoxSensor.Size = new Size(280, 23); + comboBoxSensor.TabIndex = 8; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(36, 56); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 7; + labelCount.Text = "Количество:"; + // + // labelSensor + // + labelSensor.AutoSize = true; + labelSensor.Location = new Point(36, 22); + labelSensor.Name = "labelSensor"; + labelSensor.Size = new Size(65, 15); + labelSensor.TabIndex = 6; + labelSensor.Text = "Заготовка:"; + // + // FormSecureSensors + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(460, 126); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(comboBoxSensor); + Controls.Add(labelCount); + Controls.Add(labelSensor); + Name = "FormSecureSensors"; + Text = "Заготовки для изделия"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSave; + private TextBox textBoxCount; + private ComboBox comboBoxSensor; + private Label labelCount; + private Label labelSensor; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecureSensor.cs b/SecuritySystem/SecuritySystem/FormSecureSensor.cs new file mode 100644 index 0000000..a0a7fcf --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecureSensor.cs @@ -0,0 +1,98 @@ +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Reflection.Metadata.Ecma335; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SecuritySystem +{ + public partial class FormSecureSensor : Form + { + private readonly List? _list; + + public int Id + { + get { return Convert.ToInt32(comboBoxSensor.SelectedValue); } + set { comboBoxSensor.SelectedValue = value; } + } + + public ISensorModel? SensorModel + { + 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 FormSecureSensor(ISensorLogic logic) + { + InitializeComponent(); + + _list = logic.ReadList(null); + + if (_list != null) + { + comboBoxSensor.DisplayMember = "SensorName"; + comboBoxSensor.ValueMember = "Id"; + comboBoxSensor.DataSource = _list; + comboBoxSensor.SelectedItem = null; + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + return; + } + + if (comboBoxSensor.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(); + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecureSensor.resx b/SecuritySystem/SecuritySystem/FormSecureSensor.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecureSensor.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecures.Designer.cs b/SecuritySystem/SecuritySystem/FormSecures.Designer.cs new file mode 100644 index 0000000..4e5deb3 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecures.Designer.cs @@ -0,0 +1,119 @@ +namespace SecuritySystem +{ + partial class FormSecures + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonRef = new Button(); + buttonDelete = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(20, 9); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(528, 320); + dataGridView.TabIndex = 9; + // + // buttonRef + // + buttonRef.Location = new Point(581, 152); + buttonRef.Margin = new Padding(3, 2, 3, 2); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(82, 22); + buttonRef.TabIndex = 8; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(581, 113); + buttonDelete.Margin = new Padding(3, 2, 3, 2); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(82, 22); + buttonDelete.TabIndex = 7; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonUpd + // + buttonUpd.Location = new Point(581, 69); + buttonUpd.Margin = new Padding(3, 2, 3, 2); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(82, 22); + buttonUpd.TabIndex = 6; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(581, 27); + buttonAdd.Margin = new Padding(3, 2, 3, 2); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(82, 22); + buttonAdd.TabIndex = 5; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // FormSecures + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(683, 338); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonDelete); + Controls.Add(buttonUpd); + Controls.Add(buttonAdd); + Name = "FormSecures"; + Text = "Изделия"; + Load += FormSecures_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonRef; + private Button buttonDelete; + private Button buttonUpd; + private Button buttonAdd; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecures.cs b/SecuritySystem/SecuritySystem/FormSecures.cs new file mode 100644 index 0000000..a890938 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecures.cs @@ -0,0 +1,125 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.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 SecuritySystem +{ + public partial class FormSecures : Form + { + private readonly ILogger _logger; + + private readonly ISecureLogic _logic; + public FormSecures(ILogger logger, ISecureLogic logic) + { + + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + private void FormSecures_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["SecureSensors"].Visible = false; + dataGridView.Columns["SecureName"].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(FormSecure)); + + if (service is FormSecure form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSecure)); + + if (service is FormSecure form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + + _logger.LogInformation("Удаление изделия"); + + try + { + if (!_logic.Delete(new SecureBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSecures.resx b/SecuritySystem/SecuritySystem/FormSecures.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSecures.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSensor.Designer.cs b/SecuritySystem/SecuritySystem/FormSensor.Designer.cs new file mode 100644 index 0000000..fc47bd3 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensor.Designer.cs @@ -0,0 +1,122 @@ +namespace SecuritySystem +{ + partial class FormSensor + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonSave = new Button(); + buttonCancel = new Button(); + textBoxCost = new TextBox(); + textBoxName = new TextBox(); + labelPrice = new Label(); + labelName = new Label(); + SuspendLayout(); + // + // buttonSave + // + buttonSave.Location = new Point(192, 77); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 11; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(291, 77); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 10; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // textBoxCost + // + textBoxCost.Location = new Point(117, 45); + textBoxCost.Margin = new Padding(3, 2, 3, 2); + textBoxCost.Name = "textBoxCost"; + textBoxCost.Size = new Size(157, 23); + textBoxCost.TabIndex = 9; + // + // textBoxName + // + textBoxName.Location = new Point(117, 15); + textBoxName.Margin = new Padding(3, 2, 3, 2); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(257, 23); + textBoxName.TabIndex = 8; + // + // labelPrice + // + labelPrice.AutoSize = true; + labelPrice.Location = new Point(32, 48); + labelPrice.Name = "labelPrice"; + labelPrice.Size = new Size(38, 15); + labelPrice.TabIndex = 7; + labelPrice.Text = "Цена:"; + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(32, 17); + labelName.Name = "labelName"; + labelName.Size = new Size(62, 15); + labelName.TabIndex = 6; + labelName.Text = "Название:"; + // + // FormSensor + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(406, 115); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(textBoxCost); + Controls.Add(textBoxName); + Controls.Add(labelPrice); + Controls.Add(labelName); + Name = "FormSensor"; + Text = "Заготовка"; + Load += FormSensor_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSave; + private Button buttonCancel; + private TextBox textBoxCost; + private TextBox textBoxName; + private Label labelPrice; + private Label labelName; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSensor.cs b/SecuritySystem/SecuritySystem/FormSensor.cs new file mode 100644 index 0000000..e4f9c06 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensor.cs @@ -0,0 +1,104 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using Microsoft.Extensions.Logging; + +namespace SecuritySystem +{ + //форма "Заготовка" + public partial class FormSensor : Form + { + private readonly ILogger _logger; + + private readonly ISensorLogic _logic; + + private int? _id; + + public int Id { set { _id = value; } } + + //конструктор + public FormSensor(ILogger logger, ISensorLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + //при загрузке формы + private void FormSensor_Load(object sender, EventArgs e) + { + //проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение заготовки"); + + var view = _logic.ReadElement(new SensorSearchModel { Id = _id.Value }); + + if (view != null) + { + textBoxName.Text = view.SensorName; + 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 SensorBindingModel + { + Id = _id ?? 0, + SensorName = 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(); + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSensor.resx b/SecuritySystem/SecuritySystem/FormSensor.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensor.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSensors.Designer.cs b/SecuritySystem/SecuritySystem/FormSensors.Designer.cs new file mode 100644 index 0000000..df4a934 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensors.Designer.cs @@ -0,0 +1,119 @@ +namespace SecuritySystem +{ + partial class FormSensors + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonRef = new Button(); + buttonDelete = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(20, 9); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(528, 320); + dataGridView.TabIndex = 9; + // + // buttonRef + // + buttonRef.Location = new Point(581, 152); + buttonRef.Margin = new Padding(3, 2, 3, 2); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(82, 22); + buttonRef.TabIndex = 8; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(581, 113); + buttonDelete.Margin = new Padding(3, 2, 3, 2); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(82, 22); + buttonDelete.TabIndex = 7; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // buttonUpd + // + buttonUpd.Location = new Point(581, 69); + buttonUpd.Margin = new Padding(3, 2, 3, 2); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(82, 22); + buttonUpd.TabIndex = 6; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(581, 27); + buttonAdd.Margin = new Padding(3, 2, 3, 2); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(82, 22); + buttonAdd.TabIndex = 5; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // FormSensors + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(683, 338); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonDelete); + Controls.Add(buttonUpd); + Controls.Add(buttonAdd); + Name = "FormSensors"; + Text = "Заготовки"; + Load += FormSensor_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonRef; + private Button buttonDelete; + private Button buttonUpd; + private Button buttonAdd; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormSensors.cs b/SecuritySystem/SecuritySystem/FormSensors.cs new file mode 100644 index 0000000..f8035d9 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensors.cs @@ -0,0 +1,126 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.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 SecuritySystem +{ + public partial class FormSensors : Form + { + private readonly ILogger _logger; + + private readonly ISensorLogic _logic; + + public FormSensors(ILogger logger, ISensorLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormSensor_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + + //растягиваем колонку Название на всю ширину, колонку Id скрываем + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["SensorName"].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(FormSensor)); + + if (service is FormSensor form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + //проверяем наличие выделенной строки + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSensor)); + + if (service is FormSensor form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDelete_Click(object sender, EventArgs e) + { + //проверяем наличие выделенной строки + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + + _logger.LogInformation("Удаление компонента"); + + try + { + if (!_logic.Delete(new SensorBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/SecuritySystem/SecuritySystem/FormSensors.resx b/SecuritySystem/SecuritySystem/FormSensors.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SecuritySystem/SecuritySystem/FormSensors.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/Program.cs b/SecuritySystem/SecuritySystem/Program.cs index 1cae504..7d690c7 100644 --- a/SecuritySystem/SecuritySystem/Program.cs +++ b/SecuritySystem/SecuritySystem/Program.cs @@ -1,17 +1,57 @@ +using SecuritySystemBusinessLogic.BusinessLogic; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemListImplement.Implements; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +using System.Drawing; + namespace SecuritySystem { internal static class Program { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, + // 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()); } + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } } \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/SecuritySystem.csproj b/SecuritySystem/SecuritySystem/SecuritySystem.csproj index b57c89e..35c7ef6 100644 --- a/SecuritySystem/SecuritySystem/SecuritySystem.csproj +++ b/SecuritySystem/SecuritySystem/SecuritySystem.csproj @@ -8,4 +8,17 @@ enable + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/OrderLogic.cs b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/OrderLogic.cs new file mode 100644 index 0000000..6f4927d --- /dev/null +++ b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/OrderLogic.cs @@ -0,0 +1,173 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.BusinessLogic +{ + public class OrderLogic : IOrderLogic + { + private readonly ILogger _logger; + + private readonly IOrderStorage _orderStorage; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { + _logger = logger; + _orderStorage = orderStorage; + } + + //вывод отфильтрованного списка компонентов + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. Id:{Id}", model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + + if(list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //создание чека + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + + if(model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Insert operation failed, incorrect order status"); + return false; + } + + model.Status = OrderStatus.Принят; + + if(_orderStorage.Insert(model) == null) + { + model.Status = OrderStatus.Неизвестен; + _logger.LogWarning("Insert operation failed"); + return false; + } + + return true; + } + + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } + + public bool FinishOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Готов); + } + + public bool DeliveryOrder(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выдан); + } + + //проверка на пустоту входного параметра + private void CheckModel(OrderBindingModel model, bool withParams = true) + { + if(model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении параметром withParams передаём false + if (!withParams) + { + return; + } + + //проверка на наличие товаров в заказе + if(model.Count <= 0) + { + throw new ArgumentNullException("В заказе не может быть 0 изделий", nameof(model.Count)); + } + + //проверка на наличие нормальной суммарной стоимости чека + if(model.Sum <= 0) + { + throw new ArgumentNullException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + } + + //проверка корректности id у изделий + if (model.SecureId < 0) + { + throw new ArgumentNullException("Некорректный id у изделия", nameof(model.SecureId)); + } + + //проверка корректности дат + if(model.DateCreate > model.DateImplement) + { + throw new InvalidOperationException("Дата создания должна быть более ранней, нежели дата завершения"); + } + + _logger.LogInformation("Order. OrderId:{Id}. Sun:{Sum}. SecureId:{Id}", model.Id, model.Sum, model.SecureId); + } + + //обновление статуса заказа + public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + + //если не смогли найти указанный заказ по его Id + if(viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //проверка на возможность обновления статуса на следующий + if (viewModel.Status + 1 != newOrderStatus) + { + _logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect"); + return false; + } + + model.Status = newOrderStatus; + + //проверка на выдачу + if(model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = viewModel.DateImplement; + } + + CheckModel(model, false); + + //финальная проверка на возможность обновления + if (_orderStorage.Update(model) == null) + { + model.Status--; + + _logger.LogWarning("Update operation failed"); + + return false; + } + + return true; + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SecureLogic.cs b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SecureLogic.cs new file mode 100644 index 0000000..52bd933 --- /dev/null +++ b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SecureLogic.cs @@ -0,0 +1,160 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.BusinessLogic +{ + public class SecureLogic : ISecureLogic + { + private readonly ILogger _logger; + + private readonly ISecureStorage _secureStorage; + + //конструктор + public SecureLogic(ILogger logger, ISecureStorage secureStorage) + { + _logger = logger; + _secureStorage = secureStorage; + } + + //вывод отфильтрованного списка + public List? ReadList(SecureSearchModel? model) + { + _logger.LogInformation("ReadList. SecureName:{SecureName}. Id:{Id}", model?.SecureName, model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _secureStorage.GetFullList() : _secureStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //вывод конкретного изделия + public SecureViewModel? ReadElement(SecureSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. SecureName:{SecureName}. Id:{Id}", model.SecureName, model.Id); + + var element = _secureStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + + return null; + } + + _logger.LogInformation("ReadElement find. Id:{Id}", model.Id); + + return element; + } + + //Создание изделия + public bool Create(SecureBindingModel model) + { + CheckModel(model); + + if (_secureStorage.Insert(model) == null) + { + _logger.LogWarning("Create operation failed"); + + return false; + } + + return true; + } + + //обновление изделия + public bool Update(SecureBindingModel model) + { + CheckModel(model); + + if (_secureStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + + return true; + } + + //удаление изделия + public bool Delete(SecureBindingModel model) + { + CheckModel(model, false); + + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_secureStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + + return false; + } + + return true; + } + + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(SecureBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении параметром withParams передаём false + if (!withParams) + { + return; + } + + //проверка на наличие названия изделия + if (string.IsNullOrEmpty(model.SecureName)) + { + throw new ArgumentNullException("Нет названия изделия", nameof(model.SecureName)); + } + + //проверка на наличие нормальной цены у изделия + if (model.Price <= 0) + { + throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price)); + } + + _logger.LogInformation("Secure. SecureName:{SecureName}. Price:{Price}. Id:{Id}", + model.SecureName, model.Price, model.Id); + + //проверка на наличие такого же изделия в списке + var element = _secureStorage.GetElement(new SecureSearchModel + { + SecureName = model.SecureName, + }); + + //если элемент найден и его Id не совпадает с Id объекта, переданного на вход + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Изделие с таким названием уже есть"); + } + } + } +} diff --git a/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SensorLogic.cs b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SensorLogic.cs new file mode 100644 index 0000000..3af22b1 --- /dev/null +++ b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/SensorLogic.cs @@ -0,0 +1,161 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.BusinessLogic +{ + //класс, реализующий логику для заготовок + public class SensorLogic : ISensorLogic + { + private readonly ILogger _logger; + + private readonly ISensorStorage _sensorStorage; + + //конструктор + public SensorLogic(ILogger logger, ISensorStorage sensorStorage) + { + _logger = logger; + _sensorStorage = sensorStorage; + } + + //вывод отфильтрованного списка компонентов + public List? ReadList(SensorSearchModel? model) + { + _logger.LogInformation("ReadList. SensorName:{SensorName}. Id:{Id}", model?.SensorName, model?.Id); + + //list хранит весь список в случае, если model пришло со значением null на вход метода + var list = model == null ? _sensorStorage.GetFullList() : _sensorStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + + return list; + } + + //вывод конкретного заготовки + public SensorViewModel? ReadElement(SensorSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. SensorName:{SensorName}. Id:{Id}", model.SensorName, model.Id); + + var element = _sensorStorage.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(SensorBindingModel model) + { + CheckModel(model); + + if (_sensorStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + //обновление заготовки + public bool Update(SensorBindingModel model) + { + CheckModel(model); + + if (_sensorStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + + return false; + } + + return true; + } + + //удаление заготовки + public bool Delete(SensorBindingModel model) + { + CheckModel(model, false); + + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_sensorStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + + return false; + } + + return true; + } + + //проверка входного аргумента для методов Insert, Update и Delete + private void CheckModel(SensorBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + //так как при удалении передаём как параметр false + if (!withParams) + { + return; + } + + //проверка на наличие названия заготовки + if (string.IsNullOrEmpty(model.SensorName)) + { + throw new ArgumentNullException("Нет названия заготовки", nameof(model.SensorName)); + } + + //проверка на наличие нормальной цены у заготовки + if (model.Cost <= 0) + { + throw new ArgumentNullException("Цена заготовки должна быть больше 0", nameof(model.Cost)); + } + + _logger.LogInformation("Sensor. SensorName:{SensorName}. Cost:{Cost}. Id:{Id}", + model.SensorName, model.Cost, model.Id); + + //проверка на наличие такой же заготовки в списке + var element = _sensorStorage.GetElement(new SensorSearchModel + { + SensorName = model.SensorName, + }); + + //если элемент найден и его Id не совпадает с Id переданного объекта + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Заготовка с таким названием уже есть"); + } + } + } +} diff --git a/SecuritySystem/SecuritySystemBusinessLogiс/SecuritySystemBusinessLogiс.csproj b/SecuritySystem/SecuritySystemBusinessLogiс/SecuritySystemBusinessLogiс.csproj new file mode 100644 index 0000000..7715917 --- /dev/null +++ b/SecuritySystem/SecuritySystemBusinessLogiс/SecuritySystemBusinessLogiс.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + diff --git a/SecuritySystem/SecuritySystemContracts/BindingModels/OrderBindingModel.cs b/SecuritySystem/SecuritySystemContracts/BindingModels/OrderBindingModel.cs new file mode 100644 index 0000000..634300c --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BindingModels/OrderBindingModel.cs @@ -0,0 +1,28 @@ +using SecuritySystemDataModels.Enums; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BindingModels +{ + //реализация сущности "Заказ" + public class OrderBindingModel : IOrderModel + { + public int Id { get; set; } + + public int SecureId { 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; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/BindingModels/SecureBindingModel.cs b/SecuritySystem/SecuritySystemContracts/BindingModels/SecureBindingModel.cs new file mode 100644 index 0000000..3de1bbe --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BindingModels/SecureBindingModel.cs @@ -0,0 +1,21 @@ +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BindingModels +{ + //реализация сущности "Изделие" + public class SecureBindingModel : ISecureModel + { + public int Id { get; set; } + + public string SecureName { get; set; } = string.Empty; + + public double Price { get; set; } + + public Dictionary SecureSensors { get; set; } = new(); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/BindingModels/SensorsBindingModel.cs b/SecuritySystem/SecuritySystemContracts/BindingModels/SensorsBindingModel.cs new file mode 100644 index 0000000..fc378fa --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BindingModels/SensorsBindingModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SecuritySystemDataModels.Models; + +namespace SecuritySystemContracts.BindingModels +{ + //реализация сущности "Компонент" + public class SensorBindingModel : ISensorModel + { + public int Id { get; set; } + + public string SensorName { get; set; } = string.Empty; + + public double Cost { get; set; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs new file mode 100644 index 0000000..88d38bb --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -0,0 +1,25 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BusinessLogicsContracts +{ + //бизнес-логика для заказов + public interface IOrderLogic + { + List? ReadList(OrderSearchModel? model); + + bool CreateOrder(OrderBindingModel model); + + bool TakeOrderInWork(OrderBindingModel model); + + bool FinishOrder(OrderBindingModel model); + + bool DeliveryOrder(OrderBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISecureLogic.cs b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISecureLogic.cs new file mode 100644 index 0000000..61d34b4 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISecureLogic.cs @@ -0,0 +1,25 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BusinessLogicsContracts +{ + //бизнес-логика для продуктов + public interface ISecureLogic + { + List? ReadList(SecureSearchModel? model); + + SecureViewModel? ReadElement(SecureSearchModel model); + + bool Create(SecureBindingModel model); + + bool Update(SecureBindingModel model); + + bool Delete(SecureBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISensorsLogic.cs b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISensorsLogic.cs new file mode 100644 index 0000000..f3ff9da --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/ISensorsLogic.cs @@ -0,0 +1,25 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BusinessLogicsContracts +{ + //бизнес-логика для компонентов + public interface ISensorLogic + { + List? ReadList(SensorSearchModel? model); + + SensorViewModel? ReadElement(SensorSearchModel model); + + bool Create(SensorBindingModel model); + + bool Update(SensorBindingModel model); + + bool Delete(SensorBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/SearchModels/OrderSearchModel.cs b/SecuritySystem/SecuritySystemContracts/SearchModels/OrderSearchModel.cs new file mode 100644 index 0000000..c2b1786 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/SearchModels/OrderSearchModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.SearchModels +{ + //для поиска сущности "Заказ" + public class OrderSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/SearchModels/SecureSearchModel.cs b/SecuritySystem/SecuritySystemContracts/SearchModels/SecureSearchModel.cs new file mode 100644 index 0000000..69ec334 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/SearchModels/SecureSearchModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.SearchModels +{ + //модель для поиска заготовки "Продукт" (она же изделие) + public class SecureSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + + //для поиска по названию + public string? SecureName { get; set; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/SearchModels/SensorsSearchModel.cs b/SecuritySystem/SecuritySystemContracts/SearchModels/SensorsSearchModel.cs new file mode 100644 index 0000000..aeee797 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/SearchModels/SensorsSearchModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.SearchModels +{ + //модель для поиска сущности "Компонент" (она же заготовка) + public class SensorSearchModel + { + //для поиска по идентификатору + public int? Id { get; set; } + + //для поиска по названию + public string? SensorName { get; set; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj b/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj new file mode 100644 index 0000000..e0d29fa --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + diff --git a/SecuritySystem/SecuritySystemContracts/StoragesContracts/IOrderStorage.cs b/SecuritySystem/SecuritySystemContracts/StoragesContracts/IOrderStorage.cs new file mode 100644 index 0000000..78119ca --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/StoragesContracts/IOrderStorage.cs @@ -0,0 +1,27 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.StoragesContracts +{ + //класс для хранилища заказов + public interface IOrderStorage + { + List GetFullList(); + + List GetFilteredList(OrderSearchModel model); + + OrderViewModel? GetElement(OrderSearchModel model); + + OrderViewModel? Insert(OrderBindingModel model); + + OrderViewModel? Update(OrderBindingModel model); + + OrderViewModel? Delete(OrderBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISecureStorage.cs b/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISecureStorage.cs new file mode 100644 index 0000000..3c211ac --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISecureStorage.cs @@ -0,0 +1,27 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.StoragesContracts +{ + //класс для хранилища продуктов (изделий) + public interface ISecureStorage + { + List GetFullList(); + + List GetFilteredList(SecureSearchModel model); + + SecureViewModel? GetElement(SecureSearchModel model); + + SecureViewModel? Insert(SecureBindingModel model); + + SecureViewModel? Update(SecureBindingModel model); + + SecureViewModel? Delete(SecureBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISensorsStorage.cs b/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISensorsStorage.cs new file mode 100644 index 0000000..1f3a4aa --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/StoragesContracts/ISensorsStorage.cs @@ -0,0 +1,27 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.StoragesContracts +{ + //класс хранилища компонентов (заготовок) + public interface ISensorStorage + { + List GetFullList(); + + List GetFilteredList(SensorSearchModel model); + + SensorViewModel? GetElement(SensorSearchModel model); + + SensorViewModel? Insert(SensorBindingModel model); + + SensorViewModel? Update(SensorBindingModel model); + + SensorViewModel? Delete(SensorBindingModel model); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs new file mode 100644 index 0000000..7a1462e --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs @@ -0,0 +1,38 @@ +using SecuritySystemDataModels.Enums; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.ViewModels +{ + //класс для отображения пользователю информации о заказах + public class OrderViewModel : IOrderModel + { + [DisplayName("Номер")] + public int Id { get; set; } + + public int SecureId { get; set; } + + [DisplayName("Изделие")] + public string SecureName { 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; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs new file mode 100644 index 0000000..b9d82f6 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs @@ -0,0 +1,24 @@ +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.ViewModels +{ + //класс для отображения пользователю информаци о продуктах (изделиях) + public class SecureViewModel : ISecureModel + { + public int Id { get; set; } + + [DisplayName("Навание изделия")] + public string SecureName { get; set; } = string.Empty; + + [DisplayName("Цена")] + public double Price { get; set; } + + public Dictionary SecureSensors { get; set; } = new(); + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs new file mode 100644 index 0000000..a7e46fc --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs @@ -0,0 +1,22 @@ +using SecuritySystemDataModels.Models; +using System.ComponentModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.ViewModels +{ + //класс для отображения пользователю данных + public class SensorViewModel : ISensorModel + { + public int Id { get; set; } + + [DisplayName("Название Датчика")] + public string SensorName { get; set; } = string.Empty; + + [DisplayName("Цена")] + public double Cost { get; set; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/Enums/OrderStatus.cs b/SecuritySystem/SecuritySystemDataModels/Enums/OrderStatus.cs new file mode 100644 index 0000000..5a90b04 --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/Enums/OrderStatus.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDataModels.Enums +{ + //статус заказа + public enum OrderStatus + { + Неизвестен = -1, + + Принят = 0, + + Выполняется = 1, + + Готов = 2, + + Выдан = 3 + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/IId.cs b/SecuritySystem/SecuritySystemDataModels/IId.cs new file mode 100644 index 0000000..ccdc348 --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/IId.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDataModels +{ + //интерфейс, отвечающий за id у компонентов, продуктов и чеков + public interface IId + { + int Id { get; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/Models/IOrderModel.cs b/SecuritySystem/SecuritySystemDataModels/Models/IOrderModel.cs new file mode 100644 index 0000000..cda6421 --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/Models/IOrderModel.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SecuritySystemDataModels.Enums; + +namespace SecuritySystemDataModels.Models +{ + //интерфейс, отвечающий за заказ + public interface IOrderModel : IId + { + //id продукта + int SecureId { get; } + + //кол-во продуктов + int Count { get; } + + //суммарная стоимость продуктов + double Sum { get; } + + //статус заказа + OrderStatus Status { get; } + + //дата создания заказа + DateTime DateCreate { get; } + + //дата завершения заказа (не обязательна к указанию сразу) + DateTime? DateImplement { get; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/Models/ISecureModel.cs b/SecuritySystem/SecuritySystemDataModels/Models/ISecureModel.cs new file mode 100644 index 0000000..659d21e --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/Models/ISecureModel.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDataModels.Models +{ + //интерфейс, отвечающий за продукт + public interface ISecureModel : IId + { + //наименование изделия + string SecureName { get; } + + //цена изделия + double Price { get; } + + //словарь, хранящий пары кол-во + компонент и его цена + Dictionary SecureSensors { get; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/Models/ISensorsModel.cs b/SecuritySystem/SecuritySystemDataModels/Models/ISensorsModel.cs new file mode 100644 index 0000000..4cb02f5 --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/Models/ISensorsModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDataModels.Models +{ + //интерфейс, отвечающий за компоненты + public interface ISensorModel : IId + { + //название составляющей (изделие состоит из составляющих) + string SensorName { get; } + + //цена составляющей + double Cost { get; } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemDataModels/SecuritySystemDataModels.csproj b/SecuritySystem/SecuritySystemDataModels/SecuritySystemDataModels.csproj new file mode 100644 index 0000000..c59fb31 --- /dev/null +++ b/SecuritySystem/SecuritySystemDataModels/SecuritySystemDataModels.csproj @@ -0,0 +1,16 @@ + + + + net6.0 + enable + enable + + + + + + + + + + diff --git a/SecuritySystem/SecuritySystemListImplement/DataListSingleton.cs b/SecuritySystem/SecuritySystemListImplement/DataListSingleton.cs new file mode 100644 index 0000000..2c8fe5c --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/DataListSingleton.cs @@ -0,0 +1,41 @@ +using SecuritySystemListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement +{ + //класс для списков, в которых будет храниться информация при работе приложения + public class DataListSingleton + { + private static DataListSingleton? _instance; + + //список для хранения заготовок + public List Sensors { get; set; } + + //список для хранения изделий + public List Secures { get; set; } + + //список для хранения заказов + public List Orders { get; set; } + + public DataListSingleton() + { + Sensors = new List(); + Secures = new List(); + Orders = new List(); + } + + public static DataListSingleton GetInstance() + { + if(_instance == null) + { + _instance = new DataListSingleton(); + } + + return _instance; + } + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemListImplement/Implements/OrderStorage.cs b/SecuritySystem/SecuritySystemListImplement/Implements/OrderStorage.cs new file mode 100644 index 0000000..7a486d1 --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Implements/OrderStorage.cs @@ -0,0 +1,155 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Implements +{ + //класс, реализующий интерфейс хранилища заказов + public class OrderStorage : IOrderStorage + { + //поле для работы со списком заказов + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка заготовок + public List GetFullList() + { + var result = new List(); + + foreach (var order in _source.Orders) + { + result.Add(GetViewModel(order)); + } + + return result; + } + + //получение отфильтрованного списка заказов + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + + if (!model.Id.HasValue) + { + return result; + } + + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + result.Add(GetViewModel(order)); + } + } + + return result; + } + + //получение элемента из списка заказов + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + foreach (var order in _source.Orders) + { + if (model.Id.HasValue && order.Id == model.Id) + { + return GetViewModel(order); + } + } + + return null; + } + + //метод для записи названия изделия на форме с заказами + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; + + foreach (var secures in _source.Secures) + { + if (secures.Id == order.SecureId) + { + viewModel.SecureName = secures.SecureName; + + break; + } + } + + return viewModel; + } + + //при создании заказа определяем для него новый id: ищем max id и прибавляем к нему 1 + 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 GetViewModel(newOrder); + } + + //обновление заказа + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + + return GetViewModel(order); + } + } + + return null; + } + + //удаление заказа + public OrderViewModel? Delete(OrderBindingModel model) + { + for (int i = 0; i < _source.Orders.Count; ++i) + { + if (_source.Orders[i].Id == model.Id) + { + var element = _source.Orders[i]; + _source.Orders.RemoveAt(i); + + return GetViewModel(element); + } + } + + return null; + } + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/Implements/SecureStorage.cs b/SecuritySystem/SecuritySystemListImplement/Implements/SecureStorage.cs new file mode 100644 index 0000000..0b6c5c2 --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Implements/SecureStorage.cs @@ -0,0 +1,138 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Implements +{ + //класс, реализующий интерфейс хранилища изделий + public class SecureStorage : ISecureStorage + { + //поле для работы со списком изделий + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public SecureStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка изделий + public List GetFullList() + { + var result = new List(); + + foreach (var secure in _source.Secures) + { + result.Add(secure.GetViewModel); + } + + return result; + } + + //получение отфильтрованного списка изделий + public List GetFilteredList(SecureSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.SecureName)) + { + return result; + } + + foreach (var secure in _source.Secures) + { + if (secure.SecureName.Contains(model.SecureName)) + { + result.Add(secure.GetViewModel); + } + } + + return result; + } + + //получение элемента из списка изделий + public SecureViewModel? GetElement(SecureSearchModel model) + { + if (string.IsNullOrEmpty(model.SecureName) && !model.Id.HasValue) + { + return null; + } + + foreach (var secure in _source.Secures) + { + if ((!string.IsNullOrEmpty(model.SecureName) && secure.SecureName == model.SecureName) || + (model.Id.HasValue && secure.Id == model.Id)) + { + return secure.GetViewModel; + } + } + + return null; + } + + //при создании изделия определяем для него новый id: ищем max id и прибавлляем к нему 1 + public SecureViewModel? Insert(SecureBindingModel model) + { + model.Id = 1; + + foreach (var secure in _source.Secures) + { + if (model.Id <= secure.Id) + { + model.Id = secure.Id + 1; + } + } + + var newSecure = Secure.Create(model); + + if (newSecure == null) + { + return null; + } + + _source.Secures.Add(newSecure); + + return newSecure.GetViewModel; + } + + //обновление изделия + public SecureViewModel? Update(SecureBindingModel model) + { + foreach (var secure in _source.Secures) + { + if (secure.Id == model.Id) + { + secure.Update(model); + + return secure.GetViewModel; + } + } + + return null; + } + + //удаление изделия + public SecureViewModel? Delete(SecureBindingModel model) + { + for (int i = 0; i < _source.Secures.Count; ++i) + { + if (_source.Secures[i].Id == model.Id) + { + var element = _source.Secures[i]; + _source.Secures.RemoveAt(i); + + return element.GetViewModel; + } + } + + return null; + } + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/Implements/SensorsStorage.cs b/SecuritySystem/SecuritySystemListImplement/Implements/SensorsStorage.cs new file mode 100644 index 0000000..68a1a2a --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Implements/SensorsStorage.cs @@ -0,0 +1,138 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Implements +{ + //класс, реализующий интерфейс хранилища заготовок + public class SensorStorage : ISensorStorage + { + //поле для работы со списком заготовок + private readonly DataListSingleton _source; + + //получение в конструкторе объекта DataListSingleton + public SensorStorage() + { + _source = DataListSingleton.GetInstance(); + } + + //получение полного списка заготовок + public List GetFullList() + { + var result = new List(); + + foreach (var sensor in _source.Sensors) + { + result.Add(sensor.GetViewModel); + } + + return result; + } + + //получение отфильтрованного списка заготовок + public List GetFilteredList(SensorSearchModel model) + { + var result = new List(); + + if (string.IsNullOrEmpty(model.SensorName)) + { + return result; + } + + foreach (var sensor in _source.Sensors) + { + if (sensor.SensorName.Contains(model.SensorName)) + { + result.Add(sensor.GetViewModel); + } + } + + return result; + } + + //получение элемента из списка заготовок + public SensorViewModel? GetElement(SensorSearchModel model) + { + if (string.IsNullOrEmpty(model.SensorName) && !model.Id.HasValue) + { + return null; + } + + foreach (var sensor in _source.Sensors) + { + if ((!string.IsNullOrEmpty(model.SensorName) && sensor.SensorName == model.SensorName) || + (model.Id.HasValue && sensor.Id == model.Id)) + { + return sensor.GetViewModel; + } + } + + return null; + } + + //при создании заготовки определяем для него новый id: ищем max id и прибавляем к нему 1 + public SensorViewModel? Insert(SensorBindingModel model) + { + model.Id = 1; + + foreach (var sensor in _source.Sensors) + { + if (model.Id <= sensor.Id) + { + model.Id = sensor.Id + 1; + } + } + + var newSensor = Sensor.Create(model); + + if (newSensor == null) + { + return null; + } + + _source.Sensors.Add(newSensor); + + return newSensor.GetViewModel; + } + + //обновление заготовки + public SensorViewModel? Update(SensorBindingModel model) + { + foreach (var sensor in _source.Sensors) + { + if (sensor.Id == model.Id) + { + sensor.Update(model); + + return sensor.GetViewModel; + } + } + + return null; + } + + //удаление заготовки + public SensorViewModel? Delete(SensorBindingModel model) + { + for (int i = 0; i < _source.Sensors.Count; ++i) + { + if (_source.Sensors[i].Id == model.Id) + { + var element = _source.Sensors[i]; + _source.Sensors.RemoveAt(i); + + return element.GetViewModel; + } + } + + return null; + } + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Order.cs b/SecuritySystem/SecuritySystemListImplement/Models/Order.cs new file mode 100644 index 0000000..14c2447 --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Models/Order.cs @@ -0,0 +1,74 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.PortableExecutable; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Models +{ + //класс, реализующий интерфейс модели заказа + public class Order : IOrderModel + { + //методы set сделали приватными, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } + + public int SecureId { get; private set; } + + public int Count { get; private set; } + + public double Sum { get; private set; } + + public OrderStatus Status { get; private set; } + + public DateTime DateCreate { get; private set; } = DateTime.Now; + + public DateTime? DateImplement { get; private set; } + + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Order() + { + Id = model.Id, + SecureId = model.SecureId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } + + //метод изменения существующего объекта + public void Update(OrderBindingModel? model) + { + if(model == null) + { + return; + } + Status = model.Status; + DateImplement = model.DateImplement; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public OrderViewModel GetViewModel => new() + { + Id = Id, + SecureId = SecureId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs b/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs new file mode 100644 index 0000000..1694c14 --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs @@ -0,0 +1,63 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Models +{ + //класс реализующий интерфейс модели изделия + public class Secure : ISecureModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } + + public string SecureName { get; private set; } = string.Empty; + + public double Price { get; private set; } + + public Dictionary SecureSensors { get; private set; } = new Dictionary(); + + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Secure? Create(SecureBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Secure() + { + Id = model.Id, + SecureName = model.SecureName, + Price = model.Price, + SecureSensors = model.SecureSensors + }; + } + + //метод изменения существующего объекта + public void Update(SecureBindingModel? model) + { + if (model == null) + { + return; + } + + SecureName = model.SecureName; + Price = model.Price; + SecureSensors = model.SecureSensors; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public SecureViewModel GetViewModel => new() + { + Id = Id, + SecureName = SecureName, + Price = Price, + SecureSensors = SecureSensors + }; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs b/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs new file mode 100644 index 0000000..29735cf --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs @@ -0,0 +1,58 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Models +{ + //реализация интерфейса модели заготовки + public class Sensor : ISensorModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } + + public string SensorName { get; private set; } = string.Empty; + + public double Cost { get; private set; } + + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Sensor? Create(SensorBindingModel? model) + { + if(model == null) + { + return null; + } + + return new Sensor() + { + Id = model.Id, + SensorName = model.SensorName, + Cost = model.Cost + }; + } + + //метод изменения существующего объекта + public void Update(SensorBindingModel? model) + { + if(model == null) + { + return; + } + + SensorName = model.SensorName; + Cost = model.Cost; + } + + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public SensorViewModel GetViewModel => new() + { + Id = Id, + SensorName = SensorName, + Cost = Cost + }; + } +} \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj b/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj new file mode 100644 index 0000000..618674f --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj @@ -0,0 +1,21 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + +