This commit is contained in:
spacyboy 2024-05-08 08:37:10 +04:00
parent 8044ed7232
commit 74c8fd1bae
45 changed files with 2440 additions and 246 deletions

View File

@ -0,0 +1,168 @@
namespace SecuritySystem
{
partial class FormImplementer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonCancel = new Button();
buttonSave = new Button();
textBoxQualification = new TextBox();
textBoxWorkExperience = new TextBox();
textBoxPassword = new TextBox();
textBoxImplementerFIO = new TextBox();
labelQualification = new Label();
labelWorkExperience = new Label();
labelPassword = new Label();
labelFIO = new Label();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(451, 131);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 19;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(351, 131);
buttonSave.Margin = new Padding(3, 2, 3, 2);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(82, 22);
buttonSave.TabIndex = 18;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// textBoxQualification
//
textBoxQualification.Location = new Point(400, 97);
textBoxQualification.Margin = new Padding(3, 2, 3, 2);
textBoxQualification.Name = "textBoxQualification";
textBoxQualification.Size = new Size(134, 23);
textBoxQualification.TabIndex = 17;
//
// textBoxWorkExperience
//
textBoxWorkExperience.Location = new Point(152, 97);
textBoxWorkExperience.Margin = new Padding(3, 2, 3, 2);
textBoxWorkExperience.Name = "textBoxWorkExperience";
textBoxWorkExperience.Size = new Size(111, 23);
textBoxWorkExperience.TabIndex = 16;
//
// textBoxPassword
//
textBoxPassword.Location = new Point(152, 54);
textBoxPassword.Margin = new Padding(3, 2, 3, 2);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.Size = new Size(382, 23);
textBoxPassword.TabIndex = 15;
//
// textBoxImplementerFIO
//
textBoxImplementerFIO.Location = new Point(152, 15);
textBoxImplementerFIO.Margin = new Padding(3, 2, 3, 2);
textBoxImplementerFIO.Name = "textBoxImplementerFIO";
textBoxImplementerFIO.Size = new Size(382, 23);
textBoxImplementerFIO.TabIndex = 14;
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(291, 99);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(91, 15);
labelQualification.TabIndex = 13;
labelQualification.Text = "Квалификация:";
//
// labelWorkExperience
//
labelWorkExperience.AutoSize = true;
labelWorkExperience.Location = new Point(45, 99);
labelWorkExperience.Name = "labelWorkExperience";
labelWorkExperience.Size = new Size(82, 15);
labelWorkExperience.TabIndex = 12;
labelWorkExperience.Text = "Стаж работы:";
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(45, 56);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(52, 15);
labelPassword.TabIndex = 11;
labelPassword.Text = "Пароль:";
//
// labelFIO
//
labelFIO.AutoSize = true;
labelFIO.Location = new Point(45, 17);
labelFIO.Name = "labelFIO";
labelFIO.Size = new Size(37, 15);
labelFIO.TabIndex = 10;
labelFIO.Text = "ФИО:";
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(579, 168);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxQualification);
Controls.Add(textBoxWorkExperience);
Controls.Add(textBoxPassword);
Controls.Add(textBoxImplementerFIO);
Controls.Add(labelQualification);
Controls.Add(labelWorkExperience);
Controls.Add(labelPassword);
Controls.Add(labelFIO);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxQualification;
private TextBox textBoxWorkExperience;
private TextBox textBoxPassword;
private TextBox textBoxImplementerFIO;
private Label labelQualification;
private Label labelWorkExperience;
private Label labelPassword;
private Label labelFIO;
}
}

View File

