From 38441ab9126339975af6d01a41e16e775ca0feec Mon Sep 17 00:00:00 2001 From: VictoriaPresnyakova Date: Tue, 2 May 2023 11:38:30 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BD=D0=B0=D1=87=D0=B0=D0=BB=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JewelryStore/DataGridViewExtension.cs | 51 +++ JewelryStore/FormClients.cs | 30 +- JewelryStore/FormMain.Designer.cs | 368 +++++++++--------- JewelryStore/FormMain.cs | 49 ++- JewelryStore/Program.cs | 4 +- .../BusinessLogics/BackUpLogic.cs | 99 +++++ .../Attributes/ColumnAttribute.cs | 32 ++ .../Attributes/GridViewAutoSize.cs | 20 + .../BindingModels/BackUpSaveBinidngModel.cs | 13 + .../BusinessLogicsContracts/IBackUpLogic.cs | 14 + JewelryStoreContracts/DI/DependencyManager.cs | 60 +++ .../DI/IDependencyContainer.cs | 40 ++ .../DI/IImplementationExtension.cs | 20 + .../DI/ServiceProviderLoader.cs | 57 +++ .../JewelryStoreContracts.csproj | 1 + .../StoragesContracts/IBackUpInfo.cs | 14 + .../ViewModels/ClientViewModel.cs | 3 - .../Implements/BackUpInfo.cs | 31 ++ 18 files changed, 692 insertions(+), 214 deletions(-) create mode 100644 JewelryStore/DataGridViewExtension.cs create mode 100644 JewelryStoreBusinessLogic/BusinessLogics/BackUpLogic.cs create mode 100644 JewelryStoreContracts/Attributes/ColumnAttribute.cs create mode 100644 JewelryStoreContracts/Attributes/GridViewAutoSize.cs create mode 100644 JewelryStoreContracts/BindingModels/BackUpSaveBinidngModel.cs create mode 100644 JewelryStoreContracts/BusinessLogicsContracts/IBackUpLogic.cs create mode 100644 JewelryStoreContracts/DI/DependencyManager.cs create mode 100644 JewelryStoreContracts/DI/IDependencyContainer.cs create mode 100644 JewelryStoreContracts/DI/IImplementationExtension.cs create mode 100644 JewelryStoreContracts/DI/ServiceProviderLoader.cs create mode 100644 JewelryStoreContracts/StoragesContracts/IBackUpInfo.cs create mode 100644 JewelryStoreDatabaseImplement/Implements/BackUpInfo.cs diff --git a/JewelryStore/DataGridViewExtension.cs b/JewelryStore/DataGridViewExtension.cs new file mode 100644 index 0000000..e55c84e --- /dev/null +++ b/JewelryStore/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using JewelryStoreContracts.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStore +{ + 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/JewelryStore/FormClients.cs b/JewelryStore/FormClients.cs index 833f03d..ddb75cb 100644 --- a/JewelryStore/FormClients.cs +++ b/JewelryStore/FormClients.cs @@ -30,25 +30,17 @@ namespace JewelryStore private void LoadData() { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Email"].AutoSizeMode =DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["Password"].Visible = false; - } - _logger.LogInformation("Загрузка клиентов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки клиентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } + try + { + dataGridView.FillAndConfigGrid(_logic.ReadList(null)); + _logger.LogInformation("Загрузка клиентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки клиентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } private void ButtonDel_Click(object sender, EventArgs e) diff --git a/JewelryStore/FormMain.Designer.cs b/JewelryStore/FormMain.Designer.cs index 5c00a81..d89e3c1 100644 --- a/JewelryStore/FormMain.Designer.cs +++ b/JewelryStore/FormMain.Designer.cs @@ -28,207 +28,216 @@ /// private void InitializeComponent() { - this.buttonReady = new System.Windows.Forms.Button(); - this.dataGridView = new System.Windows.Forms.DataGridView(); - this.buttonCreate = new System.Windows.Forms.Button(); - this.buttonToWork = new System.Windows.Forms.Button(); - this.buttonPut = new System.Windows.Forms.Button(); - this.buttonRefresh = new System.Windows.Forms.Button(); - this.menuStrip = new System.Windows.Forms.MenuStrip(); - this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.списокКомпонентовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.списокЗаказзовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.buttonReady = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.buttonCreate = new System.Windows.Forms.Button(); + this.buttonToWork = new System.Windows.Forms.Button(); + this.buttonPut = new System.Windows.Forms.Button(); + this.buttonRefresh = new System.Windows.Forms.Button(); + this.menuStrip = new System.Windows.Forms.MenuStrip(); + this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.списокКомпонентовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.списокЗаказзовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.элПисьмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.создатьБекапToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); - this.menuStrip.SuspendLayout(); - this.SuspendLayout(); - // - // buttonReady - // - this.buttonReady.Location = new System.Drawing.Point(1273, 298); - this.buttonReady.Name = "buttonReady"; - this.buttonReady.Size = new System.Drawing.Size(215, 34); - this.buttonReady.TabIndex = 3; - this.buttonReady.Text = "Заказ выдан"; - this.buttonReady.UseVisualStyleBackColor = true; - this.buttonReady.Click += new System.EventHandler(this.buttonReady_Click); - // - // dataGridView - // - this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView.Location = new System.Drawing.Point(9, 52); - this.dataGridView.Name = "dataGridView"; - this.dataGridView.RowHeadersWidth = 62; - this.dataGridView.RowTemplate.Height = 33; - this.dataGridView.Size = new System.Drawing.Size(1227, 386); - this.dataGridView.TabIndex = 0; - // - // buttonCreate - // - this.buttonCreate.Location = new System.Drawing.Point(1273, 52); - this.buttonCreate.Name = "buttonCreate"; - this.buttonCreate.Size = new System.Drawing.Size(215, 34); - this.buttonCreate.TabIndex = 1; - this.buttonCreate.Text = "Создать заказ"; - this.buttonCreate.UseVisualStyleBackColor = true; - this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click); - // - // buttonToWork - // - this.buttonToWork.Location = new System.Drawing.Point(1273, 137); - this.buttonToWork.Name = "buttonToWork"; - this.buttonToWork.Size = new System.Drawing.Size(215, 34); - this.buttonToWork.TabIndex = 2; - this.buttonToWork.Text = "Отдать на выполнение"; - this.buttonToWork.UseVisualStyleBackColor = true; - this.buttonToWork.Click += new System.EventHandler(this.buttonToWork_Click); - // - // buttonPut - // - this.buttonPut.Location = new System.Drawing.Point(1273, 218); - this.buttonPut.Name = "buttonPut"; - this.buttonPut.Size = new System.Drawing.Size(215, 34); - this.buttonPut.TabIndex = 4; - this.buttonPut.Text = "Заказ готов"; - this.buttonPut.UseVisualStyleBackColor = true; - this.buttonPut.Click += new System.EventHandler(this.buttonPut_Click); - // - // buttonRefresh - // - this.buttonRefresh.Location = new System.Drawing.Point(1273, 389); - this.buttonRefresh.Name = "buttonRefresh"; - this.buttonRefresh.Size = new System.Drawing.Size(215, 34); - this.buttonRefresh.TabIndex = 5; - this.buttonRefresh.Text = "Обновить список"; - this.buttonRefresh.UseVisualStyleBackColor = true; - this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click); - // - // menuStrip - // - this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.menuStrip.SuspendLayout(); + this.SuspendLayout(); + // + // buttonReady + // + this.buttonReady.Location = new System.Drawing.Point(1273, 298); + this.buttonReady.Name = "buttonReady"; + this.buttonReady.Size = new System.Drawing.Size(215, 34); + this.buttonReady.TabIndex = 3; + this.buttonReady.Text = "Заказ выдан"; + this.buttonReady.UseVisualStyleBackColor = true; + this.buttonReady.Click += new System.EventHandler(this.buttonReady_Click); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(9, 52); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 62; + this.dataGridView.RowTemplate.Height = 33; + this.dataGridView.Size = new System.Drawing.Size(1227, 386); + this.dataGridView.TabIndex = 0; + // + // buttonCreate + // + this.buttonCreate.Location = new System.Drawing.Point(1273, 52); + this.buttonCreate.Name = "buttonCreate"; + this.buttonCreate.Size = new System.Drawing.Size(215, 34); + this.buttonCreate.TabIndex = 1; + this.buttonCreate.Text = "Создать заказ"; + this.buttonCreate.UseVisualStyleBackColor = true; + this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click); + // + // buttonToWork + // + this.buttonToWork.Location = new System.Drawing.Point(1273, 137); + this.buttonToWork.Name = "buttonToWork"; + this.buttonToWork.Size = new System.Drawing.Size(215, 34); + this.buttonToWork.TabIndex = 2; + this.buttonToWork.Text = "Отдать на выполнение"; + this.buttonToWork.UseVisualStyleBackColor = true; + this.buttonToWork.Click += new System.EventHandler(this.buttonToWork_Click); + // + // buttonPut + // + this.buttonPut.Location = new System.Drawing.Point(1273, 218); + this.buttonPut.Name = "buttonPut"; + this.buttonPut.Size = new System.Drawing.Size(215, 34); + this.buttonPut.TabIndex = 4; + this.buttonPut.Text = "Заказ готов"; + this.buttonPut.UseVisualStyleBackColor = true; + this.buttonPut.Click += new System.EventHandler(this.buttonPut_Click); + // + // buttonRefresh + // + this.buttonRefresh.Location = new System.Drawing.Point(1273, 389); + this.buttonRefresh.Name = "buttonRefresh"; + this.buttonRefresh.Size = new System.Drawing.Size(215, 34); + this.buttonRefresh.TabIndex = 5; + this.buttonRefresh.Text = "Обновить список"; + this.buttonRefresh.UseVisualStyleBackColor = true; + this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click); + // + // menuStrip + // + this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.справочникиToolStripMenuItem, this.отчетыToolStripMenuItem, this.запускРаботToolStripMenuItem, - this.элПисьмаToolStripMenuItem}); - this.menuStrip.Location = new System.Drawing.Point(0, 0); - this.menuStrip.Name = "menuStrip"; - this.menuStrip.Size = new System.Drawing.Size(1530, 33); - this.menuStrip.TabIndex = 6; - this.menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.элПисьмаToolStripMenuItem, + this.создатьБекапToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(1530, 33); + this.menuStrip.TabIndex = 6; + this.menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.компонентыToolStripMenuItem, this.изделияToolStripMenuItem, this.клиентыToolStripMenuItem, this.исполнителиToolStripMenuItem}); - this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(139, 29); - this.справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - this.компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(240, 34); - this.компонентыToolStripMenuItem.Text = "Компоненты"; - this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.компонентыToolStripMenuItem_Click); - // - // изделияToolStripMenuItem - // - this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - this.изделияToolStripMenuItem.Size = new System.Drawing.Size(240, 34); - this.изделияToolStripMenuItem.Text = "Драгоценности"; - this.изделияToolStripMenuItem.Click += new System.EventHandler(this.драгоценностиToolStripMenuItem_Click); - // - // клиентыToolStripMenuItem - // - this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(240, 34); - this.клиентыToolStripMenuItem.Text = "Клиенты"; - this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click); - // - // исполнителиToolStripMenuItem - // - this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(240, 34); - this.исполнителиToolStripMenuItem.Text = "Исполнители"; - this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click); - // - // отчетыToolStripMenuItem - // - this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(139, 29); + this.справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + this.компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(240, 34); + this.компонентыToolStripMenuItem.Text = "Компоненты"; + this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.компонентыToolStripMenuItem_Click); + // + // изделияToolStripMenuItem + // + this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + this.изделияToolStripMenuItem.Size = new System.Drawing.Size(240, 34); + this.изделияToolStripMenuItem.Text = "Драгоценности"; + this.изделияToolStripMenuItem.Click += new System.EventHandler(this.драгоценностиToolStripMenuItem_Click); + // + // клиентыToolStripMenuItem + // + this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(240, 34); + this.клиентыToolStripMenuItem.Text = "Клиенты"; + this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click); + // + // исполнителиToolStripMenuItem + // + this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(240, 34); + this.исполнителиToolStripMenuItem.Text = "Исполнители"; + this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click); + // + // отчетыToolStripMenuItem + // + this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.списокКомпонентовToolStripMenuItem, this.компонентыПоИзделиямToolStripMenuItem, this.списокЗаказзовToolStripMenuItem}); - this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(88, 29); - this.отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокКомпонентовToolStripMenuItem - // - this.списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - this.списокКомпонентовToolStripMenuItem.Size = new System.Drawing.Size(325, 34); - this.списокКомпонентовToolStripMenuItem.Text = "Список изделий"; - this.списокКомпонентовToolStripMenuItem.Click += new System.EventHandler(this.списокКомпонентовToolStripMenuItem_Click); - // - // компонентыПоИзделиямToolStripMenuItem - // - this.компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - this.компонентыПоИзделиямToolStripMenuItem.Size = new System.Drawing.Size(325, 34); - this.компонентыПоИзделиямToolStripMenuItem.Text = "Изделия по компонентам"; - this.компонентыПоИзделиямToolStripMenuItem.Click += new System.EventHandler(this.компонентыПоИзделиямToolStripMenuItem_Click); - // - // списокЗаказзовToolStripMenuItem - // - this.списокЗаказзовToolStripMenuItem.Name = "списокЗаказзовToolStripMenuItem"; - this.списокЗаказзовToolStripMenuItem.Size = new System.Drawing.Size(325, 34); - this.списокЗаказзовToolStripMenuItem.Text = "Список заказов"; - this.списокЗаказзовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказзовToolStripMenuItem_Click); - // - // запускРаботToolStripMenuItem - // - this.запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(136, 29); - this.запускРаботToolStripMenuItem.Text = "Запуск работ"; - this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); + this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(88, 29); + this.отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокКомпонентовToolStripMenuItem + // + this.списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; + this.списокКомпонентовToolStripMenuItem.Size = new System.Drawing.Size(325, 34); + this.списокКомпонентовToolStripMenuItem.Text = "Список изделий"; + this.списокКомпонентовToolStripMenuItem.Click += new System.EventHandler(this.списокКомпонентовToolStripMenuItem_Click); + // + // компонентыПоИзделиямToolStripMenuItem + // + this.компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + this.компонентыПоИзделиямToolStripMenuItem.Size = new System.Drawing.Size(325, 34); + this.компонентыПоИзделиямToolStripMenuItem.Text = "Изделия по компонентам"; + this.компонентыПоИзделиямToolStripMenuItem.Click += new System.EventHandler(this.компонентыПоИзделиямToolStripMenuItem_Click); + // + // списокЗаказзовToolStripMenuItem + // + this.списокЗаказзовToolStripMenuItem.Name = "списокЗаказзовToolStripMenuItem"; + this.списокЗаказзовToolStripMenuItem.Size = new System.Drawing.Size(325, 34); + this.списокЗаказзовToolStripMenuItem.Text = "Список заказов"; + this.списокЗаказзовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказзовToolStripMenuItem_Click); + // + // запускРаботToolStripMenuItem + // + this.запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(136, 29); + this.запускРаботToolStripMenuItem.Text = "Запуск работ"; + this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); // // элПисьмаToolStripMenuItem // this.элПисьмаToolStripMenuItem.Name = "элПисьмаToolStripMenuItem"; - this.элПисьмаToolStripMenuItem.Size = new System.Drawing.Size(82, 20); + this.элПисьмаToolStripMenuItem.Size = new System.Drawing.Size(119, 29); this.элПисьмаToolStripMenuItem.Text = "Эл. Письма"; this.элПисьмаToolStripMenuItem.Click += new System.EventHandler(this.элПисьмаToolStripMenuItem_Click); // + // создатьБекапToolStripMenuItem + // + this.создатьБекапToolStripMenuItem.Name = "создатьБекапToolStripMenuItem"; + this.создатьБекапToolStripMenuItem.Size = new System.Drawing.Size(140, 29); + this.создатьБекапToolStripMenuItem.Text = "СоздатьБекап"; + this.создатьБекапToolStripMenuItem.Click += new System.EventHandler(this.создатьБекапToolStripMenuItem_Click); + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1530, 450); - this.Controls.Add(this.buttonRefresh); - this.Controls.Add(this.buttonPut); - this.Controls.Add(this.buttonReady); - this.Controls.Add(this.buttonToWork); - this.Controls.Add(this.buttonCreate); - this.Controls.Add(this.dataGridView); - this.Controls.Add(this.menuStrip); - this.MainMenuStrip = this.menuStrip; - this.Name = "FormMain"; - this.Text = "Изготовление Драгоценностей"; - this.Load += new System.EventHandler(this.FormMain_Load); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); - this.menuStrip.ResumeLayout(false); - this.menuStrip.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1530, 450); + this.Controls.Add(this.buttonRefresh); + this.Controls.Add(this.buttonPut); + this.Controls.Add(this.buttonReady); + this.Controls.Add(this.buttonToWork); + this.Controls.Add(this.buttonCreate); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; + this.Name = "FormMain"; + this.Text = "Изготовление Драгоценностей"; + this.Load += new System.EventHandler(this.FormMain_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); } @@ -252,5 +261,6 @@ private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem элПисьмаToolStripMenuItem; + private ToolStripMenuItem создатьБекапToolStripMenuItem; } } \ No newline at end of file diff --git a/JewelryStore/FormMain.cs b/JewelryStore/FormMain.cs index 91ac56c..702f776 100644 --- a/JewelryStore/FormMain.cs +++ b/JewelryStore/FormMain.cs @@ -21,17 +21,20 @@ namespace JewelryStore private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; + private readonly IBackUpLogic _backUpLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; - LoadData(); - } + _backUpLogic = backUpLogic; + LoadData(); + } private void FormMain_Load(object sender, EventArgs e) { @@ -263,13 +266,35 @@ namespace JewelryStore form.ShowDialog(); } } - private void элПисьмаToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); - if (service is FormMails form) - { - form.ShowDialog(); - } - } - } + private void элПисьмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + + private void создатьБекапToolStripMenuItem_Click(object sender, EventArgs e) + { + { + try + { + 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/JewelryStore/Program.cs b/JewelryStore/Program.cs index 9d4c511..81d36ba 100644 --- a/JewelryStore/Program.cs +++ b/JewelryStore/Program.cs @@ -79,8 +79,10 @@ namespace JewelryStore services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/JewelryStoreBusinessLogic/BusinessLogics/BackUpLogic.cs b/JewelryStoreBusinessLogic/BusinessLogics/BackUpLogic.cs new file mode 100644 index 0000000..a590b00 --- /dev/null +++ b/JewelryStoreBusinessLogic/BusinessLogics/BackUpLogic.cs @@ -0,0 +1,99 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using JewelryStoreContracts.StoragesContracts; +using JewelryStoreDataModels; +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 JewelryStoreBusinessLogic.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/JewelryStoreContracts/Attributes/ColumnAttribute.cs b/JewelryStoreContracts/Attributes/ColumnAttribute.cs new file mode 100644 index 0000000..99cff93 --- /dev/null +++ b/JewelryStoreContracts/Attributes/ColumnAttribute.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/Attributes/GridViewAutoSize.cs b/JewelryStoreContracts/Attributes/GridViewAutoSize.cs new file mode 100644 index 0000000..ddb8d60 --- /dev/null +++ b/JewelryStoreContracts/Attributes/GridViewAutoSize.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.Attributes +{ + public enum GridViewAutoSize + { + NotSet = 0, + None = 1, + ColumnHeader = 2, + AllCellsExceptHeader = 4, + AllCells = 6, + DisplayedCellsExceptHeader = 8, + DisplayedCells = 10, + Fill = 16 + } +} diff --git a/JewelryStoreContracts/BindingModels/BackUpSaveBinidngModel.cs b/JewelryStoreContracts/BindingModels/BackUpSaveBinidngModel.cs new file mode 100644 index 0000000..a1c744c --- /dev/null +++ b/JewelryStoreContracts/BindingModels/BackUpSaveBinidngModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.BindingModels +{ + public class BackUpSaveBinidngModel + { + public string FolderName { get; set; } = string.Empty; + } +} diff --git a/JewelryStoreContracts/BusinessLogicsContracts/IBackUpLogic.cs b/JewelryStoreContracts/BusinessLogicsContracts/IBackUpLogic.cs new file mode 100644 index 0000000..bdfba62 --- /dev/null +++ b/JewelryStoreContracts/BusinessLogicsContracts/IBackUpLogic.cs @@ -0,0 +1,14 @@ +using JewelryStoreContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.BusinessLogicsContracts +{ + public interface IBackUpLogic + { + void CreateBackUp(BackUpSaveBinidngModel model); + } +} diff --git a/JewelryStoreContracts/DI/DependencyManager.cs b/JewelryStoreContracts/DI/DependencyManager.cs new file mode 100644 index 0000000..2991a82 --- /dev/null +++ b/JewelryStoreContracts/DI/DependencyManager.cs @@ -0,0 +1,60 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/DI/IDependencyContainer.cs b/JewelryStoreContracts/DI/IDependencyContainer.cs new file mode 100644 index 0000000..200e70e --- /dev/null +++ b/JewelryStoreContracts/DI/IDependencyContainer.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/DI/IImplementationExtension.cs b/JewelryStoreContracts/DI/IImplementationExtension.cs new file mode 100644 index 0000000..33b8de3 --- /dev/null +++ b/JewelryStoreContracts/DI/IImplementationExtension.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.DI +{ + /// + /// Интерфейс для регистрации зависимостей в модулях + /// + public interface IImplementationExtension + { + public int Priority { get; } + /// + /// Регистрация сервисов + /// + public void RegisterServices(); + } +} diff --git a/JewelryStoreContracts/DI/ServiceProviderLoader.cs b/JewelryStoreContracts/DI/ServiceProviderLoader.cs new file mode 100644 index 0000000..8acd2d3 --- /dev/null +++ b/JewelryStoreContracts/DI/ServiceProviderLoader.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/JewelryStoreContracts.csproj b/JewelryStoreContracts/JewelryStoreContracts.csproj index b4c900b..a196f49 100644 --- a/JewelryStoreContracts/JewelryStoreContracts.csproj +++ b/JewelryStoreContracts/JewelryStoreContracts.csproj @@ -7,6 +7,7 @@ + diff --git a/JewelryStoreContracts/StoragesContracts/IBackUpInfo.cs b/JewelryStoreContracts/StoragesContracts/IBackUpInfo.cs new file mode 100644 index 0000000..9008686 --- /dev/null +++ b/JewelryStoreContracts/StoragesContracts/IBackUpInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.StoragesContracts +{ + public interface IBackUpInfo + { + List? GetList() where T : class, new(); + Type? GetTypeByModelInterface(string modelInterfaceName); + } +} diff --git a/JewelryStoreContracts/ViewModels/ClientViewModel.cs b/JewelryStoreContracts/ViewModels/ClientViewModel.cs index fb12e3f..504ee45 100644 --- a/JewelryStoreContracts/ViewModels/ClientViewModel.cs +++ b/JewelryStoreContracts/ViewModels/ClientViewModel.cs @@ -11,11 +11,8 @@ namespace JewelryStoreContracts.ViewModels public class ClientViewModel : IClientModel { public int Id { get; set; } - [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Логин (эл. почта)")] public string Email { get; set; } = string.Empty; - [DisplayName("Пароль")] public string Password { get; set; } = string.Empty; } } diff --git a/JewelryStoreDatabaseImplement/Implements/BackUpInfo.cs b/JewelryStoreDatabaseImplement/Implements/BackUpInfo.cs new file mode 100644 index 0000000..40ea98b --- /dev/null +++ b/JewelryStoreDatabaseImplement/Implements/BackUpInfo.cs @@ -0,0 +1,31 @@ +using JewelryStoreContracts.StoragesContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreDatabaseImplement.Implements +{ + public class BackUpInfo : IBackUpInfo + { + public List? GetList() where T : class, new() + { + using var context = new JewelryStoreDataBase(); + 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; + } + } +}