From 2dcc0cab18bd7f86fd17864101c19a921d38ad12 Mon Sep 17 00:00:00 2001 From: shadowik Date: Sun, 14 May 2023 07:44:14 +0400 Subject: [PATCH 1/4] Final --- .gitignore | 3 + Pizzeria/Pizzeria/DataGridViewExtension.cs | 53 +++++++++ Pizzeria/Pizzeria/FormClients.cs | 8 +- Pizzeria/Pizzeria/FormComponents.cs | 21 ++-- Pizzeria/Pizzeria/FormImplementers.cs | 38 +++---- Pizzeria/Pizzeria/FormMail.cs | 12 +- Pizzeria/Pizzeria/FormMain.Designer.cs | 24 ++-- Pizzeria/Pizzeria/FormMain.cs | 98 ++++++++--------- Pizzeria/Pizzeria/FormPizza.cs | 64 +++++------ Pizzeria/Pizzeria/FormPizzas.cs | 39 ++----- Pizzeria/Pizzeria/Program.cs | 82 +++++++------- .../BusinessLogics/BackUpLogic.cs | 103 ++++++++++++++++++ .../Attributes/ColumnAttribute.cs | 25 +++++ .../Attributes/GridViewAutoSize.cs | 27 +++++ .../BindingModels/BackUpSaveBinidngModel.cs | 13 +++ .../BindingModels/MessageInfoBindingModel.cs | 1 + .../BusinessLogicsContracts/IBackUpLogic.cs | 14 +++ .../PizzeriaContracts/DI/DependencyManager.cs | 66 +++++++++++ .../DI/IDependencyContainer.cs | 40 +++++++ .../DI/IImplementationExtension.cs | 17 +++ .../DI/ServiceDependencyContainer.cs | 62 +++++++++++ .../DI/ServiceProviderLoader.cs | 55 ++++++++++ .../PizzeriaContracts.csproj | 4 + .../StoragesContracts/IBackUpInfo.cs | 15 +++ .../ViewModels/ClientViewModel.cs | 11 +- .../ViewModels/ComponentViewModel.cs | 8 +- .../ViewModels/ImplementerViewModel.cs | 12 +- .../ViewModels/MessageInfoViewModel.cs | 16 ++- .../ViewModels/OrderViewModel.cs | 26 +++-- .../ViewModels/PizzaViewModel.cs | 12 +- .../Models/IMessageInfoModel.cs | 2 +- .../ImplementationExtension.cs | 27 +++++ .../Implements/BackUpInfo.cs | 32 ++++++ .../Models/Client.cs | 6 + .../Models/Component.cs | 8 ++ .../Models/Implementer.cs | 7 ++ .../Models/MessageInfo.cs | 12 +- .../PizzeriaDatabaseImplement/Models/Order.cs | 11 ++ .../PizzeriaDatabaseImplement/Models/Pizza.cs | 9 ++ .../PizzeriaDatabaseImplement - Backup.csproj | 25 +++++ .../PizzeriaDatabaseImplement.csproj | 6 + 41 files changed, 857 insertions(+), 257 deletions(-) create mode 100644 Pizzeria/Pizzeria/DataGridViewExtension.cs create mode 100644 Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs create mode 100644 Pizzeria/PizzeriaContracts/Attributes/ColumnAttribute.cs create mode 100644 Pizzeria/PizzeriaContracts/Attributes/GridViewAutoSize.cs create mode 100644 Pizzeria/PizzeriaContracts/BindingModels/BackUpSaveBinidngModel.cs create mode 100644 Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 Pizzeria/PizzeriaContracts/DI/DependencyManager.cs create mode 100644 Pizzeria/PizzeriaContracts/DI/IDependencyContainer.cs create mode 100644 Pizzeria/PizzeriaContracts/DI/IImplementationExtension.cs create mode 100644 Pizzeria/PizzeriaContracts/DI/ServiceDependencyContainer.cs create mode 100644 Pizzeria/PizzeriaContracts/DI/ServiceProviderLoader.cs create mode 100644 Pizzeria/PizzeriaContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/ImplementationExtension.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/Implements/BackUpInfo.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement - Backup.csproj diff --git a/.gitignore b/.gitignore index ca1c7a3..38a89f9 100644 --- a/.gitignore +++ b/.gitignore @@ -398,3 +398,6 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml + +/Pizzeria/ImplementationExtensions +/BankExecutor \ No newline at end of file diff --git a/Pizzeria/Pizzeria/DataGridViewExtension.cs b/Pizzeria/Pizzeria/DataGridViewExtension.cs new file mode 100644 index 0000000..ce7d461 --- /dev/null +++ b/Pizzeria/Pizzeria/DataGridViewExtension.cs @@ -0,0 +1,53 @@ +using PizzeriaContracts.Attributes; +using System; +using System.Collections.Generic; + +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaView +{ + internal 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/Pizzeria/Pizzeria/FormClients.cs b/Pizzeria/Pizzeria/FormClients.cs index 6174f8d..6f53349 100644 --- a/Pizzeria/Pizzeria/FormClients.cs +++ b/Pizzeria/Pizzeria/FormClients.cs @@ -35,13 +35,7 @@ namespace PizzeriaView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) diff --git a/Pizzeria/Pizzeria/FormComponents.cs b/Pizzeria/Pizzeria/FormComponents.cs index 7d5b4d9..d4ee42b 100644 --- a/Pizzeria/Pizzeria/FormComponents.cs +++ b/Pizzeria/Pizzeria/FormComponents.cs @@ -2,6 +2,7 @@ using Pizzeria; using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.DI; using System; using System.Collections.Generic; using System.ComponentModel; @@ -51,28 +52,22 @@ namespace PizzeriaView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { LoadData(); - } } } } diff --git a/Pizzeria/Pizzeria/FormImplementers.cs b/Pizzeria/Pizzeria/FormImplementers.cs index bcf3035..3a8f68b 100644 --- a/Pizzeria/Pizzeria/FormImplementers.cs +++ b/Pizzeria/Pizzeria/FormImplementers.cs @@ -2,6 +2,7 @@ using Pizzeria; using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.DI; using System; using System.Collections.Generic; using System.ComponentModel; @@ -28,15 +29,8 @@ namespace PizzeriaView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка исполнителей"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка исполнителей"); } catch (Exception ex) { @@ -51,28 +45,22 @@ namespace PizzeriaView } private void buttonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) - { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + 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(FormImplementer)); - if (service is FormImplementer form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } - } + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } } } private void buttonDel_Click(object sender, EventArgs e) diff --git a/Pizzeria/Pizzeria/FormMail.cs b/Pizzeria/Pizzeria/FormMail.cs index 550e925..bc5a368 100644 --- a/Pizzeria/Pizzeria/FormMail.cs +++ b/Pizzeria/Pizzeria/FormMail.cs @@ -29,16 +29,8 @@ namespace PizzeriaView { try { - var list = _logic.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("Загрузка почтовых собщений"); + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка почтовых собщений"); } catch (Exception ex) { diff --git a/Pizzeria/Pizzeria/FormMain.Designer.cs b/Pizzeria/Pizzeria/FormMain.Designer.cs index 520be00..c8851c9 100644 --- a/Pizzeria/Pizzeria/FormMain.Designer.cs +++ b/Pizzeria/Pizzeria/FormMain.Designer.cs @@ -39,13 +39,14 @@ this.componentPizzaToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.ordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.почтаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.buttonCreateOrder = new System.Windows.Forms.Button(); this.buttonTakeOrderInWork = new System.Windows.Forms.Button(); this.buttonOrderReady = new System.Windows.Forms.Button(); this.buttonIssuedOrder = new System.Windows.Forms.Button(); this.buttonRef = new System.Windows.Forms.Button(); - this.почтаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.создатьБекапToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -57,7 +58,8 @@ this.bookToolStripMenuItem, this.отчётыToolStripMenuItem, this.запускРаботToolStripMenuItem, - this.почтаToolStripMenuItem}); + this.почтаToolStripMenuItem, + this.создатьБекапToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2); @@ -142,6 +144,13 @@ this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.startWorkToolStripMenuItem_Click); // + // почтаToolStripMenuItem + // + this.почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + this.почтаToolStripMenuItem.Size = new System.Drawing.Size(53, 20); + this.почтаToolStripMenuItem.Text = "Почта"; + this.почтаToolStripMenuItem.Click += new System.EventHandler(this.mailToolStripMenuItem_Click); + // // dataGridView // this.dataGridView.AllowUserToAddRows = false; @@ -211,12 +220,12 @@ this.buttonRef.UseVisualStyleBackColor = true; this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); // - // почтаToolStripMenuItem + // создатьБекапToolStripMenuItem // - this.почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; - this.почтаToolStripMenuItem.Size = new System.Drawing.Size(53, 20); - this.почтаToolStripMenuItem.Text = "Почта"; - this.почтаToolStripMenuItem.Click += new System.EventHandler(this.mailToolStripMenuItem_Click); + this.создатьБекапToolStripMenuItem.Name = "создатьБекапToolStripMenuItem"; + this.создатьБекапToolStripMenuItem.Size = new System.Drawing.Size(97, 20); + this.создатьБекапToolStripMenuItem.Text = "Создать Бекап"; + this.создатьБекапToolStripMenuItem.Click += new System.EventHandler(this.createBackUpToolStripMenuItem_Click); // // FormMain // @@ -263,5 +272,6 @@ private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem почтаToolStripMenuItem; + private ToolStripMenuItem создатьБекапToolStripMenuItem; } } \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormMain.cs b/Pizzeria/Pizzeria/FormMain.cs index 890160f..f4c2be7 100644 --- a/Pizzeria/Pizzeria/FormMain.cs +++ b/Pizzeria/Pizzeria/FormMain.cs @@ -3,6 +3,7 @@ using Pizzeria; using PizzeriaBusinessLogic.BusinessLogics; using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.DI; namespace PizzeriaView { @@ -12,13 +13,15 @@ namespace PizzeriaView private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; 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(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; + _backUpLogic = backUpLogic; } private void FormMain_Load(object sender, EventArgs e) { @@ -28,17 +31,7 @@ namespace PizzeriaView { try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["PizzaId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientEmail"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["PizzaName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) @@ -49,28 +42,19 @@ namespace PizzeriaView } private void IngridentsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void PizzasToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzas)); - if (service is FormPizzas form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + 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 ButtonTakeOrderInWork_Click(object sender, EventArgs e) { @@ -165,52 +149,62 @@ namespace PizzeriaView private void ComponentPizzaToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportPizzaComponents)); - if (service is FormReportPizzaComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ClientToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void employersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void startWorkToolStripMenuItem_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 mailToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMail)); - if (service is FormMail form) + var form = DependencyManager.Instance.Resolve(); + 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/Pizzeria/Pizzeria/FormPizza.cs b/Pizzeria/Pizzeria/FormPizza.cs index 64e3e1e..d929b22 100644 --- a/Pizzeria/Pizzeria/FormPizza.cs +++ b/Pizzeria/Pizzeria/FormPizza.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging; using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaContracts.SearchModels; +using PizzeriaContracts.DI; namespace PizzeriaView @@ -74,53 +75,44 @@ namespace PizzeriaView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzaComponent)); - if (service is FormPizzaComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { + return; + } + _logger.LogInformation("Добавление нового ингридиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + if (_PizzaComponents.ContainsKey(form.Id)) + { + _PizzaComponents[form.Id] = (form.ComponentModel, + form.Count); + } + else + { + _PizzaComponents.Add(form.Id, (form.ComponentModel, + form.Count)); + } + LoadData(); + } + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var form = DependencyManager.Instance.Resolve(); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _PizzaComponents[id].Item2; if (form.ShowDialog() == DialogResult.OK) { if (form.ComponentModel == null) { return; } - _logger.LogInformation("Добавление нового ингредиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); - if (_PizzaComponents.ContainsKey(form.Id)) - { - _PizzaComponents[form.Id] = (form.ComponentModel, - form.Count); - } - else - { - _PizzaComponents.Add(form.Id, (form.ComponentModel, - form.Count)); - } + _logger.LogInformation("Изменение ингридиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + _PizzaComponents[form.Id] = (form.ComponentModel, form.Count); LoadData(); } } } - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzaComponent)); - if (service is FormPizzaComponent form) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _PizzaComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) - { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение ингредиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); - _PizzaComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); - } - } - } - } private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) diff --git a/Pizzeria/Pizzeria/FormPizzas.cs b/Pizzeria/Pizzeria/FormPizzas.cs index cf2cc73..73b180c 100644 --- a/Pizzeria/Pizzeria/FormPizzas.cs +++ b/Pizzeria/Pizzeria/FormPizzas.cs @@ -4,13 +4,7 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using PizzeriaContracts.DI; namespace PizzeriaView { @@ -32,15 +26,7 @@ namespace PizzeriaView { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["PizzaComponents"].Visible = false; - dataGridView.Columns["PizzaName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка пиццы"); } catch (Exception ex) @@ -51,27 +37,20 @@ namespace PizzeriaView } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizza)); - if (service is FormPizza form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizza)); - if (service is FormPizza form) - { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { + LoadData(); } } } diff --git a/Pizzeria/Pizzeria/Program.cs b/Pizzeria/Pizzeria/Program.cs index a515b40..7e9ba62 100644 --- a/Pizzeria/Pizzeria/Program.cs +++ b/Pizzeria/Pizzeria/Program.cs @@ -13,6 +13,7 @@ using System.Drawing; using PizzeriaBusinessLogic.Implements; using PizzeriaBusinessLogic.OfficePackage; using Microsoft.EntityFrameworkCore.Design; +using PizzeriaContracts.DI; namespace Pizzeria { @@ -29,12 +30,10 @@ namespace Pizzeria // 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(); + InitDependency(); try { - var mailSender = _serviceProvider.GetService(); + var mailSender = DependencyManager.Instance.Resolve(); mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, @@ -45,63 +44,58 @@ namespace Pizzeria PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) }); - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + // todo Delete email to fine work + //var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); } catch (Exception ex) { - var logger = _serviceProvider.GetService(); + var logger = DependencyManager.Instance.Resolve(); logger?.LogError(ex, "Mails Problem"); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) + private static void InitDependency() { - services.AddLogging(option => + DependencyManager.InitDependency(); + + DependencyManager.Instance.AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - 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(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); + DependencyManager.Instance.RegisterType(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - - 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(); - 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/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..13212f1 --- /dev/null +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,103 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.StoragesContracts; +using PizzeriaDataModels; +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 PizzeriaBusinessLogic.BusinessLogics +{ + 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) + { + 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; + } + 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/Pizzeria/PizzeriaContracts/Attributes/ColumnAttribute.cs b/Pizzeria/PizzeriaContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..3e1ba95 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,25 @@ +namespace PizzeriaContracts.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + 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; } + + 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; + } + } +} diff --git a/Pizzeria/PizzeriaContracts/Attributes/GridViewAutoSize.cs b/Pizzeria/PizzeriaContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..4dfa873 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + + None = 1, + + ColumnHeader = 2, + + AllCellsExceptHeader = 4, + + AllCells = 6, + + DisplayedCellsExceptHeader = 8, + + DisplayedCells = 10, + + Fill = 16 + } +} diff --git a/Pizzeria/PizzeriaContracts/BindingModels/BackUpSaveBinidngModel.cs b/Pizzeria/PizzeriaContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..d3d6d1e --- /dev/null +++ b/Pizzeria/PizzeriaContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/Pizzeria/PizzeriaContracts/BindingModels/MessageInfoBindingModel.cs b/Pizzeria/PizzeriaContracts/BindingModels/MessageInfoBindingModel.cs index 21b5346..4dda212 100644 --- a/Pizzeria/PizzeriaContracts/BindingModels/MessageInfoBindingModel.cs +++ b/Pizzeria/PizzeriaContracts/BindingModels/MessageInfoBindingModel.cs @@ -15,5 +15,6 @@ namespace PizzeriaContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; public DateTime DateDelivery { get; set; } + public int Id => throw new NotImplementedException(); } } diff --git a/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IBackUpLogic.cs b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..82a4f2f --- /dev/null +++ b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using PizzeriaContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/Pizzeria/PizzeriaContracts/DI/DependencyManager.cs b/Pizzeria/PizzeriaContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..19c4a59 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/DI/DependencyManager.cs @@ -0,0 +1,66 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.DI +{ + public class DependencyManager + { + private readonly IDependencyContainer _dependencyManager; + + private static DependencyManager? _manager; + + private static readonly object _locjObject = new(); + + private DependencyManager() + { + _dependencyManager = new ServiceDependencyContainer(); + } + + 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/Pizzeria/PizzeriaContracts/DI/IDependencyContainer.cs b/Pizzeria/PizzeriaContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..a05eb77 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/DI/IDependencyContainer.cs @@ -0,0 +1,40 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.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/Pizzeria/PizzeriaContracts/DI/IImplementationExtension.cs b/Pizzeria/PizzeriaContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..ae8735e --- /dev/null +++ b/Pizzeria/PizzeriaContracts/DI/IImplementationExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.DI +{ + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/Pizzeria/PizzeriaContracts/DI/ServiceDependencyContainer.cs b/Pizzeria/PizzeriaContracts/DI/ServiceDependencyContainer.cs new file mode 100644 index 0000000..3b51dd7 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/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 PizzeriaContracts.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/Pizzeria/PizzeriaContracts/DI/ServiceProviderLoader.cs b/Pizzeria/PizzeriaContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..80b8801 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.DI +{ + public 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/Pizzeria/PizzeriaContracts/PizzeriaContracts.csproj b/Pizzeria/PizzeriaContracts/PizzeriaContracts.csproj index 84e1e90..d9dbbe7 100644 --- a/Pizzeria/PizzeriaContracts/PizzeriaContracts.csproj +++ b/Pizzeria/PizzeriaContracts/PizzeriaContracts.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/Pizzeria/PizzeriaContracts/StoragesContracts/IBackUpInfo.cs b/Pizzeria/PizzeriaContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..b8e1da3 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/Pizzeria/PizzeriaContracts/ViewModels/ClientViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/ClientViewModel.cs index acfb889..9c6c05e 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/ClientViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/ClientViewModel.cs @@ -1,7 +1,7 @@ -using PizzeriaDataModels.Models; +using PizzeriaContracts.Attributes; using System; using System.Collections.Generic; -using System.ComponentModel; +using PizzeriaDataModels.Models; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,15 +10,16 @@ namespace PizzeriaContracts.ViewModels { public class ClientViewModel : IClientModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО клиента")] + [Column(title: "ФИО клиента", width: 150)] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] + [Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 150)] public string Password { get; set; } = string.Empty; } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/ComponentViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/ComponentViewModel.cs index 1844231..78ef9ec 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/ComponentViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/ComponentViewModel.cs @@ -1,14 +1,16 @@ -using PizzeriaDataModels.Models; +using PizzeriaContracts.Attributes; +using PizzeriaDataModels.Models; using System.ComponentModel; namespace PizzeriaContracts.ViewModels { public class ComponentViewModel : IComponentModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название ингредиента")] + [Column(title: "Название ингридиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ComponentName { get; set; } = string.Empty; - [DisplayName("Цена")] + [Column(title: "Цена", width: 150)] public double Cost { get; set; } } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs index 8f5e29c..7436e02 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs @@ -1,4 +1,5 @@ -using PizzeriaDataModels.Models; +using PizzeriaContracts.Attributes; +using PizzeriaDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,18 +11,19 @@ namespace PizzeriaContracts.ViewModels { public class ImplementerViewModel : IImplementerModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("ФИО исполнителя")] + [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string ImplementerFIO { get; set; } = string.Empty; - [DisplayName("Пароль")] + [Column(title: "Пароль", width: 100)] public string Password { get; set; } = string.Empty; - [DisplayName("Стаж работы")] + [Column(title: "Стаж работы", width: 60)] public int WorkExperience { get; set; } - [DisplayName("Квалификация")] + [Column(title: "Квалификация", width: 60)] public int Qualification { get; set; } } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/MessageInfoViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/MessageInfoViewModel.cs index 1e0912d..4730faa 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/MessageInfoViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/MessageInfoViewModel.cs @@ -1,4 +1,5 @@ -using PizzeriaDataModels.Models; +using PizzeriaContracts.Attributes; +using PizzeriaDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -10,20 +11,25 @@ namespace PizzeriaContracts.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: 120)] public DateTime DateDelivery { get; set; } - [DisplayName("Заголовок")] + [Column(title: "Заголовок", width: 120)] public string Subject { get; set; } = string.Empty; - [DisplayName("Текст")] + [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string Body { get; set; } = string.Empty; } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs index 6a4dd8d..0ebb043 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ -using PizzeriaDataModels.Enums; +using PizzeriaContracts.Attributes; +using PizzeriaDataModels.Enums; using PizzeriaDataModels.Models; using System.ComponentModel; @@ -6,38 +7,43 @@ namespace PizzeriaContracts.ViewModels { public class OrderViewModel : IOrderModel { - [DisplayName("Номер")] + [Column(title: "Номер", width: 90)] public int Id { get; set; } + [Column(visible: false)] public int ClientId { get; set; } - [DisplayName("Имя клиента")] + [Column(title: "Имя клиента", width: 190)] public string? ClientFIO { get; set; } = string.Empty; + [Column(visible: false)] public string ClientEmail { get; set; } = string.Empty; + [Column(visible: false)] public int PizzaId { get; set; } - [DisplayName("Пицца")] + [Column(title: "Пицца", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string PizzaName { get; set; } = string.Empty; + [Column(visible: false)] public int? ImplementerId { get; set; } - [DisplayName("Исполнитель")] + + [Column(title: "Исполнитель", width: 150)] public string? ImplementerFIO { get; set; } = null; - [DisplayName("Количество")] + [Column(title: "Количество", width: 100)] public int Count { get; set; } - [DisplayName("Сумма")] + [Column(title: "Сумма", width: 120)] public double Sum { get; set; } - [DisplayName("Статус")] + [Column(title: "Статус", width: 70)] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; - [DisplayName("Дата создания")] + [Column(title: "Дата создания", width: 120)] public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] + [Column(title: "Дата выполнения", width: 120)] public DateTime? DateImplement { get; set; } } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/PizzaViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/PizzaViewModel.cs index f7e8984..00de876 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/PizzaViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/PizzaViewModel.cs @@ -1,15 +1,21 @@ -using PizzeriaDataModels.Models; +using PizzeriaContracts.Attributes; +using PizzeriaDataModels.Models; using System.ComponentModel; namespace PizzeriaContracts.ViewModels { public class PizzaViewModel : IPizzaModel { + [Column(visible: false)] public int Id { get; set; } - [DisplayName("Название пиццы")] + + [Column(title: "Название пиццы", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] public string PizzaName { get; set; } = string.Empty; - [DisplayName("Цена")] + + [Column(title: "Цена", width: 70)] public double Price { get; set; } + + [Column(visible: false)] public Dictionary PizzaComponents { get;set;} = new(); } } diff --git a/Pizzeria/PizzeriaDataModels/Models/IMessageInfoModel.cs b/Pizzeria/PizzeriaDataModels/Models/IMessageInfoModel.cs index f029ed7..4a54253 100644 --- a/Pizzeria/PizzeriaDataModels/Models/IMessageInfoModel.cs +++ b/Pizzeria/PizzeriaDataModels/Models/IMessageInfoModel.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace PizzeriaDataModels.Models { - public interface IMessageInfoModel + public interface IMessageInfoModel : IId { string MessageId { get; } int? ClientId { get; } diff --git a/Pizzeria/PizzeriaDatabaseImplement/ImplementationExtension.cs b/Pizzeria/PizzeriaDatabaseImplement/ImplementationExtension.cs new file mode 100644 index 0000000..4b9d41f --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/ImplementationExtension.cs @@ -0,0 +1,27 @@ +using PizzeriaContracts.DI; +using PizzeriaContracts.StoragesContracts; +using PizzeriaDatabaseImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaDatabaseImplement +{ + public class ImplementationExtension : IImplementationExtension + { + public int Priority => 3; + + 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/Pizzeria/PizzeriaDatabaseImplement/Implements/BackUpInfo.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..74ca581 --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,32 @@ +using PizzeriaContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new PizzeriaDatabase(); + 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/Pizzeria/PizzeriaDatabaseImplement/Models/Client.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Client.cs index 8591ec2..e76bf42 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Client.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Client.cs @@ -7,21 +7,27 @@ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PizzeriaDatabaseImplement.Models { + [DataContract] public class Client : IClientModel { + [DataMember] public int Id { get; set; } + [DataMember] [Required] public string ClientFIO { get; set; } = string.Empty; + [DataMember] [Required] public string Email { get; set; } = string.Empty; + [DataMember] [Required] public string Password { get; set; } = string.Empty; diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Component.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Component.cs index 8f01acb..a4710d1 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Component.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Component.cs @@ -3,16 +3,24 @@ using PizzeriaContracts.ViewModels; using PizzeriaDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace PizzeriaDatabaseImplement.Models { + [DataContract] public class Component : IComponentModel { + [DataMember] public int Id { get; private set; } + + [DataMember] [Required] public string ComponentName { get; private set; } = string.Empty; + + [DataMember] [Required] public double Cost { get; set; } + [ForeignKey("ComponentId")] public virtual List PizzaComponents { get; set; } = new(); public static Component? Create(ComponentBindingModel model) diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs index 3e5b372..c36e7b3 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs @@ -8,22 +8,29 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace PizzeriaDatabaseImplement.Models { + [DataContract] public class Implementer : IImplementerModel { + [DataMember] public int Id { get; set; } + [DataMember] [Required] public string ImplementerFIO { get; set; } = string.Empty; + [DataMember] [Required] public string Password { get; set; } = string.Empty; + [DataMember] [Required] public int WorkExperience { get; set; } + [DataMember] [Required] public int Qualification { get; set; } diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/MessageInfo.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/MessageInfo.cs index 00bb1ee..e4886e3 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/MessageInfo.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/MessageInfo.cs @@ -8,28 +8,38 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Runtime.Serialization; namespace PizzeriaDatabaseImplement.Models { public class MessageInfo : IMessageInfoModel { + [NotMapped] + public int Id { get; private set; } + + [DataMember] [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string MessageId { get; set; } = string.Empty; + [DataMember] public int? ClientId { get; set; } public virtual Client? Client { get; set; } - + + [DataMember] [Required] public string SenderName { get; set; } = string.Empty; + [DataMember] [Required] public DateTime DateDelivery { get; set; } + [DataMember] [Required] public string Subject { get; set; } = string.Empty; + [DataMember] [Required] public string Body { get; set; } = string.Empty; diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs index b15dc81..096b084 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs @@ -6,41 +6,52 @@ 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 PizzeriaDatabaseImplement.Models { + [DataContract] public class Order { + [DataMember] public int Id { get; private set; } + [DataMember] [Required] public int ClientId { get; private set; } public virtual Client Client { get; private set; } = new(); + [DataMember] [Required] public int PizzaId { get; private set; } public virtual Pizza Pizza { get; set; } = new(); + [DataMember] public int? ImplementerId { get; private set; } public virtual Implementer? Implementer { get; set; } = new(); + [DataMember] [Required] public int Count { get; private set; } + [DataMember] [Required] public double Sum { get; private set; } + [DataMember] [Required] public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [DataMember] [Required] public DateTime DateCreate { get; private set; } = DateTime.Now; + [DataMember] public DateTime? DateImplement { get; private set; } public static Order Create(PizzeriaDatabase context, OrderBindingModel model) diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Pizza.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Pizza.cs index 87acbff..e8334c7 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Pizza.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Pizza.cs @@ -3,18 +3,27 @@ using PizzeriaContracts.ViewModels; using PizzeriaDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; namespace PizzeriaDatabaseImplement.Models { + [DataContract] public class Pizza : IPizzaModel { + [DataMember] public int Id { get; set; } + + [DataMember] [Required] public string PizzaName { get; set; } = string.Empty; + + [DataMember] [Required] public double Price { get; set; } private Dictionary? _pizzaComponents = null; + + [DataMember] [NotMapped] public Dictionary PizzaComponents { diff --git a/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement - Backup.csproj b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement - Backup.csproj new file mode 100644 index 0000000..fe9daa0 --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement - Backup.csproj @@ -0,0 +1,25 @@ + + + + net6.0 + enable + enable + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement.csproj b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement.csproj index 738b64b..e09e085 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement.csproj +++ b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabaseImplement.csproj @@ -20,4 +20,10 @@ + + + + + + From f6bc620bc72e5e5dcd57ec7840944416e6a6babd Mon Sep 17 00:00:00 2001 From: shadowik Date: Wed, 17 May 2023 10:20:24 +0400 Subject: [PATCH 2/4] Fixes --- .../PizzeriaDatabaseImplement/Models/Order.cs | 3 +- .../DataFileSingleton.cs | 16 +++- .../ImplementationExtension.cs | 27 ++++++ .../Implements/BackUpInfo.cs | 42 +++++++++ .../Implements/ClientStorage.cs | 82 +++++++++++++++++ .../Implements/MessageInfoStorage.cs | 53 +++++++++++ .../PizzeriaFileImplement/Models/Client.cs | 79 ++++++++++++++++ .../Models/Implementer.cs | 86 ++++++++++++++++++ .../Models/MessageInfo.cs | 89 +++++++++++++++++++ .../PizzeriaFileImplement.csproj | 4 + 10 files changed, 479 insertions(+), 2 deletions(-) create mode 100644 Pizzeria/PizzeriaFileImplement/ImplementationExtension.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Implements/BackUpInfo.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Implements/ClientStorage.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Implements/MessageInfoStorage.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Models/Client.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Models/Implementer.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Models/MessageInfo.cs diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs index 096b084..6198ea0 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs @@ -1,6 +1,7 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.ViewModels; using PizzeriaDataModels.Enums; +using PizzeriaDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -13,7 +14,7 @@ using System.Threading.Tasks; namespace PizzeriaDatabaseImplement.Models { [DataContract] - public class Order + public class Order : IOrderModel { [DataMember] public int Id { get; private set; } diff --git a/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs b/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs index 59ad9a4..337ebc1 100644 --- a/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs +++ b/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs @@ -9,10 +9,16 @@ namespace PizzeriaFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string PizzaFileName = "Pizza.xml"; + private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfos.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Pizzas { get; private set; } - + public List Clients { get; private set; } + public List Implementers { get; private set; } + public List MessageInfos { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -24,11 +30,19 @@ namespace PizzeriaFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SavePizzas() => SaveData(Pizzas, PizzaFileName, "Pizzas", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + + public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessageInfos() => SaveData(MessageInfos, MessageInfoFileName, "MessageInfos", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Pizzas = LoadData(PizzaFileName, "Pizza", x => Pizza.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; + Implementers = LoadData(ImplementerFileName, "Client", x => Implementer.Create(x)!)!; + MessageInfos = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/Pizzeria/PizzeriaFileImplement/ImplementationExtension.cs b/Pizzeria/PizzeriaFileImplement/ImplementationExtension.cs new file mode 100644 index 0000000..f4ced5e --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/ImplementationExtension.cs @@ -0,0 +1,27 @@ +using PizzeriaContracts.DI; +using PizzeriaContracts.StoragesContracts; +using PizzeriaFileImplement.Implements; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaFileImplement +{ + public class ImplementationExtension : 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/Pizzeria/PizzeriaFileImplement/Implements/BackUpInfo.cs b/Pizzeria/PizzeriaFileImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..9b301ed --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Implements/BackUpInfo.cs @@ -0,0 +1,42 @@ +using PizzeriaContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using static System.Net.Mime.MediaTypeNames; + +namespace PizzeriaFileImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + private readonly DataFileSingleton source; + private readonly PropertyInfo[] sourceProperties; + public BackUpInfo() + { + source = DataFileSingleton.GetInstance(); + sourceProperties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); + } + public List? GetList() where T : class, new() + { + var requredType = typeof(T); + return (List?)sourceProperties.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == requredType) + ?.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/Pizzeria/PizzeriaFileImplement/Implements/ClientStorage.cs b/Pizzeria/PizzeriaFileImplement/Implements/ClientStorage.cs new file mode 100644 index 0000000..c75b180 --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Implements/ClientStorage.cs @@ -0,0 +1,82 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StoragesContracts; +using PizzeriaContracts.ViewModels; +using PizzeriaFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaFileImplement.Implements +{ + public class ClientStorage : IClientStorage + { + private readonly DataFileSingleton source; + public ClientStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.Clients.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ClientSearchModel model) + { + if(string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email)) + { + return new(); + } + return source.Clients.Where(x => (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO.Contains(model.ClientFIO)) || + (!string.IsNullOrEmpty(model.Email) && x.Email.Contains(model.Email))).Select(x => x.GetViewModel).ToList(); + } + public ClientViewModel? GetElement(ClientSearchModel model) + { + if (!model.Id.HasValue && string.IsNullOrEmpty(model.ClientFIO) && (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))) + { + return new(); + } + return source.Clients.FirstOrDefault(x => (!model.Id.HasValue && x.Id == model.Id) || + (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password))) + ?.GetViewModel; + } + public ClientViewModel? Insert(ClientBindingModel model) + { + model.Id = source.Clients.Count > 0 ? source.Clients.Max(x => x.Id) + 1 : 1; + var newClient = Client.Create(model); + if(newClient == null) + { + return null; + } + source.Clients.Add(newClient); + source.SaveClients(); + return newClient.GetViewModel; + } + public ClientViewModel? Update(ClientBindingModel model) + { + model.Id = source.Clients.Count > 0 ? source.Clients.Max(x => x.Id) + 1 : 1; + var client = source.Clients.FirstOrDefault(x=> x.Id == model.Id); + if(client == null) + { + return null; + } + + client.Update(model); + source.SaveClients(); + return client.GetViewModel; + } + public ClientViewModel? Delete(ClientBindingModel model) + { + var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + if(client != null) + { + source.Clients.Remove(client); + source.SaveClients(); + return client.GetViewModel; + } + return null; + } + } +} diff --git a/Pizzeria/PizzeriaFileImplement/Implements/MessageInfoStorage.cs b/Pizzeria/PizzeriaFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..ac89183 --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StoragesContracts; +using PizzeriaContracts.ViewModels; +using PizzeriaFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + return source.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + return source.MessageInfos.FirstOrDefault(x=>x.MessageId == model.MessageId)?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + source.MessageInfos.Add(newMessage); + source.SaveMessageInfos(); + return newMessage.GetViewModel; + } + } +} diff --git a/Pizzeria/PizzeriaFileImplement/Models/Client.cs b/Pizzeria/PizzeriaFileImplement/Models/Client.cs new file mode 100644 index 0000000..60b325e --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Models/Client.cs @@ -0,0 +1,79 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.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 PizzeriaFileImplement.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) + { + if (model == null) + { + return null; + } + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password, + }; + } + public static Client? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Client() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ClientFIO = element.Element("ClientFIO")!.Value, + Email = element.Element("Email")!.Value, + Password = element.Element("Password")!.Value, + }; + } + public void Update(ClientBindingModel model) + { + if (model == null) + { + return; + } + ClientFIO = model.ClientFIO; + Email = model.Email; + Password = model.Password; + } + public ClientViewModel GetViewModel => new() + { + Id = Id, + ClientFIO = ClientFIO, + Email = Email, + Password = Password, + }; + public XElement GetXElement => new("Client", + new XAttribute("Id", Id), + new XElement("ClientFIO", ClientFIO), + new XElement("Email", Email), + new XElement("Password", Password)); + } +} diff --git a/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs b/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..8890cac --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs @@ -0,0 +1,86 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.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 PizzeriaFileImplement.Models +{ + [DataContract] + public class Implementer : IImplementerModel + { + [DataMember] + public int Id { get; set; } + [DataMember] + public string ImplementerFIO { get; set; } = string.Empty; + + [DataMember] + public string Password { get; set; } = string.Empty; + + [DataMember] + public int WorkExperience { get; set; } + + [DataMember] + public int Qualification { get; set; } + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification + }; + } + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Implementer() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ImplementerFIO = element.Element("ImplementerFIO")!.Value, + Password = element.Element("Password")!.Value, + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value) + }; + } + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + public XElement GetXElement=>new("Implementer", + new XAttribute("Id", Id), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("Password", Password), + new XElement("WorkExperience", WorkExperience.ToString()), + new XElement("Qualification", Qualification.ToString())); + } +} diff --git a/Pizzeria/PizzeriaFileImplement/Models/MessageInfo.cs b/Pizzeria/PizzeriaFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..7214eb1 --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Models/MessageInfo.cs @@ -0,0 +1,89 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Models; +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 PizzeriaFileImplement.Models +{ + [DataContract] + public class MessageInfo : IMessageInfoModel + { + [DataMember] + 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; } + + [DataMember] + public string Subject { get; private set; } = string.Empty; + + [DataMember] + public string Body { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + string clientId = element.Element("ClientId")!.Value; + return new() + { + MessageId = element.Attribute("MessageId")!.Value, + ClientId = string.IsNullOrEmpty(clientId) ? null : Convert.ToInt32(clientId), + SenderName = element.Element("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value), + Subject = element.Element("Subject")!.Value, + Body = element.Element("Body")!.Value + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + public XElement GetXElement => new("MessageInfo", + new XAttribute("MessageId", MessageId), + new XElement("ClientId", ClientId.ToString()), + new XElement("SenderName", SenderName), + new XElement("DateDelivery", DateDelivery.ToString()), + new XElement("Subject", Subject), + new XElement("Body", Body)); + } +} diff --git a/Pizzeria/PizzeriaFileImplement/PizzeriaFileImplement.csproj b/Pizzeria/PizzeriaFileImplement/PizzeriaFileImplement.csproj index 22ae113..a4aa05e 100644 --- a/Pizzeria/PizzeriaFileImplement/PizzeriaFileImplement.csproj +++ b/Pizzeria/PizzeriaFileImplement/PizzeriaFileImplement.csproj @@ -20,4 +20,8 @@ + + + + From 0ef56a3f2ad6bd8332d0d375690e23cf852645b9 Mon Sep 17 00:00:00 2001 From: shadowik Date: Thu, 18 May 2023 09:26:21 +0400 Subject: [PATCH 3/4] final --- Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs index 13212f1..9a527e6 100644 --- a/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -35,7 +35,6 @@ namespace PizzeriaBusinessLogic.BusinessLogics try { _logger.LogDebug("Clear folder"); - // зачистка папки и удаление старого архива var dirInfo = new DirectoryInfo(model.FolderName); if (dirInfo.Exists) { From b3253504a64c7aea4fde92af119b976a99f25814 Mon Sep 17 00:00:00 2001 From: shadowik Date: Thu, 18 May 2023 10:04:09 +0400 Subject: [PATCH 4/4] Email enable --- Pizzeria/Pizzeria/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Pizzeria/Pizzeria/Program.cs b/Pizzeria/Pizzeria/Program.cs index 7e9ba62..eb0c0c5 100644 --- a/Pizzeria/Pizzeria/Program.cs +++ b/Pizzeria/Pizzeria/Program.cs @@ -45,7 +45,7 @@ namespace Pizzeria }); // todo Delete email to fine work - //var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); } catch (Exception ex) {