@ -0,0 +1,138 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SecuritySystem
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
//конструктор
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
//при загрузке формы
private void FormImplementer_Load(object sender, EventArgs e)
{
//проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value });
if (view != null)
{
textBoxImplementerFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.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(textBoxImplementerFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля с паролем
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля со стажем
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля с квалификацией
if (string.IsNullOrEmpty(textBoxQualification.Text))
{
MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxImplementerFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt16(textBoxWorkExperience.Text),
Qualification = Convert.ToInt16(textBoxQualification.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранеии. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,119 @@
namespace SecuritySystem
{
partial class FormImplementers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonUpdate = new Button();
buttonDelete = new Button();
buttonChange = new Button();
buttonCreate = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonUpdate
//
buttonUpdate.Location = new Point(710, 164);
buttonUpdate.Margin = new Padding(3, 2, 3, 2);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(140, 22);
buttonUpdate.TabIndex = 9;
buttonUpdate.Text = "Обновить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(710, 115);
buttonDelete.Margin = new Padding(3, 2, 3, 2);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(140, 22);
buttonDelete.TabIndex = 8;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonChange
//
buttonChange.Location = new Point(710, 68);
buttonChange.Margin = new Padding(3, 2, 3, 2);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(140, 22);
buttonChange.TabIndex = 7;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonCreate
//
buttonCreate.Location = new Point(710, 16);
buttonCreate.Margin = new Padding(3, 2, 3, 2);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(140, 22);
buttonCreate.TabIndex = 6;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(16, 9);
dataGridView.Margin = new Padding(3, 2, 3, 2);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(672, 320);
dataGridView.TabIndex = 5;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(867, 338);
Controls.Add(buttonUpdate);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonCreate);
Controls.Add(dataGridView);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonChange;
private Button buttonCreate;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,127 @@
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 FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormSensors> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementers_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["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonChange_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer 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 ImplementerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

View File

@ -28,11 +28,6 @@
/// </summary>
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();
@ -44,65 +39,16 @@
ordersToolStripMenuItem = new ToolStripMenuItem();
workWithClientsToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
implementerToolStripMenuItem = new ToolStripMenuItem();
startingWorkToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button();
buttonRef = new Button();
buttonIssuedOrder = new Button();
((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;
@ -117,7 +63,7 @@
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
@ -184,10 +130,64 @@
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(180, 22);
clientsToolStripMenuItem.Size = new Size(122, 22);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// workWithImplementerToolStripMenuItem
//
workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
workWithImplementerToolStripMenuItem.Size = new Size(157, 20);
workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
//
// implementerToolStripMenuItem
//
implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
implementerToolStripMenuItem.Size = new Size(180, 22);
implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click;
//
// startingWorkToolStripMenuItem
//
startingWorkToolStripMenuItem.Name = "startingWorkToolStripMenuItem";
startingWorkToolStripMenuItem.Size = new Size(92, 20);
startingWorkToolStripMenuItem.Text = "Запуск работ";
startingWorkToolStripMenuItem.Click += StartingWorkToolStripMenuItem_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;
//
// buttonRef
//
buttonRef.Location = new Point(887, 166);
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, 111);
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;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -195,8 +195,6 @@
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);
@ -211,12 +209,6 @@
}
#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;
@ -228,5 +220,11 @@
private ToolStripMenuItem ordersToolStripMenuItem;
private ToolStripMenuItem workWithClientsToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem workWithImplementerToolStripMenuItem;
private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem startingWorkToolStripMenuItem;
private Button buttonCreateOrder;
private Button buttonRef;
private Button buttonIssuedOrder;
}
}

View File

@ -23,13 +23,16 @@ namespace SecuritySystem
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
@ -49,9 +52,11 @@ namespace SecuritySystem
{
dataGridView.DataSource = list;
dataGridView.Columns["SecureId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["SecureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà çàêàçîâ");
@ -95,64 +100,6 @@ namespace SecuritySystem
}
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)
@ -233,5 +180,22 @@ namespace SecuritySystem
form.ShowDialog();
}
}
private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Ïðîöåññ çàïóùåí", "Ñîîáùåíèå", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
}
}

View File

@ -43,12 +43,15 @@ namespace SecuritySystem
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISecureStorage, SecureStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<ISensorLogic, SensorLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISecureLogic, SecureLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -64,6 +67,8 @@ namespace SecuritySystem
services.AddTransient<FormReportSecureSensors>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
}
}
}

View File

@ -141,7 +141,7 @@ namespace SecuritySystemBusinessLogic.BusinessLogic
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
_logger.LogInformation("Sensor. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}",
_logger.LogInformation("Client. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}",
model.ClientFIO, model.Email, model.Password, model.Id);
//для проверка на наличие такого же аккаунта

View File

@ -0,0 +1,167 @@
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 ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model?.Id);
var element = _implementerStorage.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(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
//проверка на наличие ФИО
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO));
}
//проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
//проверка на наличие квалификации
if (model.Qualification <= 0)
{
throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification));
}
//проверка на наличие квалификации
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Указан некоректный стаж работы", nameof(model.WorkExperience));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +
"Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}",
model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id);
//для проверка на наличие такого же аккаунта
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
//если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким именем уже есть");
}
}
}
}

View File

