diff --git a/.gitignore b/.gitignore index ca1c7a3..ab6315f 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,7 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +# dll файлы +*.dll + +/SecuritySystem/ImplementationExtensions \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/DataGridViewExtension.cs b/SecuritySystem/SecuritySystem/DataGridViewExtension.cs new file mode 100644 index 0000000..ff2b042 --- /dev/null +++ b/SecuritySystem/SecuritySystem/DataGridViewExtension.cs @@ -0,0 +1,63 @@ +using SecuritySystemContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystem +{ + public static class DataGridViewExtension + { + public static void FillandConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + + grid.DataSource = data; + + //получаем тип + var type = typeof(T); + + //получаем свойства + var properties = type.GetProperties(); + + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем { column.Name }"); + } + + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства { property.Name }"); + } + + // ищем нужный нам атрибут + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), + columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } + +} diff --git a/SecuritySystem/SecuritySystem/FormClients.cs b/SecuritySystem/SecuritySystem/FormClients.cs index acc5a5b..d41113a 100644 --- a/SecuritySystem/SecuritySystem/FormClients.cs +++ b/SecuritySystem/SecuritySystem/FormClients.cs @@ -15,82 +15,73 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormClients : Form - { - private readonly ILogger _logger; + public partial class FormClients : Form + { + private readonly ILogger _logger; - private readonly IClientLogic _clientLogic; + private readonly IClientLogic _clientLogic; - public FormClients(ILogger logger, IClientLogic clientLogic) - { - InitializeComponent(); + public FormClients(ILogger logger, IClientLogic clientLogic) + { + InitializeComponent(); - _logger = logger; - _clientLogic = clientLogic; - } + _logger = logger; + _clientLogic = clientLogic; + } - private void FormClients_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormClients_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - _logger.LogInformation("Загрузка клиентов"); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_clientLogic.ReadList(null)); + _logger.LogInformation("Загрузка клиентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки клиентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - try - { - var list = _clientLogic.ReadList(null); + 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); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + _logger.LogInformation("Удаление клиента"); - _logger.LogInformation("Успешная загрузка клиентов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки клиентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + try + { + if (!_clientLogic.Delete(new ClientBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - 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); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } - _logger.LogInformation("Удаление клиента"); - - try - { - if (!_clientLogic.Delete(new ClientBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } - - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/SecuritySystem/SecuritySystem/FormImplementer.cs b/SecuritySystem/SecuritySystem/FormImplementer.cs index e024d14..9efc689 100644 --- a/SecuritySystem/SecuritySystem/FormImplementer.cs +++ b/SecuritySystem/SecuritySystem/FormImplementer.cs @@ -14,125 +14,125 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormImplementer : Form - { - private readonly ILogger _logger; + public partial class FormImplementer : Form + { + private readonly ILogger _logger; - private readonly IImplementerLogic _logic; + private readonly IImplementerLogic _logic; - private int? _id; + private int? _id; - public int Id { set { _id = value; } } + public int Id { set { _id = value; } } - //конструктор - public FormImplementer(ILogger logger, IImplementerLogic logic) - { - InitializeComponent(); + //конструктор + public FormImplementer(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); - _logger = logger; - _logic = logic; - } + _logger = logger; + _logic = logic; + } - //при загрузке формы - private void FormImplementer_Load(object sender, EventArgs e) - { - //проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран - if (_id.HasValue) - { - try - { - _logger.LogInformation("Получение исполнителя"); + //при загрузке формы + private void FormImplementer_Load(object sender, EventArgs e) + { + //проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); - var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value }); + 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, "Ошибка получения исполнителя"); + 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); - } - } - } + 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); + private void ButtonSave_Click(object sender, EventArgs e) + { + //проверка на заполнение поля с ФИО исполнителя + if (string.IsNullOrEmpty(textBoxImplementerFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - //проверка на заполнение поля с паролем - if (string.IsNullOrEmpty(textBoxPassword.Text)) - { - MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + //проверка на заполнение поля с паролем + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - //проверка на заполнение поля со стажем - if (string.IsNullOrEmpty(textBoxWorkExperience.Text)) - { - MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + //проверка на заполнение поля со стажем + if (string.IsNullOrEmpty(textBoxWorkExperience.Text)) + { + MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - //проверка на заполнение поля с квалификацией - if (string.IsNullOrEmpty(textBoxQualification.Text)) - { - MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + //проверка на заполнение поля с квалификацией + if (string.IsNullOrEmpty(textBoxQualification.Text)) + { + MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - _logger.LogInformation("Сохранение исполнителя"); + _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) - }; + 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); + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранеии. Дополнительная информация в логах."); - } + if (!operationResult) + { + throw new Exception("Ошибка при сохранеии. Дополнительная информация в логах."); + } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения исполнителя"); + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ButtonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } - } + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } } diff --git a/SecuritySystem/SecuritySystem/FormImplementers.cs b/SecuritySystem/SecuritySystem/FormImplementers.cs index 7f68331..4d375ac 100644 --- a/SecuritySystem/SecuritySystem/FormImplementers.cs +++ b/SecuritySystem/SecuritySystem/FormImplementers.cs @@ -1,5 +1,7 @@ -using SecuritySystemContracts.BindingModels; +using SecuritySystemBusinessLogic.BusinessLogic; +using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,115 +15,101 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormImplementers : Form - { - private readonly ILogger _logger; + public partial class FormImplementers : Form + { + private readonly ILogger _logger; - private readonly IImplementerLogic _logic; + private readonly IImplementerLogic _logic; - public FormImplementers(ILogger logger, IImplementerLogic logic) - { - InitializeComponent(); + public FormImplementers(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); - _logger = logger; - _logic = logic; - } + _logger = logger; + _logic = logic; + } - private void FormImplementers_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_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, "Ошибка загрузки исполнителей"); - _logger.LogInformation("Загрузка исполнителей"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void ButtonCreate_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonCreate_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } - 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 form = DependencyManager.Instance.Resolve(); - private void ButtonChange_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } - 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); - 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("Удаление исполнителя"); - _logger.LogInformation("Удаление исполнителя"); + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - 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); + } + } + } + } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления исполнителя"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonUpdate_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonUpdate_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/SecuritySystem/SecuritySystem/FormMails.cs b/SecuritySystem/SecuritySystem/FormMails.cs index cee925e..6d59405 100644 --- a/SecuritySystem/SecuritySystem/FormMails.cs +++ b/SecuritySystem/SecuritySystem/FormMails.cs @@ -13,48 +13,40 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormMails : Form - { - private readonly ILogger _logger; + public partial class FormMails : Form + { + private readonly ILogger _logger; - private readonly IMessageInfoLogic _messageLogic; + private readonly IMessageInfoLogic _messageLogic; - public FormMails(ILogger logger, IMessageInfoLogic messageLogic) - { - InitializeComponent(); + public FormMails(ILogger logger, IMessageInfoLogic messageLogic) + { + InitializeComponent(); - _logger = logger; - _messageLogic = messageLogic; - } + _logger = logger; + _messageLogic = messageLogic; + } - private void FormMails_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - _logger.LogInformation("Загрузка писем"); + private void LoadData() + { + _logger.LogInformation("Загрузка писем"); - try - { - var list = _messageLogic.ReadList(null); + try + { + dataGridView.FillandConfigGrid(_messageLogic.ReadList(null)); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - - _logger.LogInformation("Успешная загрузка писем"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки писем"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + _logger.LogInformation("Успешная загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/SecuritySystem/SecuritySystem/FormMain.Designer.cs b/SecuritySystem/SecuritySystem/FormMain.Designer.cs index 33998ed..4c3c3ad 100644 --- a/SecuritySystem/SecuritySystem/FormMain.Designer.cs +++ b/SecuritySystem/SecuritySystem/FormMain.Designer.cs @@ -33,6 +33,7 @@ toolStripMenuItem = new ToolStripMenuItem(); SensorToolStripMenuItem = new ToolStripMenuItem(); SecureToolStripMenuItem = new ToolStripMenuItem(); + письмаToolStripMenuItem = new ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem(); sensorsToolStripMenuItem = new ToolStripMenuItem(); sensorSecuresToolStripMenuItem = new ToolStripMenuItem(); @@ -45,7 +46,7 @@ buttonCreateOrder = new Button(); buttonRef = new Button(); buttonIssuedOrder = new Button(); - письмаToolStripMenuItem = new ToolStripMenuItem(); + createBackUpToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout(); SuspendLayout(); @@ -64,7 +65,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem, createBackUpToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(5, 2, 0, 2); @@ -82,17 +83,24 @@ // SensorToolStripMenuItem // SensorToolStripMenuItem.Name = "SensorToolStripMenuItem"; - SensorToolStripMenuItem.Size = new Size(180, 22); + SensorToolStripMenuItem.Size = new Size(130, 22); SensorToolStripMenuItem.Text = "Заготовки"; SensorToolStripMenuItem.Click += SensorToolStripMenuItem_Click; // // SecureToolStripMenuItem // SecureToolStripMenuItem.Name = "SecureToolStripMenuItem"; - SecureToolStripMenuItem.Size = new Size(180, 22); + SecureToolStripMenuItem.Size = new Size(130, 22); SecureToolStripMenuItem.Text = "Изделия"; SecureToolStripMenuItem.Click += SecureToolStripMenuItem_Click; // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(130, 22); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += MailsToolStripMenuItem_Click; + // // reportsToolStripMenuItem // reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { sensorsToolStripMenuItem, sensorSecuresToolStripMenuItem, ordersToolStripMenuItem }); @@ -189,12 +197,12 @@ buttonIssuedOrder.UseVisualStyleBackColor = true; buttonIssuedOrder.Click += ButtonIssuedOrder_Click; // - // письмаToolStripMenuItem + // createBackUpToolStripMenuItem // - письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; - письмаToolStripMenuItem.Size = new Size(180, 22); - письмаToolStripMenuItem.Text = "Письма"; - письмаToolStripMenuItem.Click += MailsToolStripMenuItem_Click; + createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem"; + createBackUpToolStripMenuItem.Size = new Size(97, 20); + createBackUpToolStripMenuItem.Text = "Создать бекап"; + createBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click; // // FormMain // @@ -235,5 +243,6 @@ private Button buttonRef; private Button buttonIssuedOrder; private ToolStripMenuItem письмаToolStripMenuItem; + private ToolStripMenuItem createBackUpToolStripMenuItem; } } \ No newline at end of file diff --git a/SecuritySystem/SecuritySystem/FormMain.cs b/SecuritySystem/SecuritySystem/FormMain.cs index 89ab48a..de5e31c 100644 --- a/SecuritySystem/SecuritySystem/FormMain.cs +++ b/SecuritySystem/SecuritySystem/FormMain.cs @@ -1,6 +1,7 @@ using SecuritySystemBusinessLogic.BusinessLogic; using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using SecuritySystemDataModels.Enums; using Microsoft.Extensions.Logging; using System; @@ -25,7 +26,9 @@ namespace SecuritySystem private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + private readonly IBackUpLogic _backUpLogic; + + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); @@ -33,6 +36,7 @@ namespace SecuritySystem _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) @@ -46,18 +50,7 @@ namespace SecuritySystem try { - var list = _orderLogic.ReadList(null); - - if (list != null) - { - 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; - } + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation(" "); } @@ -70,34 +63,24 @@ namespace SecuritySystem private void SensorToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSensors)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormSensors form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void SecureToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormSecures)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormSecures form) - { - form.ShowDialog(); - } + 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(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private void ButtonIssuedOrder_Click(object sender, EventArgs e) @@ -153,58 +136,69 @@ namespace SecuritySystem private void SensorSecuresToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportSecureSensors)); + var form = DependencyManager.Instance.Resolve(); + + form.ShowDialog(); - if (service is FormReportSecureSensors form) - { - form.ShowDialog(); - } } private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormClients form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e) { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + _workProcess.DoWork(DependencyManager.Instance.Resolve()!, _orderLogic); MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormImplementers form) - { - form.ShowDialog(); - } + form.ShowDialog(); } private void MailsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + var form = DependencyManager.Instance.Resolve(); - if (service is FormMails form) + form.ShowDialog(); + } + + private void CreateBackUpToolStripMenuItem_Click(object sender, EventArgs e) + { + try { - form.ShowDialog(); + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + + MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/SecuritySystem/SecuritySystem/FormSecure.cs b/SecuritySystem/SecuritySystem/FormSecure.cs index 0d19bbb..66ef384 100644 --- a/SecuritySystem/SecuritySystem/FormSecure.cs +++ b/SecuritySystem/SecuritySystem/FormSecure.cs @@ -1,5 +1,6 @@ using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using SecuritySystemContracts.SearchModels; using SecuritySystemDataModels.Models; using Microsoft.Extensions.Logging; @@ -15,232 +16,226 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormSecure : Form - { - private readonly ILogger _logger; + public partial class FormSecure : Form + { + private readonly ILogger _logger; - private readonly ISecureLogic _logic; + private readonly ISecureLogic _logic; - private int? _id; + private int? _id; - private Dictionary _secureSensors; + private Dictionary _secureSensors; - public int Id { set { _id = value; } } + public int Id { set { _id = value; } } - public FormSecure(ILogger logger, ISecureLogic logic) - { - InitializeComponent(); + public FormSecure(ILogger logger, ISecureLogic logic) + { + InitializeComponent(); - _logger = logger; - _logic = logic; - _secureSensors = new Dictionary(); - } + _logger = logger; + _logic = logic; + _secureSensors = new Dictionary(); + } - private void FormSecure_Load(object sender, EventArgs e) - { - if (_id.HasValue) - { - _logger.LogInformation("Загрузка изделия"); + private void FormSecure_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка изделия"); - try - { - var view = _logic.ReadElement(new SecureSearchModel { Id = _id.Value }); + 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); - } - } - } + 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("Загрузка заготовок для изделия"); + private void LoadData() + { + _logger.LogInformation("Загрузка заготовок для изделия"); - try - { - if (_secureSensors != null) - { - dataGridView.Rows.Clear(); + 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 }); - } + 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); - } - } + 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)); + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormSecureSensor form) - { - if (form.ShowDialog() == DialogResult.OK) - { - if (form.SensorModel == null) - { - return; - } + if (form.ShowDialog() == DialogResult.OK) + { + if (form.SensorModel == null) + { + return; + } - _logger.LogInformation("Добавление новой заготовки:{SensorName} - {Count}", form.SensorModel.SensorName, form.Count); + _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)); - } + if (_secureSensors.ContainsKey(form.Id)) + { + _secureSensors[form.Id] = (form.SensorModel, form.Count); + } + else + { + _secureSensors.Add(form.Id, (form.SensorModel, form.Count)); + } - LoadData(); - } - } - } + LoadData(); + } + } - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSecureSensor)); + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormSecureSensor form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _secureSensors[id].Item2; + 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; - } + 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); + _logger.LogInformation("Изменение компонента:{SensorName} - {Count}", form.SensorModel.SensorName, form.Count); + _secureSensors[form.Id] = (form.SensorModel, form.Count); - LoadData(); - } - } - } - } + 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); - } + 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(); - } - } - } + LoadData(); + } + } + } - private void ButtonRef_Click(object sender, EventArgs e) - { - 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); + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - if (string.IsNullOrEmpty(textBoxPrice.Text)) - { - MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (string.IsNullOrEmpty(textBoxPrice.Text)) + { + MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - if (_secureSensors == null || _secureSensors.Count == 0) - { - MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (_secureSensors == null || _secureSensors.Count == 0) + { + MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } + return; + } - _logger.LogInformation("Сохранение изделия"); + _logger.LogInformation("Сохранение изделия"); - try - { - var model = new SecureBindingModel - { - Id = _id ?? 0, - SecureName = textBoxName.Text, - Price = Convert.ToDouble(textBoxPrice.Text), - SecureSensors = _secureSensors - }; + 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); + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения изделия"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ButtonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } - //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) - private double CalcPrice() - { - double price = 0; + //в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%) + private double CalcPrice() + { + double price = 0; - foreach (var elem in _secureSensors) - { - price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); - } + foreach (var elem in _secureSensors) + { + price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); + } - return Math.Round(price * 1.1, 2); - } - } + return Math.Round(price * 1.1, 2); + } + } } diff --git a/SecuritySystem/SecuritySystem/FormSecures.cs b/SecuritySystem/SecuritySystem/FormSecures.cs index a890938..fc01463 100644 --- a/SecuritySystem/SecuritySystem/FormSecures.cs +++ b/SecuritySystem/SecuritySystem/FormSecures.cs @@ -1,5 +1,7 @@ -using SecuritySystemContracts.BindingModels; +using SecuritySystemBusinessLogic.BusinessLogic; +using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,113 +15,100 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormSecures : Form - { - private readonly ILogger _logger; + public partial class FormSecures : Form + { + private readonly ILogger _logger; - private readonly ISecureLogic _logic; - public FormSecures(ILogger logger, ISecureLogic logic) - { + private readonly ISecureLogic _logic; - InitializeComponent(); + public FormSecures(ILogger logger, ISecureLogic logic) + { - _logger = logger; - _logic = logic; - } + InitializeComponent(); - private void FormSecures_Load(object sender, EventArgs e) - { - LoadData(); - } + _logger = logger; + _logic = logic; + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); + private void FormSecures_Load(object sender, EventArgs e) + { + LoadData(); + } - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["SecureSensors"].Visible = false; - dataGridView.Columns["SecureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_logic.ReadList(null)); - _logger.LogInformation("Загрузка изделий"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки изделий"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + _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)); + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormSecure form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } + 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)); + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); - if (service is FormSecure form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } - } - } + 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); + 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("Удаление изделия"); + _logger.LogInformation("Удаление изделия"); - try - { - if (!_logic.Delete(new SecureBindingModel - { - Id = id - })) - { - throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); - } + 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); - } - } - } - } + 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 + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/SecuritySystem/SecuritySystem/FormSensors.cs b/SecuritySystem/SecuritySystem/FormSensors.cs index f8035d9..694d4ee 100644 --- a/SecuritySystem/SecuritySystem/FormSensors.cs +++ b/SecuritySystem/SecuritySystem/FormSensors.cs @@ -1,5 +1,7 @@ -using SecuritySystemContracts.BindingModels; +using SecuritySystemBusinessLogic.BusinessLogic; +using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -13,114 +15,100 @@ using System.Windows.Forms; namespace SecuritySystem { - public partial class FormSensors : Form - { - private readonly ILogger _logger; + public partial class FormSensors : Form + { + private readonly ILogger _logger; - private readonly ISensorLogic _logic; + private readonly ISensorLogic _logic; - public FormSensors(ILogger logger, ISensorLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public FormSensors(ILogger logger, ISensorLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } - private void FormSensor_Load(object sender, EventArgs e) - { - LoadData(); - } + private void FormSensor_Load(object sender, EventArgs e) + { + LoadData(); + } - private void LoadData() - { - try - { - var list = _logic.ReadList(null); + private void LoadData() + { + try + { + dataGridView.FillandConfigGrid(_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, "Ошибка загрузки заготовок"); - _logger.LogInformation("Загрузка заготовок"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заготовок"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void ButtonAdd_Click(object sender, EventArgs e) + { + var form = DependencyManager.Instance.Resolve(); - private void ButtonAdd_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSensor)); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } - 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 form = DependencyManager.Instance.Resolve(); - //проверяем наличие выделенной строки - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSensor)); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } - 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); - 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("Удаление компонента"); - _logger.LogInformation("Удаление компонента"); + try + { + if (!_logic.Delete(new SensorBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } - 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); + } + } + } + } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } - - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } } diff --git a/SecuritySystem/SecuritySystem/Program.cs b/SecuritySystem/SecuritySystem/Program.cs index 908f2a3..79ce65b 100644 --- a/SecuritySystem/SecuritySystem/Program.cs +++ b/SecuritySystem/SecuritySystem/Program.cs @@ -4,6 +4,7 @@ using SecuritySystemBusinessLogic.OfficePackage; using SecuritySystemBusinessLogic.OfficePackage.Implements; using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.DI; using SecuritySystemContracts.StoragesContracts; using SecuritySystemDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; @@ -12,97 +13,88 @@ using NLog.Extensions.Logging; namespace SecuritySystem { - internal static class Program - { - private static ServiceProvider? _serviceProvider; + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font; + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + InitDependency(); - public static ServiceProvider? ServiceProvider => _serviceProvider; + try + { + var mailSender = DependencyManager.Instance.Resolve(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font; - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = DependencyManager.Instance.Resolve(); - try - { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); - - // - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); - } - catch (Exception ex) - { - var logger = _serviceProvider.GetService(); - - logger?.LogError(ex, " "); - } + logger?.LogError(ex, " "); + } - Application.Run(_serviceProvider.GetRequiredService()); - } + Application.Run(DependencyManager.Instance.Resolve()); + } - private static void ConfigureServices(ServiceCollection services) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); + private static void InitDependency() + { + DependencyManager.InitDependency(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddSingleton(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); - 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(); - } + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); - } + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); + } } \ No newline at end of file diff --git a/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/BackUpLogic.cs b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..c43d934 --- /dev/null +++ b/SecuritySystem/SecuritySystemBusinessLogiс/BusinessLogic/BackUpLogic.cs @@ -0,0 +1,129 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemDataModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.BusinessLogic +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + + private readonly IBackUpInfo _backUpInfo; + + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + + public void CreateBackUp(BackUpSaveBinidngModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + + if (dirInfo.Exists) + { + //НЕ ВЫБИРАЕМ РАБОЧИЙ СТОЛ, ИНАЧЕ ВСЁ С НЕГО УДАЛИТСЯ + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + + _logger.LogDebug("Delete archive"); + + string fileName = $"{model.FolderName}.zip"; + + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", nameof(assembly)); + } + + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + + _logger.LogDebug("Find {count} types", types.Length); + + foreach (var type in types) + { + //проверка на то, является ли тип интерфейсом и унаследован ли он от IId + if (type.IsInterface && type.GetInterface(typeIId.Name) != null) + { + var modelType = _backUpInfo.GetTypeByModelInterface(type.Name); + + if (modelType == null) + { + throw new InvalidOperationException($"Не найден класс - модель для { type.Name }"); + } + + _logger.LogDebug("Call SaveToFile method for {name} type", type.Name); + + // вызываем метод на выполнение + method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName }); + } + } + + _logger.LogDebug("Create zip and remove folder"); + + // архивируем + ZipFile.CreateFromDirectory(model.FolderName, fileName); + + // удаляем папку + dirInfo.Delete(true); + } + catch (Exception) + { + throw; + } + } + + private void SaveToFile(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + + return; + } + + //три строчки ниже - сериализация файлов в json + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + + using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate); + + jsonFormatter.WriteObject(fs, records); + } + } + +} diff --git a/SecuritySystem/SecuritySystemContracts/Attributes/ColumnAttribute.cs b/SecuritySystem/SecuritySystemContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..553e761 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.Attributes +{ + //указываем, что данный атрибут можно прописать только в Property + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public ColumnAttribute(string title = "", bool visible = true, int width = 0, + GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) + { + Title = title; + Visible = visible; + Width = width; + GridViewAutoSize = gridViewAutoSize; + IsUseAutoSize = isUseAutoSize; + } + + public string Title { get; private set; } + + public bool Visible { get; private set; } + + public int Width { get; private set; } + + public GridViewAutoSize GridViewAutoSize { get; private set; } + + public bool IsUseAutoSize { get; private set; } + } +} diff --git a/SecuritySystem/SecuritySystemContracts/Attributes/GridViewAutoSize.cs b/SecuritySystem/SecuritySystemContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..df5bd5d --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/SecuritySystem/SecuritySystemContracts/BindingModels/BackUpSaveBinidngModel.cs b/SecuritySystem/SecuritySystemContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..ca01f61 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/SecuritySystem/SecuritySystemContracts/BindingModels/MessageInfoBindingModel.cs b/SecuritySystem/SecuritySystemContracts/BindingModels/MessageInfoBindingModel.cs index b19ef31..04276a7 100644 --- a/SecuritySystem/SecuritySystemContracts/BindingModels/MessageInfoBindingModel.cs +++ b/SecuritySystem/SecuritySystemContracts/BindingModels/MessageInfoBindingModel.cs @@ -9,6 +9,8 @@ namespace SecuritySystemContracts.BindingModels { public class MessageInfoBindingModel : IMessageInfoModel { + public int Id { get; set; } + public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } diff --git a/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IBackUpLogic.cs b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..2b8ac54 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,16 @@ +using SecuritySystemContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BusinessLogicsContracts +{ + //интерфейс создания бекапа + public interface IBackUpLogic + { + //путь и имя файла для архивации + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/DependencyManager.cs b/SecuritySystem/SecuritySystemContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..b5d43d0 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/DependencyManager.cs @@ -0,0 +1,63 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + /// + /// Менеджер для работы с зависимостями + /// + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new UnityDependencyContainer(); + } + + public static DependencyManager Instance + { + get + { + if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } + + return _manager; + } + } + + //Иницализация библиотек, в которых идут установки зависомстей + public static void InitDependency() + { + var ext = ServiceProviderLoader.GetImplementationExtensions(); + + if (ext == null) + { + throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); + } + + // регистрируем зависимости + ext.RegisterServices(); + } + + //Регистрация логгера + public void AddLogging(Action configure) => _dependencyManager.AddLogging(configure); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType(isSingle); + + //Добавление зависимости + public void RegisterType(bool isSingle = false) where T : class => _dependencyManager.RegisterType(isSingle); + + //Получение класса со всеми зависмостями + public T Resolve() => _dependencyManager.Resolve(); + } + +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/IDependencyContainer.cs b/SecuritySystem/SecuritySystemContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..52f775c --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/IDependencyContainer.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + //Интерфейс установки зависмости между элементами + public interface IDependencyContainer + { + //Регистрация логгера + void AddLogging(Action configure); + + //Добавление зависимости + void RegisterType(bool isSingle) where U : class, T where T : + class; + + //Добавление зависимости + void RegisterType(bool isSingle) where T : class; + + //Получение класса со всеми зависмостями + T Resolve(); + } +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/IImplementationExtension.cs b/SecuritySystem/SecuritySystemContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..7c9f2ae --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/IImplementationExtension.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + + //Интерфейс для регистрации зависимостей в модулях + public interface IImplementationExtension + { + //для установления приоритета + public int Priority { get; } + + //Регистрация сервисов + public void RegisterServices(); + } + +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/ServiceDependencyContainer.cs b/SecuritySystem/SecuritySystemContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..235f536 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/ServiceDependencyContainer.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + public class ServiceDependencyContainer : IDependencyContainer + { + private ServiceProvider? _serviceProvider; + + private readonly ServiceCollection _serviceCollection; + + public ServiceDependencyContainer() + { + _serviceCollection = new ServiceCollection(); + } + + public void AddLogging(Action configure) + { + _serviceCollection.AddLogging(configure); + } + + public void RegisterType(bool isSingle) where U : class, T where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + _serviceProvider = null; + } + + public void RegisterType(bool isSingle) where T : class + { + if (isSingle) + { + _serviceCollection.AddSingleton(); + } + else + { + _serviceCollection.AddTransient(); + } + _serviceProvider = null; + } + + public T Resolve() + { + if (_serviceProvider == null) + { + _serviceProvider = _serviceCollection.BuildServiceProvider(); + } + return _serviceProvider.GetService()!; + } + } +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/ServiceProviderLoader.cs b/SecuritySystem/SecuritySystemContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..698c4a7 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + //Загрузчик данных + public static partial class ServiceProviderLoader + { + //Загрузка всех классов-реализаций IImplementationExtension + public static IImplementationExtension? GetImplementationExtensions() + { + IImplementationExtension? source = null; + + var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories); + + foreach (var file in files.Distinct()) + { + Assembly asm = Assembly.LoadFrom(file); + + foreach (var t in asm.GetExportedTypes()) + { + if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t)) + { + if (source == null) + { + source = (IImplementationExtension)Activator.CreateInstance(t)!; + } + else + { + var newSource = (IImplementationExtension)Activator.CreateInstance(t)!; + + if (newSource.Priority > source.Priority) + { + source = newSource; + } + } + } + } + } + + return source; + } + + private static string TryGetImplementationExtensionsFolder() + { + var directory = new DirectoryInfo(Directory.GetCurrentDirectory()); + + while (directory != null && !directory.GetDirectories("ImplementationExtensions", + SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions")) + { + directory = directory.Parent; + } + + return $"{directory?.FullName}\\ImplementationExtensions"; + } + } +} diff --git a/SecuritySystem/SecuritySystemContracts/DI/UnityDependencyContainer.cs b/SecuritySystem/SecuritySystemContracts/DI/UnityDependencyContainer.cs new file mode 100644 index 0000000..74d82b1 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/DI/UnityDependencyContainer.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Logging; +using Unity.Microsoft.Logging; +using Unity; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.DI +{ + public class UnityDependencyContainer : IDependencyContainer + { + private readonly IUnityContainer _container; + + public UnityDependencyContainer() + { + _container = new UnityContainer(); + } + + public void AddLogging(Action configure) + { + var factory = LoggerFactory.Create(configure); + _container.AddExtension(new LoggingExtension(factory)); + } + + public void RegisterType(bool isSingle) where T : class + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + + } + + public T Resolve() + { + return _container.Resolve(); + } + + void IDependencyContainer.RegisterType(bool isSingle) + { + _container.RegisterType(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient); + } + } +} diff --git a/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj b/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj index 07925a0..148e183 100644 --- a/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj +++ b/SecuritySystem/SecuritySystemContracts/SecuritySystemContracts.csproj @@ -15,6 +15,8 @@ + + diff --git a/SecuritySystem/SecuritySystemContracts/StoragesContracts/IBackUpInfo.cs b/SecuritySystem/SecuritySystemContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..fc44c58 --- /dev/null +++ b/SecuritySystem/SecuritySystemContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.StoragesContracts +{ + //интерфейс получения данных по всем сущностям + public interface IBackUpInfo + { + //метод получения данных по всем сущностям + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } + +} diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/ClientViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/ClientViewModel.cs index f032831..a82379b 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/ClientViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/ClientViewModel.cs @@ -1,4 +1,5 @@ -using SecuritySystemDataModels.Models; +using SecuritySystemContracts.Attributes; +using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,18 +9,19 @@ using System.Threading.Tasks; namespace SecuritySystemContracts.ViewModels { - public class ClientViewModel : IClientModel - { - public int Id { get; set; } + public class ClientViewModel : IClientModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; + [Column(title: "ФИО клиента", width: 150)] + public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] - public string Email { get; set; } = string.Empty; + [Column(title: "Логие (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] - public string Password { get; set; } = string.Empty; + [Column(title: "Пароль", width: 150)] + public string Password { get; set; } = string.Empty; - } + } } diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs index 4c2512e..e16b3da 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using SecuritySystemDataModels.Models; +using SecuritySystemContracts.Attributes; +using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,18 +11,19 @@ namespace SecuritySystemContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", width: 150)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 150)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж")] + [Column(title: "Стаж", width: 150)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column(title: "Квалификация", width: 150)] public int Qualification { get; set; } } } diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/MessageInfoViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/MessageInfoViewModel.cs index 89a3e6a..725addf 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/MessageInfoViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using SecuritySystemDataModels.Models; +using SecuritySystemContracts.Attributes; +using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace SecuritySystemContracts.ViewModels { public class MessageInfoViewModel : IMessageInfoModel { + [Column(visible: false)] + public int Id { get; set; } + + [Column(visible: false)] public string MessageId { get; set; } = string.Empty; + [Column(visible: false)] public int? ClientId { get; set; } - [DisplayName("Отправитель")] + [Column(title: "Отправитель", width: 150)] public string SenderName { get; set; } = string.Empty; - [DisplayName("Дата отправки")] + [Column(title: "Дата отправки", width: 150)] public DateTime DateDelivery { get; set; } = DateTime.Now; - [DisplayName("Заголовок")] + [Column(title: "Заголовок", width: 150)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", width: 150)] public string Body { get; set; } = string.Empty; } } diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs index d47ff93..5a32fb6 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using SecuritySystemDataModels.Enums; +using SecuritySystemContracts.Attributes; +using SecuritySystemDataModels.Enums; using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; @@ -9,40 +10,43 @@ using System.Threading.Tasks; namespace SecuritySystemContracts.ViewModels { - //класс для отображения пользователю информации о заказах - public class OrderViewModel : IOrderModel - { - [DisplayName("Номер")] - public int Id { get; set; } + //класс для отображения пользователю информации о заказах + public class OrderViewModel : IOrderModel + { + [Column(visible: false)] + public int Id { get; set; } - public int ClientId { get; set; } + [Column(visible: false)] + public int ClientId { get; set; } - public int? ImplementerId { get; set; } + [Column(visible: false)] + public int? ImplementerId { get; set; } - public int SecureId { get; set; } + [Column(visible: false)] + public int SecureId { get; set; } - [DisplayName("ФИО клиента")] - public string ClientFIO { get; set; } = string.Empty; + [Column(title: "ФИО клиента", width: 150)] + public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Изделие")] - public string SecureName { get; set; } = string.Empty; + [Column(title: "Изделие", width: 150)] + public string SecureName { get; set; } = string.Empty; - [DisplayName("ФИО исполнителя")] - public string ImplementerFIO { get; set; } = string.Empty; + [Column(title: "ФИО исполнителя", width: 150)] + public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Количество")] - public int Count { get; set; } + [Column(title: "Количество", width: 150)] + public int Count { get; set; } - [DisplayName("Сумма")] - public double Sum { get; set; } + [Column(title: "Сумма", width: 150)] + public double Sum { get; set; } - [DisplayName("Статус")] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [Column(title: "Статус", width: 150)] + public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] - public DateTime DateCreate { get; set; } = DateTime.Now; + [Column(title: "Дата создания", width: 150)] + public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] - public DateTime? DateImplement { get; set; } - } + [Column(title: "Дата выполнения", width: 150)] + public DateTime? DateImplement { get; set; } + } } diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs index b9d82f6..b1393a2 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/SecureViewModel.cs @@ -1,4 +1,5 @@ -using SecuritySystemDataModels.Models; +using SecuritySystemContracts.Attributes; +using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,17 +9,19 @@ using System.Threading.Tasks; namespace SecuritySystemContracts.ViewModels { - //класс для отображения пользователю информаци о продуктах (изделиях) - public class SecureViewModel : ISecureModel - { - public int Id { get; set; } + //класс для отображения пользователю информаци о продуктах (изделиях) + public class SecureViewModel : ISecureModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Навание изделия")] - public string SecureName { get; set; } = string.Empty; + [Column(title: "Навание изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] + public string SecureName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Price { get; set; } + [Column(title: "Цена", width: 150)] + public double Price { get; set; } - public Dictionary SecureSensors { get; set; } = new(); - } -} \ No newline at end of file + [Column(visible: false)] + public Dictionary SecureSensors { get; set; } = new(); + } +} diff --git a/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs b/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs index a7e46fc..4578d05 100644 --- a/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs +++ b/SecuritySystem/SecuritySystemContracts/ViewModels/SensorsViewModel.cs @@ -5,18 +5,20 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using SecuritySystemContracts.Attributes; namespace SecuritySystemContracts.ViewModels { - //класс для отображения пользователю данных - public class SensorViewModel : ISensorModel - { - public int Id { get; set; } + //класс для отображения пользователю данных + public class SensorViewModel : ISensorModel + { + [Column(visible: false)] + public int Id { get; set; } - [DisplayName("Название Датчика")] - public string SensorName { get; set; } = string.Empty; + [Column(title: "Название датчика", width: 150)] + public string SensorName { get; set; } = string.Empty; - [DisplayName("Цена")] - public double Cost { get; set; } - } -} \ No newline at end of file + [Column(title: "Цена", width: 150)] + public double Cost { get; set; } + } +} diff --git a/SecuritySystem/SecuritySystemDataModels/Models/IMessageInfoModel.cs b/SecuritySystem/SecuritySystemDataModels/Models/IMessageInfoModel.cs index 5a50c57..5248509 100644 --- a/SecuritySystem/SecuritySystemDataModels/Models/IMessageInfoModel.cs +++ b/SecuritySystem/SecuritySystemDataModels/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace SecuritySystemDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/DataBaseImplementationExtension.cs b/SecuritySystem/SecuritySystemDatabaseImplement/DataBaseImplementationExtension.cs new file mode 100644 index 0000000..2d586d0 --- /dev/null +++ b/SecuritySystem/SecuritySystemDatabaseImplement/DataBaseImplementationExtension.cs @@ -0,0 +1,33 @@ +using SecuritySystemContracts.DI; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDatabaseImplement +{ + public class DataBaseImplementationExtension : IImplementationExtension + { + public int Priority => 2; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Implements/BackUpInfo.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..29b8eb8 --- /dev/null +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,36 @@ +using SecuritySystemContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new SecuritySystemDatabase(); + + return context.Set().ToList(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + + return null; + } + } + +} diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Client.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Client.cs index 5c35dbd..879cb1a 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Client.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Client.cs @@ -6,22 +6,28 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ClientFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Email { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; //для реализации связи многие ко многим с заказами (так как клиенты могу сделать одинаковый заказ) diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Implementer.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Implementer.cs index e52c93b..910b45c 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Implementer.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Implementer.cs @@ -6,25 +6,32 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } [Required] + [DataMember] public string ImplementerFIO { get; set; } = string.Empty; [Required] + [DataMember] public string Password { get; set; } = string.Empty; [Required] + [DataMember] public int WorkExperience { get; set; } [Required] + [DataMember] public int Qualification { get; set; } //для реализации связи один ко многим с заказами diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/MessageInfo.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/MessageInfo.cs index 05403f5..4fd6006 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/MessageInfo.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/MessageInfo.cs @@ -5,28 +5,29 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + public int Id => throw new NotImplementedException(); + [Key] + [DataMember] public string MessageId { get; set; } = string.Empty; public int? ClientId { get; set; } - [Required] public string SenderName { get; set; } = string.Empty; - [Required] public DateTime DateDelivery { get; set; } = DateTime.Now; - [Required] public string Subject { get; set; } = string.Empty; - [Required] public string Body { get; set; } = string.Empty; public virtual Client? Client { get; set; } diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Order.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Order.cs index d9637c2..3bf5b9f 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Order.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Order.cs @@ -6,94 +6,105 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemDatabaseImplement.Models { - public class Order : IOrderModel - { - public int Id { get; private set; } + [DataContract] + public class Order : IOrderModel + { + [DataMember] + public int Id { get; private set; } - [Required] - public int SecureId { get; private set; } + [Required] + [DataMember] + public int SecureId { get; private set; } - [Required] - public int ClientId { get; private set; } + [Required] + [DataMember] + public int ClientId { get; private set; } - public int? ImplementerId { get; private set; } + [DataMember] + public int? ImplementerId { get; private set; } - [Required] - public int Count { get; private set; } + [Required] + [DataMember] + public int Count { get; private set; } - [Required] - public double Sum { get; private set; } + [Required] + [DataMember] + public double Sum { get; private set; } - [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [Required] + [DataMember] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; + [Required] + [DataMember] + public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } + [DataMember] + public DateTime? DateImplement { get; private set; } - //для передачи названия изделия - public virtual Secure Secure { get; set; } + //для передачи названия изделия + public virtual Secure Secure { get; set; } - //для передачи имени клиента - public virtual Client Client { get; set; } + //для передачи имени клиента + public virtual Client Client { get; set; } - //для передачи имени исполнителя - public virtual Implementer? Implementer { get; set; } + //для передачи имени исполнителя + public virtual Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel model) - { - if (model == null) - { - return null; - } + public static Order? Create(OrderBindingModel model) + { + if (model == null) + { + return null; + } - return new Order() - { - Id = model.Id, - SecureId = model.SecureId, - ClientId = model.ClientId, - ImplementerId = model.ImplementerId, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; - } + return new Order() + { + Id = model.Id, + SecureId = model.SecureId, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } - public void Update(OrderBindingModel model) - { - if (model == null) - { - return; - } + public void Update(OrderBindingModel model) + { + if (model == null) + { + return; + } - ImplementerId = model.ImplementerId; - Status = model.Status; - DateImplement = model.DateImplement; - } + ImplementerId = model.ImplementerId; + Status = model.Status; + DateImplement = model.DateImplement; + } - public OrderViewModel GetViewModel => new() - { - Id = Id, - SecureId = SecureId, - ClientId = ClientId, - ImplementerId = ImplementerId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement, - SecureName = Secure.SecureName, - ClientFIO = Client.ClientFIO, - ImplementerFIO = Implementer?.ImplementerFIO - }; - } + public OrderViewModel GetViewModel => new() + { + Id = Id, + SecureId = SecureId, + ClientId = ClientId, + ImplementerId = ImplementerId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement, + SecureName = Secure.SecureName, + ClientFIO = Client.ClientFIO, + ImplementerFIO = Implementer?.ImplementerFIO + }; + } } diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Secure.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Secure.cs index e97f6de..0878640 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Secure.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Secure.cs @@ -7,112 +7,118 @@ using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { - public class Secure : ISecureModel - { - public int Id { get; set; } + [DataContract] + public class Secure : ISecureModel + { + [DataMember] + public int Id { get; set; } - [Required] - public string SecureName { get; set; } = string.Empty; + [Required] + [DataMember] + public string SecureName { get; set; } = string.Empty; - [Required] - public double Price { get; set; } + [Required] + [DataMember] + public double Price { get; set; } - public Dictionary? _secureSensors = null; + public Dictionary? _secureSensors = null; - //это поле не будет "мапиться" в бд - [NotMapped] - public Dictionary SecureSensors - { - get - { - if (_secureSensors == null) - { - _secureSensors = Sensors - .ToDictionary(recPC => recPC.SensorId, recPC => (recPC.Sensor as ISensorModel, recPC.Count)); - } + //это поле не будет "мапиться" в бд + [NotMapped] + [DataMember] + public Dictionary SecureSensors + { + get + { + if (_secureSensors == null) + { + _secureSensors = Sensors + .ToDictionary(recPC => recPC.SensorId, recPC => (recPC.Sensor as ISensorModel, recPC.Count)); + } - return _secureSensors; - } - } + return _secureSensors; + } + } - //для реализации связи многие ко многим с заготовками - [ForeignKey("SecureId")] - public virtual List Sensors { get; set; } = new(); + //для реализации связи многие ко многим с заготовками + [ForeignKey("SecureId")] + public virtual List Sensors { get; set; } = new(); - [ForeignKey("SecureId")] - public virtual List Orders { get; set; } = new(); + [ForeignKey("SecureId")] + public virtual List Orders { get; set; } = new(); - public static Secure Create(SecuritySystemDatabase context, SecureBindingModel model) - { - return new Secure() - { - Id = model.Id, - SecureName = model.SecureName, - Price = model.Price, - Sensors = model.SecureSensors.Select(x => new SecureSensor - { - Sensor = context.Sensors.First(y => y.Id == x.Key), - Count = x.Value.Item2 - }).ToList() - }; - } + public static Secure Create(SecuritySystemDatabase context, SecureBindingModel model) + { + return new Secure() + { + Id = model.Id, + SecureName = model.SecureName, + Price = model.Price, + Sensors = model.SecureSensors.Select(x => new SecureSensor + { + Sensor = context.Sensors.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } - public void Update(SecureBindingModel model) - { - SecureName = model.SecureName; - Price = model.Price; - } + public void Update(SecureBindingModel model) + { + SecureName = model.SecureName; + Price = model.Price; + } - public SecureViewModel GetViewModel => new() - { - Id = Id, - SecureName = SecureName, - Price = Price, - SecureSensors = SecureSensors - }; + public SecureViewModel GetViewModel => new() + { + Id = Id, + SecureName = SecureName, + Price = Price, + SecureSensors = SecureSensors + }; - Dictionary ISecureModel.SecureSensors => throw new NotImplementedException(); + Dictionary ISecureModel.SecureSensors => throw new NotImplementedException(); - public void UpdateSensors(SecuritySystemDatabase context, SecureBindingModel model) - { - var secureSensors = context.SecureSensors.Where(rec => rec.SecureId == model.Id).ToList(); + public void UpdateSensors(SecuritySystemDatabase context, SecureBindingModel model) + { + var secureSensors = context.SecureSensors.Where(rec => rec.SecureId == model.Id).ToList(); - if (secureSensors != null && secureSensors.Count > 0) - { - // удалили те, которых нет в модели - context.SecureSensors.RemoveRange(secureSensors.Where(rec => !model.SecureSensors.ContainsKey(rec.SecureId))); - context.SaveChanges(); + if (secureSensors != null && secureSensors.Count > 0) + { + // удалили те, которых нет в модели + context.SecureSensors.RemoveRange(secureSensors.Where(rec => !model.SecureSensors.ContainsKey(rec.SecureId))); + context.SaveChanges(); - // обновили количество у существующих записей - foreach (var updateSecure in secureSensors) - { - updateSecure.Count = model.SecureSensors[updateSecure.SecureId].Item2; - model.SecureSensors.Remove(updateSecure.SecureId); - } + // обновили количество у существующих записей + foreach (var updateSecure in secureSensors) + { + updateSecure.Count = model.SecureSensors[updateSecure.SecureId].Item2; + model.SecureSensors.Remove(updateSecure.SecureId); + } - context.SaveChanges(); - } + context.SaveChanges(); + } - var secure = context.Secures.First(x => x.Id == Id); + var secure = context.Secures.First(x => x.Id == Id); - foreach (var pc in model.SecureSensors) - { - context.SecureSensors.Add(new SecureSensor - { - Secure = secure, - Sensor = context.Sensors.First(x => x.Id == pc.Key), - Count = pc.Value.Item2 - }); + foreach (var pc in model.SecureSensors) + { + context.SecureSensors.Add(new SecureSensor + { + Secure = secure, + Sensor = context.Sensors.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); - context.SaveChanges(); - } + context.SaveChanges(); + } - _secureSensors = null; - } - } + _secureSensors = null; + } + } } diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/SecureSensor.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/SecureSensor.cs index b67bc50..05c57ed 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/SecureSensor.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/SecureSensor.cs @@ -2,26 +2,28 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { - public class SecureSensor - { - public int Id { get; set; } + [DataContract] + public class SecureSensor + { + public int Id { get; set; } - [Required] - public int SecureId { get; set; } + [Required] + public int SecureId { get; set; } - [Required] - public int SensorId { get; set; } + [Required] + public int SensorId { get; set; } - [Required] - public int Count { get; set; } + [Required] + public int Count { get; set; } - public virtual Sensor Sensor { get; set; } = new(); + public virtual Sensor Sensor { get; set; } = new(); - public virtual Secure Secure { get; set; } = new(); - } + public virtual Secure Secure { get; set; } = new(); + } } diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Sensor.cs b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Sensor.cs index f7ce4ed..2160a8d 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/Models/Sensor.cs +++ b/SecuritySystem/SecuritySystemDatabaseImplement/Models/Sensor.cs @@ -7,66 +7,71 @@ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Models { - public class Sensor : ISensorModel - { - public int Id { get; private set; } + [DataContract] + public class Sensor : ISensorModel + { + [DataMember] + public int Id { get; private set; } - [Required] - public string SensorName { get; private set; } = string.Empty; + [Required] + [DataMember] + public string SensorName { get; private set; } = string.Empty; - [Required] - public double Cost { get; set; } + [Required] + [DataMember] + public double Cost { get; set; } - //для реализации связи многие ко многим с изделиями - [ForeignKey("SensorId")] - public virtual List SecureSensors { get; set; } = new(); + //для реализации связи многие ко многим с изделиями + [ForeignKey("SensorId")] + public virtual List SecureSensors { get; set; } = new(); - public static Sensor? Create(SensorBindingModel model) - { - if(model == null) - { - return null; - } + public static Sensor? Create(SensorBindingModel model) + { + if (model == null) + { + return null; + } - return new Sensor() - { - Id = model.Id, - SensorName = model.SensorName, - Cost = model.Cost - }; - } + return new Sensor() + { + Id = model.Id, + SensorName = model.SensorName, + Cost = model.Cost + }; + } - public static Sensor Create(SensorViewModel model) - { - return new Sensor - { - Id = model.Id, - SensorName = model.SensorName, - Cost = model.Cost - }; - } + public static Sensor Create(SensorViewModel model) + { + return new Sensor + { + Id = model.Id, + SensorName = model.SensorName, + Cost = model.Cost + }; + } - public void Update(SensorBindingModel model) - { - if(model == null) - { - return; - } + public void Update(SensorBindingModel model) + { + if (model == null) + { + return; + } - SensorName = model.SensorName; - Cost = model.Cost; - } + SensorName = model.SensorName; + Cost = model.Cost; + } - public SensorViewModel GetViewModel => new() - { - Id = Id, - SensorName = SensorName, - Cost = Cost - }; - } -} \ No newline at end of file + public SensorViewModel GetViewModel => new() + { + Id = Id, + SensorName = SensorName, + Cost = Cost + }; + } +} diff --git a/SecuritySystem/SecuritySystemDatabaseImplement/SecuritySystemDatabaseImplement.csproj b/SecuritySystem/SecuritySystemDatabaseImplement/SecuritySystemDatabaseImplement.csproj index c47a43f..f08eaca 100644 --- a/SecuritySystem/SecuritySystemDatabaseImplement/SecuritySystemDatabaseImplement.csproj +++ b/SecuritySystem/SecuritySystemDatabaseImplement/SecuritySystemDatabaseImplement.csproj @@ -20,4 +20,8 @@ + + + + diff --git a/SecuritySystem/SecuritySystemFileImplement/FileImplementationExtension.cs b/SecuritySystem/SecuritySystemFileImplement/FileImplementationExtension.cs new file mode 100644 index 0000000..4236987 --- /dev/null +++ b/SecuritySystem/SecuritySystemFileImplement/FileImplementationExtension.cs @@ -0,0 +1,34 @@ +using SecuritySystemContracts.DI; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemFileImplement +{ + //для реализации нужных нам зависимостей в данном варианте хранения информации + public class FileImplementationExtension : IImplementationExtension + { + public int Priority => 1; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } +} diff --git a/SecuritySystem/SecuritySystemFileImplement/Implements/BackUpInfo.cs b/SecuritySystem/SecuritySystemFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..c16f923 --- /dev/null +++ b/SecuritySystem/SecuritySystemFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,37 @@ +using SecuritySystemContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + var source = DataFileSingleton.GetInstance(); + + return (List?)source.GetType().GetProperties() + .FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T)) + ?.GetValue(source); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + var assembly = typeof(BackUpInfo).Assembly; + var types = assembly.GetTypes(); + + foreach (var type in types) + { + if (type.IsClass && type.GetInterface(modelInterfaceName) != null) + { + return type; + } + } + + return null; + } + } +} diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/Client.cs b/SecuritySystem/SecuritySystemFileImplement/Models/Client.cs index d689027..9127148 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/Client.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/Client.cs @@ -7,20 +7,26 @@ using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ClientFIO { get; private set; } = string.Empty; + [DataMember] public string Email { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/Implementer.cs b/SecuritySystem/SecuritySystemFileImplement/Models/Implementer.cs index a91342c..29d6d13 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/Implementer.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/Implementer.cs @@ -5,22 +5,29 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; private set; } + [DataMember] public string ImplementerFIO { get; private set; } = string.Empty; + [DataMember] public string Password { get; private set; } = string.Empty; + [DataMember] public int WorkExperience { get; private set; } + [DataMember] public int Qualification { get; private set; } public static Implementer? Create(ImplementerBindingModel model) diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/MessageInfo.cs b/SecuritySystem/SecuritySystemFileImplement/Models/MessageInfo.cs index e87d878..17aafe1 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/MessageInfo.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/MessageInfo.cs @@ -6,24 +6,34 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { + [DataContract] public class MessageInfo : IMessageInfoModel { + public int Id { get; private set; } + + [DataMember] public string MessageId { get; private set; } = string.Empty; + [DataMember] public int? ClientId { get; private set; } + [DataMember] public string SenderName { get; private set; } = string.Empty; + [DataMember] public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] public string Subject { get; private set; } = string.Empty; + [DataMember] public string Body { get; private set; } = string.Empty; public static MessageInfo? Create(MessageInfoBindingModel model) diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/Order.cs b/SecuritySystem/SecuritySystemFileImplement/Models/Order.cs index 994a1e7..52af375 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/Order.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/Order.cs @@ -6,109 +6,120 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { - //класс, реализующий интерфейс модели заказа - public class Order : IOrderModel - { - public int Id { get; private set; } + //класс, реализующий интерфейс модели заказа + [DataContract] + public class Order : IOrderModel + { + [DataMember] + public int Id { get; private set; } - public int ClientId { get; private set; } + [DataMember] + public int ClientId { get; private set; } - public int? ImplementerId { get; private set; } + [DataMember] + public int? ImplementerId { get; private set; } - public int SecureId { get; private set; } + [DataMember] + public int SecureId { get; private set; } - public int Count { get; private set; } + [DataMember] + public int Count { get; private set; } - public double Sum { get; private set; } + [DataMember] + public double Sum { get; private set; } - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] + public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } + [DataMember] + public DateTime? DateImplement { get; private set; } - public static Order? Create(OrderBindingModel model) - { - if (model == null) - { - return null; - } + public static Order? Create(OrderBindingModel model) + { + if (model == null) + { + return null; + } - return new Order() - { - Id = model.Id, - ClientId = model.ClientId, - SecureId = model.SecureId, - ImplementerId = model.ImplementerId, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; - } + return new Order() + { + Id = model.Id, + ClientId = model.ClientId, + SecureId = model.SecureId, + ImplementerId = model.ImplementerId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } - public static Order? Create(XElement element) - { - if (element == null) - { - return null; - } + public static Order? Create(XElement element) + { + if (element == null) + { + return null; + } - return new Order() - { - Id = 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), - Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), - DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), - DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : - Convert.ToDateTime(element.Element("DateImplement")!.Value) - }; - } + return new Order() + { + Id = 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), + Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), + DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), + DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : + Convert.ToDateTime(element.Element("DateImplement")!.Value) + }; + } - public void Update(OrderBindingModel model) - { - if (model == null) - { - return; - } + public void Update(OrderBindingModel model) + { + if (model == null) + { + return; + } - Status = model.Status; - DateImplement = model.DateImplement; - } + Status = model.Status; + DateImplement = model.DateImplement; + } - public OrderViewModel GetViewModel => new() - { - Id = Id, - ClientId = ClientId, - ImplementerId = ImplementerId, - SecureId = SecureId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement - }; + public OrderViewModel GetViewModel => new() + { + Id = Id, + ClientId = ClientId, + ImplementerId = ImplementerId, + SecureId = SecureId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; - 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()), - new XElement("Status", Status.ToString()), - new XElement("DateCreate", DateCreate.ToString()), - new XElement("DateImplement", DateImplement.ToString())); - } + 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()), + new XElement("Status", Status.ToString()), + new XElement("DateCreate", DateCreate.ToString()), + new XElement("DateImplement", DateImplement.ToString())); + } } diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/Secure.cs b/SecuritySystem/SecuritySystemFileImplement/Models/Secure.cs index 29581ff..94efd72 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/Secure.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/Secure.cs @@ -4,105 +4,110 @@ using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { - //класс реализующий интерфейс модели изделия - public class Secure : ISecureModel - { - public int Id { get; private set; } + //класс реализующий интерфейс модели изделия + [DataContract] + public class Secure : ISecureModel + { + [DataMember] + public int Id { get; private set; } - public string SecureName { get; private set; } = string.Empty; + [DataMember] + public string SecureName { get; private set; } = string.Empty; - public double Price { get; private set; } + [DataMember] + public double Price { get; private set; } - public Dictionary Sensors { get; private set; } = new(); + public Dictionary Sensors { get; private set; } = new(); + private Dictionary? _secureSensors = null; - private Dictionary? _secureSensors = null; + [DataMember] + public Dictionary SecureSensors + { + get + { + if (_secureSensors == null) + { + var source = DataFileSingleton.GetInstance(); - public Dictionary SecureSensors - { - get - { - if (_secureSensors == null) - { - var source = DataFileSingleton.GetInstance(); + _secureSensors = Sensors.ToDictionary(x => x.Key, + y => ((source.Sensors.FirstOrDefault(z => z.Id == y.Key) as ISensorModel)!, y.Value)); + } - _secureSensors = Sensors.ToDictionary(x => x.Key, - y => ((source.Sensors.FirstOrDefault(z => z.Id == y.Key) as ISensorModel)!, y.Value)); - } + return _secureSensors; + } + } - return _secureSensors; - } - } + public static Secure? Create(SecureBindingModel model) + { + if (model == null) + { + return null; + } - public static Secure? Create(SecureBindingModel model) - { - if (model == null) - { - return null; - } + return new Secure() + { + Id = model.Id, + SecureName = model.SecureName, + Price = model.Price, + Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } - return new Secure() - { - Id = model.Id, - SecureName = model.SecureName, - Price = model.Price, - Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2) - }; - } + public static Secure? Create(XElement element) + { + if (element == null) + { + return null; + } - public static Secure? Create(XElement element) - { - if (element == null) - { - return null; - } + return new Secure() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + SecureName = element.Element("SecureName")!.Value, + Price = Convert.ToDouble(element.Element("Price")!.Value), + Sensors = element.Element("SecureSensors")!.Elements("SecureSensors").ToDictionary( + x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } - return new Secure() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - SecureName = element.Element("SecureName")!.Value, - Price = Convert.ToDouble(element.Element("Price")!.Value), - Sensors = element.Element("SecureSensors")!.Elements("SecureSensors").ToDictionary( - x => Convert.ToInt32(x.Element("Key")?.Value), - x => Convert.ToInt32(x.Element("Value")?.Value)) - }; - } + public void Update(SecureBindingModel model) + { + if (model == null) + { + return; + } - public void Update(SecureBindingModel model) - { - if (model == null) - { - return; - } + SecureName = model.SecureName; + Price = model.Price; + Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2); + _secureSensors = null; + } - SecureName = model.SecureName; - Price = model.Price; - Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2); - _secureSensors = null; - } + public SecureViewModel GetViewModel => new() + { + Id = Id, + SecureName = SecureName, + Price = Price, + SecureSensors = SecureSensors + }; - public SecureViewModel GetViewModel => new() - { - Id = Id, - SecureName = SecureName, - Price = Price, - SecureSensors = SecureSensors - }; - - public XElement GetXElement => new("Secure", - new XAttribute("Id", Id), - new XElement("SecureName", SecureName), - new XElement("Price", Price.ToString()), - new XElement("SecureSensors", Sensors.Select( - x => new XElement("SecureSensors", - new XElement("Key", x.Key), - new XElement("Value", x.Value)) - ).ToArray())); - } + public XElement GetXElement => new("Secure", + new XAttribute("Id", Id), + new XElement("SecureName", SecureName), + new XElement("Price", Price.ToString()), + new XElement("SecureSensors", Sensors.Select( + x => new XElement("SecureSensors", + new XElement("Key", x.Key), + new XElement("Value", x.Value)) + ).ToArray())); + } } diff --git a/SecuritySystem/SecuritySystemFileImplement/Models/Sensor.cs b/SecuritySystem/SecuritySystemFileImplement/Models/Sensor.cs index 4859ccf..79743e0 100644 --- a/SecuritySystem/SecuritySystemFileImplement/Models/Sensor.cs +++ b/SecuritySystem/SecuritySystemFileImplement/Models/Sensor.cs @@ -5,72 +5,77 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { - //реализация интерфейса модели заготовки - public class Sensor : ISensorModel - { - public int Id { get; private set; } + //реализация интерфейса модели заготовки + [DataContract] + public class Sensor : ISensorModel + { + [DataMember] + public int Id { get; private set; } - public string SensorName { get; private set; } = string.Empty; + [DataMember] + public string SensorName { get; private set; } = string.Empty; - public double Cost { get; set; } + [DataMember] + public double Cost { get; set; } - public static Sensor? Create(SensorBindingModel model) - { - if (model == null) - { - return null; - } + public static Sensor? Create(SensorBindingModel model) + { + if (model == null) + { + return null; + } - return new Sensor() - { - Id = model.Id, - SensorName = model.SensorName, - Cost = model.Cost - }; - } + return new Sensor() + { + Id = model.Id, + SensorName = model.SensorName, + Cost = model.Cost + }; + } - public static Sensor? Create(XElement element) - { - if (element == null) - { - return null; - } + public static Sensor? Create(XElement element) + { + if (element == null) + { + return null; + } - return new Sensor() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - SensorName = element.Element("SensorName")!.Value, - Cost = Convert.ToDouble(element.Element("Cost")!.Value) - }; - } + return new Sensor() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + SensorName = element.Element("SensorName")!.Value, + Cost = Convert.ToDouble(element.Element("Cost")!.Value) + }; + } - public void Update(SensorBindingModel model) - { - if (model == null) - { - return; - } + public void Update(SensorBindingModel model) + { + if (model == null) + { + return; + } - SensorName = model.SensorName; - Cost = model.Cost; - } + SensorName = model.SensorName; + Cost = model.Cost; + } - public SensorViewModel GetViewModel => new() - { - Id = Id, - SensorName = SensorName, - Cost = Cost - }; + public SensorViewModel GetViewModel => new() + { + Id = Id, + SensorName = SensorName, + Cost = Cost + }; - public XElement GetXElement => new("Sensor", - new XAttribute("Id", Id), - new XElement("SensorName", SensorName), - new XElement("Cost", Cost.ToString())); - } + public XElement GetXElement => new("Sensor", + new XAttribute("Id", Id), + new XElement("SensorName", SensorName), + new XElement("Cost", Cost.ToString())); + } } diff --git a/SecuritySystem/SecuritySystemFileImplement/SecuritySystemFileImplement.csproj b/SecuritySystem/SecuritySystemFileImplement/SecuritySystemFileImplement.csproj index e205c75..d4e26d8 100644 --- a/SecuritySystem/SecuritySystemFileImplement/SecuritySystemFileImplement.csproj +++ b/SecuritySystem/SecuritySystemFileImplement/SecuritySystemFileImplement.csproj @@ -18,4 +18,8 @@ + + + + diff --git a/SecuritySystem/SecuritySystemListImplement/Implements/BackUpInfo.cs b/SecuritySystem/SecuritySystemListImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..b5ce189 --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/Implements/BackUpInfo.cs @@ -0,0 +1,22 @@ +using SecuritySystemContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + throw new NotImplementedException(); + } + + public Type? GetTypeByModelInterface(string modelInterfaceName) + { + throw new NotImplementedException(); + } + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/ListImplementationExtension.cs b/SecuritySystem/SecuritySystemListImplement/ListImplementationExtension.cs new file mode 100644 index 0000000..e90353c --- /dev/null +++ b/SecuritySystem/SecuritySystemListImplement/ListImplementationExtension.cs @@ -0,0 +1,34 @@ +using SecuritySystemContracts.DI; +using SecuritySystemContracts.StoragesContracts; +using SecuritySystemListImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement +{ + public class ListImplementationExtension : IImplementationExtension + { + public int Priority => 0; + + public void RegisterServices() + { + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + } + } + +} diff --git a/SecuritySystem/SecuritySystemListImplement/Models/MessageInfo.cs b/SecuritySystem/SecuritySystemListImplement/Models/MessageInfo.cs index 86695cc..e23c6bc 100644 --- a/SecuritySystem/SecuritySystemListImplement/Models/MessageInfo.cs +++ b/SecuritySystem/SecuritySystemListImplement/Models/MessageInfo.cs @@ -12,6 +12,8 @@ namespace SecuritySystemListImplement.Models { public class MessageInfo : IMessageInfoModel { + public int Id { get; private set; } + public string MessageId { get; private set; } = string.Empty; public int? ClientId { get; private set; } diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Order.cs b/SecuritySystem/SecuritySystemListImplement/Models/Order.cs index dbaef91..662ae2c 100644 --- a/SecuritySystem/SecuritySystemListImplement/Models/Order.cs +++ b/SecuritySystem/SecuritySystemListImplement/Models/Order.cs @@ -12,73 +12,73 @@ using System.Threading.Tasks; namespace SecuritySystemListImplement.Models { - //класс, реализующий интерфейс модели заказа - public class Order : IOrderModel - { - //методы set сделали приватными, чтобы исключить неразрешённые манипуляции - public int Id { get; private set; } + //класс, реализующий интерфейс модели заказа + public class Order : IOrderModel + { + //методы set сделали приватными, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } - public int ClientId { get; private set; } + public int ClientId { get; private set; } - public int? ImplementerId { get; private set; } + public int? ImplementerId { get; private set; } - public int SecureId { get; private set; } + public int SecureId { get; private set; } - public int Count { get; private set; } + public int Count { get; private set; } - public double Sum { get; private set; } + public double Sum { get; private set; } - public OrderStatus Status { get; private set; } + public OrderStatus Status { get; private set; } - public DateTime DateCreate { get; private set; } = DateTime.Now; + public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } + public DateTime? DateImplement { get; private set; } - public static Order? Create(OrderBindingModel? model) - { - if (model == null) - { - return null; - } + public static Order? Create(OrderBindingModel? model) + { + if (model == null) + { + return null; + } - return new Order() - { - Id = model.Id, - SecureId = model.SecureId, - ClientId = model.ClientId, - ImplementerId = model.ImplementerId, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; - } + return new Order() + { + Id = model.Id, + SecureId = model.SecureId, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement + }; + } - //метод изменения существующего объекта - public void Update(OrderBindingModel? model) - { - if (model == null) - { - return; - } + //метод изменения существующего объекта + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } - Status = model.Status; - DateImplement = model.DateImplement; - } + Status = model.Status; + DateImplement = model.DateImplement; + } - //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента - public OrderViewModel GetViewModel => new() - { - Id = Id, - SecureId = SecureId, - ClientId = ClientId, - ImplementerId = ImplementerId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement - }; - } + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public OrderViewModel GetViewModel => new() + { + Id = Id, + SecureId = SecureId, + ClientId = ClientId, + ImplementerId = ImplementerId, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; + } } diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs b/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs index 1694c14..b5d1959 100644 --- a/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs +++ b/SecuritySystem/SecuritySystemListImplement/Models/Secure.cs @@ -9,55 +9,55 @@ using System.Threading.Tasks; namespace SecuritySystemListImplement.Models { - //класс реализующий интерфейс модели изделия - public class Secure : ISecureModel - { - //методы set делаем приватным, чтобы исключить неразрешённые манипуляции - public int Id { get; private set; } + //класс, реализующий интерфейс модели изделия + public class Secure : ISecureModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } - public string SecureName { get; private set; } = string.Empty; + public string SecureName { get; private set; } = string.Empty; - public double Price { get; private set; } + public double Price { get; private set; } - public Dictionary SecureSensors { get; private set; } = new Dictionary(); + public Dictionary SecureSensors { get; private set; } = new Dictionary(); - //метод для создания объекта от класса-компонента на основе класса-BindingModel - public static Secure? Create(SecureBindingModel? model) - { - if (model == null) - { - return null; - } + //метод для создания объекта от класса-компонента на основе класса-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 - }; - } + return new Secure() + { + Id = model.Id, + SecureName = model.SecureName, + Price = model.Price, + SecureSensors = model.SecureSensors + }; + } - //метод изменения существующего объекта - public void Update(SecureBindingModel? model) - { - if (model == null) - { - return; - } + //метод изменения существующего объекта + public void Update(SecureBindingModel? model) + { + if (model == null) + { + return; + } - SecureName = model.SecureName; - Price = model.Price; - SecureSensors = model.SecureSensors; - } + 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 + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public SecureViewModel GetViewModel => new() + { + Id = Id, + SecureName = SecureName, + Price = Price, + SecureSensors = SecureSensors + }; + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs b/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs index 29735cf..7b169f9 100644 --- a/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs +++ b/SecuritySystem/SecuritySystemListImplement/Models/Sensor.cs @@ -9,50 +9,50 @@ using System.Threading.Tasks; namespace SecuritySystemListImplement.Models { - //реализация интерфейса модели заготовки - public class Sensor : ISensorModel - { - //методы set делаем приватным, чтобы исключить неразрешённые манипуляции - public int Id { get; private set; } + //реализация интерфейса модели заготовки + public class Sensor : ISensorModel + { + //методы set делаем приватным, чтобы исключить неразрешённые манипуляции + public int Id { get; private set; } - public string SensorName { get; private set; } = string.Empty; + public string SensorName { get; private set; } = string.Empty; - public double Cost { get; private set; } + public double Cost { get; private set; } - //метод для создания объекта от класса-компонента на основе класса-BindingModel - public static Sensor? Create(SensorBindingModel? model) - { - if(model == null) - { - return null; - } + //метод для создания объекта от класса-компонента на основе класса-BindingModel + public static Sensor? Create(SensorBindingModel? model) + { + if (model == null) + { + return null; + } - return new Sensor() - { - Id = model.Id, - SensorName = model.SensorName, - Cost = model.Cost - }; - } + return new Sensor() + { + Id = model.Id, + SensorName = model.SensorName, + Cost = model.Cost + }; + } - //метод изменения существующего объекта - public void Update(SensorBindingModel? model) - { - if(model == null) - { - return; - } + //метод изменения существующего объекта + public void Update(SensorBindingModel? model) + { + if (model == null) + { + return; + } - SensorName = model.SensorName; - Cost = model.Cost; - } + SensorName = model.SensorName; + Cost = model.Cost; + } - //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента - public SensorViewModel GetViewModel => new() - { - Id = Id, - SensorName = SensorName, - Cost = Cost - }; - } -} \ No newline at end of file + //метод для создания объекта класса ViewModel на основе данных объекта класса-компонента + public SensorViewModel GetViewModel => new() + { + Id = Id, + SensorName = SensorName, + Cost = Cost + }; + } +} diff --git a/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj b/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj index 50856fd..cd74bdd 100644 --- a/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj +++ b/SecuritySystem/SecuritySystemListImplement/SecuritySystemListImplement.csproj @@ -22,4 +22,8 @@ + + + + diff --git a/SecuritySystem/Для бэкапа.zip b/SecuritySystem/Для бэкапа.zip new file mode 100644 index 0000000..f288f79 Binary files /dev/null and b/SecuritySystem/Для бэкапа.zip differ