@ -46,6 +46,29 @@ namespace SecuritySystemBusinessLogic.BusinessLogic
return list;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{Id}", model?.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
//создание чека
public bool CreateOrder(OrderBindingModel model)
{
@ -150,6 +173,12 @@ namespace SecuritySystemBusinessLogic.BusinessLogic
model.Status = newOrderStatus;
//не забываем положить id работника
if (viewModel.ImplementerId.HasValue)
{
model.ImplementerId = viewModel.ImplementerId;
}
//проверка на выдачу
if (model.Status == OrderStatus.Выдан)
{

View File

@ -0,0 +1,161 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
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 WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
// Иммитация работы исполнителя
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id,
});
// отдыхаем
Thread.Sleep(implementer.Qualification);
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
//Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification);
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

View File

@ -0,0 +1,22 @@
using SecuritySystemDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemContracts.BindingModels
{
public class ImplementerBindingModel : IImplementerModel
{
public int Id { get; set; }
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; }
public int Qualification { get; set; }
}
}

View File

@ -15,6 +15,8 @@ namespace SecuritySystemContracts.BindingModels
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int SecureId { get; set; }
public int Count { get; set; }

View File

@ -0,0 +1,24 @@
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 IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

View File

@ -14,6 +14,8 @@ namespace SecuritySystemContracts.BusinessLogicsContracts
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemContracts.BusinessLogicsContracts
{
//интерфейс для класса, имитирующего работу
public interface IWorkProcess
{
// Запуск работ
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
public int? WorkExperience { get; set; }
public int? Qualification { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System;
using SecuritySystemDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -15,9 +16,14 @@ namespace SecuritySystemContracts.SearchModels
//для поиска по клиенту
public int? ClientId { get; set; }
//для поиска по исполнителю
public int? ImplementerId { get; set; }
//два поля для возможности производить выборку
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public OrderStatus? Status { get; set; }
}
}

View File

@ -0,0 +1,26 @@
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 IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

View File

@ -0,0 +1,27 @@
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 ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
public int Qualification { get; set; }
}
}

View File

@ -17,6 +17,8 @@ namespace SecuritySystemContracts.ViewModels
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int SecureId { get; set; }
[DisplayName("ФИО клиента")]
@ -25,6 +27,9 @@ namespace SecuritySystemContracts.ViewModels
[DisplayName("Изделие")]
public string SecureName { get; set; } = string.Empty;
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }

View File

@ -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 IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -16,6 +16,9 @@ namespace SecuritySystemDataModels.Models
//id клиента
int ClientId { get; }
//id исполнителя
int? ImplementerId { get; }
//кол-во продуктов
int Count { get; }

View File

@ -0,0 +1,128 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public List<ImplementerViewModel> GetFullList()
{
using var context = new SecuritySystemDatabase();
return context.Implementers
.Include(x => x.Orders)
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var context = new SecuritySystemDatabase();
return context.Implementers
.Include(x => x.Orders)
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new SecuritySystemDatabase();
if (model.Id.HasValue)
{
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
else if (!string.IsNullOrEmpty(model.ImplementerFIO) && !string.IsNullOrEmpty(model.Password))
{
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => (x.ImplementerFIO == model.ImplementerFIO && x.Password == model.Password))
?.GetViewModel;
}
return new();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new SecuritySystemDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == newImplementer.Id)
?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new SecuritySystemDatabase();
var order = context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new SecuritySystemDatabase();
var element = context.Implementers
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
// для отображения КОРРЕКТНОЙ ViewModel-и
var deletedElement = context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
context.Implementers.Remove(element);
context.SaveChanges();
return deletedElement;
}
return null;
}
}
}

View File

@ -51,7 +51,10 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
.Include(x => x.Implementer)
.FirstOrDefault(x => (model.Status == null || model.Status != null && model.Status == x.Status) &&
model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId ||
model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
@ -64,6 +67,7 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
@ -73,6 +77,7 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
@ -82,12 +87,29 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ImplementerId.HasValue)
{
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => model.Status == x.Status)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFullList()
@ -97,6 +119,7 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
@ -125,9 +148,11 @@ namespace SecuritySystemDatabaseImplement.Implements
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SecuritySystemDatabase();
var order = context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
@ -141,6 +166,7 @@ namespace SecuritySystemDatabaseImplement.Implements
return context.Orders
.Include(x => x.Secure)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}

View File

@ -12,7 +12,7 @@ using SecuritySystemDatabaseImplement;
namespace SecuritySystemDatabaseImplement.Migrations
{
[DbContext(typeof(SecuritySystemDatabase))]
[Migration("20240508035208_Init")]
[Migration("20240508043144_Init")]
partial class Init
{
/// <inheritdoc />
@ -50,6 +50,33 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.ToTable("Clients");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -70,6 +97,9 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SecureId")
.HasColumnType("int");
@ -83,6 +113,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SecureId");
b.ToTable("Orders");
@ -162,6 +194,10 @@ namespace SecuritySystemDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure")
.WithMany("Orders")
.HasForeignKey("SecureId")
@ -170,6 +206,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Secure");
});
@ -197,6 +235,11 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b =>
{
b.Navigation("Orders");

View File

@ -26,6 +26,22 @@ namespace SecuritySystemDatabaseImplement.Migrations
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Secures",
columns: table => new
@ -62,6 +78,7 @@ namespace SecuritySystemDatabaseImplement.Migrations
.Annotation("SqlServer:Identity", "1, 1"),
SecureId = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
@ -77,6 +94,11 @@ namespace SecuritySystemDatabaseImplement.Migrations
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Secures_SecureId",
column: x => x.SecureId,
@ -117,6 +139,11 @@ namespace SecuritySystemDatabaseImplement.Migrations
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_SecureId",
table: "Orders",
@ -145,6 +172,9 @@ namespace SecuritySystemDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Secures");

View File

@ -47,6 +47,33 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.ToTable("Clients");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -67,6 +94,9 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SecureId")
.HasColumnType("int");
@ -80,6 +110,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SecureId");
b.ToTable("Orders");
@ -159,6 +191,10 @@ namespace SecuritySystemDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure")
.WithMany("Orders")
.HasForeignKey("SecureId")
@ -167,6 +203,8 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Secure");
});
@ -194,6 +232,11 @@ namespace SecuritySystemDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b =>
{
b.Navigation("Orders");

View File

@ -0,0 +1,86 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; set; }
[Required]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public int WorkExperience { get; set; }
[Required]
public int Qualification { get; set; }
//для реализации связи один ко многим с заказами
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
public static Implementer Create(ImplementerViewModel model)
{
return new Implementer
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Id = model.Id;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
ImplementerFIO = ImplementerFIO,
Qualification = Qualification,
WorkExperience = WorkExperience
};
}
}

View File

@ -22,6 +22,8 @@ namespace SecuritySystemDatabaseImplement.Models
[Required]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[Required]
public int Count { get; private set; }
@ -42,6 +44,9 @@ namespace SecuritySystemDatabaseImplement.Models
//для передачи имени клиента
public virtual Client Client { get; set; }
//для передачи имени исполнителя
public virtual Implementer? Implementer { get; set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
@ -54,6 +59,7 @@ namespace SecuritySystemDatabaseImplement.Models
Id = model.Id,
SecureId = model.SecureId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -69,6 +75,7 @@ namespace SecuritySystemDatabaseImplement.Models
return;
}
ImplementerId = model.ImplementerId;
Status = model.Status;
DateImplement = model.DateImplement;
}
@ -78,13 +85,15 @@ namespace SecuritySystemDatabaseImplement.Models
Id = Id,
SecureId = SecureId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
SecureName = Secure.SecureName,
ClientFIO = Client.ClientFIO
ClientFIO = Client.ClientFIO,
ImplementerFIO = Implementer?.ImplementerFIO
};
}
}

View File

@ -31,5 +31,7 @@ namespace SecuritySystemDatabaseImplement
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { get; set; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -20,6 +20,8 @@ namespace SecuritySystemFileImplement
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Sensor> Sensors { get; private set; }
public List<Order> Orders { get; private set; }
@ -28,6 +30,8 @@ namespace SecuritySystemFileImplement
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -46,12 +50,15 @@ namespace SecuritySystemFileImplement
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Sensors = LoadData(SensorFileName, "Sensor", x => Sensor.Create(x)!)!;
Secures = LoadData(SecureFileName, "Secure", x => Secure.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)

View File

@ -0,0 +1,90 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
return source.Implementers.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1;
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
source.Implementers.Add(newImplementer);
source.SaveImplementers();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
source.SaveImplementers();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -48,6 +48,13 @@ namespace SecuritySystemFileImplement.Implements
.Select(x => GetViewModel(x))
.ToList();
}
else if (model.ImplementerId.HasValue)
{
return source.Orders
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => GetViewModel(x))
.ToList();
}
return new();
}
@ -62,7 +69,7 @@ namespace SecuritySystemFileImplement.Implements
return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
//для загрузки названий изделия в заказе
//для загрузки названий и имён в заказ
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
@ -71,6 +78,8 @@ namespace SecuritySystemFileImplement.Implements
var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId);
var implementer = source.Implementers.FirstOrDefault(x => x.Id == order.ImplementerId);
if (secure != null)
{
viewModel.SecureName = secure.SecureName;
@ -81,6 +90,11 @@ namespace SecuritySystemFileImplement.Implements
viewModel.ClientFIO = client.ClientFIO;
}
if (implementer != null)
{
viewModel.ImplementerFIO = implementer.ImplementerFIO;
}
return viewModel;
}

View File

@ -0,0 +1,90 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace SecuritySystemFileImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Implementer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Password = element.Element("Password")!.Value,
ImplementerFIO = element.Element("ImplementerFIO")!.Value,
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value)
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Id = model.Id;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
ImplementerFIO = ImplementerFIO,
Qualification = Qualification,
WorkExperience = WorkExperience
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("Password", Password),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("Qualification", Qualification),
new XElement("WorkExperience", WorkExperience));
}
}

View File

@ -19,6 +19,8 @@ namespace SecuritySystemFileImplement.Models
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int SecureId { get; private set; }
public int Count { get; private set; }
@ -43,6 +45,7 @@ namespace SecuritySystemFileImplement.Models
Id = model.Id,
ClientId = model.ClientId,
SecureId = model.SecureId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -61,7 +64,8 @@ namespace SecuritySystemFileImplement.Models
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientId = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Attribute("ImplementerId")!.Value),
SecureId = Convert.ToInt32(element.Element("SecureId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
@ -87,6 +91,7 @@ namespace SecuritySystemFileImplement.Models
{
Id = Id,
ClientId = ClientId,
ImplementerId = ImplementerId,
SecureId = SecureId,
Count = Count,
Sum = Sum,
@ -98,6 +103,7 @@ namespace SecuritySystemFileImplement.Models
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("ClientId", ClientId.ToString()),
new XElement("ImplementerId", ClientId.ToString()),
new XElement("SecureId", SecureId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),

View File

@ -24,12 +24,16 @@ namespace SecuritySystemListImplement
//список для хранения клиентов
public List<Client> Clients { get; set; }
//список для хранения исполнителей
public List<Implementer> Implementers { get; set; }
public DataListSingleton()
{
Sensors = new List<Sensor>();
Secures = new List<Secure>();
Orders = new List<Order>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()

View File

@ -0,0 +1,130 @@
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 ImplementerStorage : IImplementerStorage
{
//поле для работы со списком исполнителей
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return result;
}
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Contains(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
return result;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
foreach (var implementer in _source.Implementers)
{
if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) ||
(model.Id.HasValue && implementer.Id == model.Id))
{
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -100,7 +100,7 @@ namespace SecuritySystemListImplement.Implements
return null;
}
//метод для записи названия изделия на форме с заказами
//метод для передачи названий и имён на форму
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
@ -124,6 +124,16 @@ namespace SecuritySystemListImplement.Implements
}
}
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == order.ImplementerId)
{
viewModel.ImplementerFIO = implementer.ImplementerFIO;
break;
}
}
return viewModel;
}

View File

@ -0,0 +1,67 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SecuritySystemListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
//метод для создания объекта от класса-компонента на основе класса-BindingModel
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
//метод изменения существующего объекта
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification;
WorkExperience = model.WorkExperience;
}
//метод для создания объекта класса ViewModel на основе данных объекта класса-компонента
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
ImplementerFIO = ImplementerFIO,
Qualification = Qualification,
WorkExperience = WorkExperience
};
}
}

View File

@ -5,6 +5,7 @@ using SecuritySystemDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
@ -19,6 +20,8 @@ namespace SecuritySystemListImplement.Models
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int SecureId { get; private set; }
public int Count { get; private set; }
@ -43,6 +46,7 @@ namespace SecuritySystemListImplement.Models
Id = model.Id,
SecureId = model.SecureId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -69,6 +73,7 @@ namespace SecuritySystemListImplement.Models
Id = Id,
SecureId = SecureId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,

View File

@ -0,0 +1,112 @@
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace SecuritySystemRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{
_logger = logger;
_order = order;
_logic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _order.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_order.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_order.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id);
throw;
}
}
}
}

View File

@ -14,10 +14,12 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<ISecureStorage, SecureStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ISecureLogic, SecureLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddControllers();