From 9ca5aa40c93a6e993b3ee4e361550cd24e2d15c0 Mon Sep 17 00:00:00 2001 From: goblinrf Date: Thu, 7 Nov 2024 14:19:38 +0400 Subject: [PATCH] Done --- .../Forms/FormCustomer.Designer.cs | 181 ++++++++++++ PluginConventionLibrary/Forms/FormCustomer.cs | 172 ++++++++++++ .../Forms/FormCustomer.resx | 120 ++++++++ .../Forms/FormProductCategory.Designer.cs | 68 +++++ .../Forms/FormProductCategory.cs | 110 ++++++++ .../Forms/FormProductCategory.resx | 120 ++++++++ .../MainPluginConvention.cs | 264 ++++++++++++++++++ .../MainPluginConventionElement.cs | 15 + .../Plugins/IPluginsConvention.cs | 60 ++++ .../Plugins/PluginsConventionElement.cs | 7 + .../Plugins/PluginsConventionSaveDocument.cs | 7 + .../PluginsConventionLibrary.csproj | 22 ++ .../BusinessLogics/CustomerLogic.cs | 107 +++---- .../BusinessLogics/ProductCategoryLogic.cs | 7 +- ShopBusinessLogic/ShopBusinessLogic.csproj | 1 + WinFormsLibrary1.sln | 16 +- WinFormsLibrary2/FormCustomer.cs | 255 +++++++++-------- WinFormsLibrary2/FormMain.Designer.cs | 1 - WinFormsLibrary2/FormMain.cs | 14 +- WinFormsLibrary2/FormMainPlugins.Designer.cs | 174 ++++++++++++ WinFormsLibrary2/FormMainPlugins.cs | 163 +++++++++++ WinFormsLibrary2/FormMainPlugins.resx | 132 +++++++++ WinFormsLibrary2/Model/TestModel.cs | 13 + WinFormsLibrary2/PluginsManager.cs | 43 +++ WinFormsLibrary2/Program.cs | 10 +- WinFormsLibrary2/ShopView.csproj | 4 +- 26 files changed, 1884 insertions(+), 202 deletions(-) create mode 100644 PluginConventionLibrary/Forms/FormCustomer.Designer.cs create mode 100644 PluginConventionLibrary/Forms/FormCustomer.cs create mode 100644 PluginConventionLibrary/Forms/FormCustomer.resx create mode 100644 PluginConventionLibrary/Forms/FormProductCategory.Designer.cs create mode 100644 PluginConventionLibrary/Forms/FormProductCategory.cs create mode 100644 PluginConventionLibrary/Forms/FormProductCategory.resx create mode 100644 PluginConventionLibrary/MainPluginConvention.cs create mode 100644 PluginConventionLibrary/MainPluginConventionElement.cs create mode 100644 PluginConventionLibrary/Plugins/IPluginsConvention.cs create mode 100644 PluginConventionLibrary/Plugins/PluginsConventionElement.cs create mode 100644 PluginConventionLibrary/Plugins/PluginsConventionSaveDocument.cs create mode 100644 PluginConventionLibrary/PluginsConventionLibrary.csproj create mode 100644 WinFormsLibrary2/FormMainPlugins.Designer.cs create mode 100644 WinFormsLibrary2/FormMainPlugins.cs create mode 100644 WinFormsLibrary2/FormMainPlugins.resx create mode 100644 WinFormsLibrary2/Model/TestModel.cs create mode 100644 WinFormsLibrary2/PluginsManager.cs diff --git a/PluginConventionLibrary/Forms/FormCustomer.Designer.cs b/PluginConventionLibrary/Forms/FormCustomer.Designer.cs new file mode 100644 index 0000000..32218d1 --- /dev/null +++ b/PluginConventionLibrary/Forms/FormCustomer.Designer.cs @@ -0,0 +1,181 @@ +namespace PluginsConventionLibrary.Forms +{ + partial class FormCustomer + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxFIO = new TextBox(); + label1 = new Label(); + label2 = new Label(); + emailField1 = new Lab1.EmailField(); + groupBox1 = new GroupBox(); + myListBox1 = new KOP.MyListBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + buttonAddPhoto = new Button(); + pictureBox = new PictureBox(); + groupBox1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // textBoxFIO + // + textBoxFIO.Location = new Point(120, 36); + textBoxFIO.Margin = new Padding(3, 4, 3, 4); + textBoxFIO.Name = "textBoxFIO"; + textBoxFIO.Size = new Size(244, 27); + textBoxFIO.TabIndex = 0; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(74, 40); + label1.Name = "label1"; + label1.Size = new Size(42, 20); + label1.TabIndex = 1; + label1.Text = "ФИО"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(74, 91); + label2.Name = "label2"; + label2.Size = new Size(143, 20); + label2.TabIndex = 3; + label2.Text = "Электронная почта"; + // + // emailField1 + // + emailField1.EmailExample = null; + emailField1.EmailRegex = null; + emailField1.Location = new Point(210, 87); + emailField1.Name = "emailField1"; + emailField1.Size = new Size(154, 51); + emailField1.TabIndex = 4; + // + // groupBox1 + // + groupBox1.Controls.Add(myListBox1); + groupBox1.Location = new Point(14, 144); + groupBox1.Margin = new Padding(3, 4, 3, 4); + groupBox1.Name = "groupBox1"; + groupBox1.Padding = new Padding(3, 4, 3, 4); + groupBox1.Size = new Size(414, 200); + groupBox1.TabIndex = 5; + groupBox1.TabStop = false; + groupBox1.Text = "Категория товаров"; + // + // myListBox1 + // + myListBox1.Dock = DockStyle.Fill; + myListBox1.Location = new Point(3, 24); + myListBox1.Margin = new Padding(3, 4, 3, 4); + myListBox1.Name = "myListBox1"; + myListBox1.SelectedItem = ""; + myListBox1.Size = new Size(408, 172); + myListBox1.TabIndex = 0; + // + // buttonSave + // + buttonSave.Location = new Point(249, 620); + buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(86, 31); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(342, 620); + buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(86, 31); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonAddPhoto + // + buttonAddPhoto.Location = new Point(14, 352); + buttonAddPhoto.Margin = new Padding(3, 4, 3, 4); + buttonAddPhoto.Name = "buttonAddPhoto"; + buttonAddPhoto.Size = new Size(411, 31); + buttonAddPhoto.TabIndex = 8; + buttonAddPhoto.Text = "Загрузить фото"; + buttonAddPhoto.UseVisualStyleBackColor = true; + buttonAddPhoto.Click += buttonAddPhoto_Click; + // + // pictureBox + // + pictureBox.Location = new Point(14, 391); + pictureBox.Margin = new Padding(3, 4, 3, 4); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(410, 221); + pictureBox.TabIndex = 9; + pictureBox.TabStop = false; + // + // FormCustomer + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(439, 667); + Controls.Add(pictureBox); + Controls.Add(buttonAddPhoto); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(groupBox1); + Controls.Add(emailField1); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(textBoxFIO); + Margin = new Padding(3, 4, 3, 4); + Name = "FormCustomer"; + Text = "Клиент"; + Load += FormCustomer_Load; + groupBox1.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxFIO; + private Label label1; + private Label label2; + private Lab1.EmailField emailField1; + private GroupBox groupBox1; + private Button buttonSave; + private Button buttonCancel; + private KOP.MyListBox myListBox1; + private Button buttonAddPhoto; + private PictureBox pictureBox; + } +} \ No newline at end of file diff --git a/PluginConventionLibrary/Forms/FormCustomer.cs b/PluginConventionLibrary/Forms/FormCustomer.cs new file mode 100644 index 0000000..bdeebbf --- /dev/null +++ b/PluginConventionLibrary/Forms/FormCustomer.cs @@ -0,0 +1,172 @@ +using Microsoft.Extensions.Logging; +using System.ComponentModel; +using ShopContracts.BindingModels; +using ShopContracts.BusinessLogicsContracts; +using ShopContracts.ViewModels; +using KOP; +using Lab1.VisualComponents.Exceptions; +using Lab1; + +namespace PluginsConventionLibrary.Forms +{ + public partial class FormCustomer : Form + { + private readonly ICustomerLogic _customerLogic; + private readonly IProductCategoryLogic _productCategoryLogic; + private string imagePath; + BindingList _list; + private int? _id; + public int Id { set { _id = value; } } + List productCategory = new(); + public FormCustomer( ICustomerLogic customerLogic, IProductCategoryLogic productCategoryLogic) + { + InitializeComponent(); + _customerLogic = customerLogic; + _productCategoryLogic = productCategoryLogic; + imagePath = ""; + _list = new BindingList(); + emailField1.EmailRegex = "^\\S+@\\S+\\.\\S+$"; + emailField1.EmailExample = "example@mail.ru"; + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + if (string.IsNullOrEmpty(emailField1.Value)) + { + MessageBox.Show("Введите почту!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + catch (IsNotMatchRegexException) + { + + } + if (myListBox1.SelectedItem == null) + { + MessageBox.Show("Заполните категорию товара", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (pictureBox.Image == null) + { + MessageBox.Show("Загрузите фото", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + _customerLogic.CreateOrUpdate(new CustomerBindingModel + { + Id = _id, + FIO = textBoxFIO.Text, + PhotoFilePath = imagePath, + Email = emailField1.Value, + ProductCategoryName = myListBox1.SelectedItem + }); + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void FormCustomer_Load(object sender, EventArgs e) + { + LoadData(); + if (_id.HasValue) + { + try + { + var view = _customerLogic.Read(new CustomerBindingModel { Id = _id.Value })?.FirstOrDefault(); + if (view != null) + { + textBoxFIO.Text = view.FIO; + imagePath = view.PhotoFilePath ?? string.Empty; + + // Используем рефлексию для доступа к textBox1 в emailField1 + var textBoxField = typeof(EmailField).GetField("textBox1", + System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Instance); + + if (textBoxField?.GetValue(emailField1) is TextBox innerTextBox) + { + innerTextBox.Text = view.Email ?? string.Empty; // Устанавливаем значение напрямую + } + + // Устанавливаем другие значения, как и раньше + string[] dirs = view.ProductCategoryName.Split(";"); + foreach (var dir in dirs) + { + myListBox1.SelectedItem = dir; + } + if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath)) + { + pictureBox.Image = Image.FromFile(imagePath); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + + private void LoadData() + { + try + { + var list = _productCategoryLogic.Read(null); + myListBox1.Clear(); + productCategory.Clear(); + _list.Clear(); + if (list != null) + { + foreach (var item in list) + { + productCategory.Add(item.Name); + _list.Add(new ProductCategoryBindingModel + { + Id = item.Id, + Name = item.Name, + }); + } + } + myListBox1.AddItems(productCategory); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonAddPhoto_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new() + { + Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*" + }; + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + imagePath = openFileDialog.FileName; + pictureBox.Image = Image.FromFile(imagePath); + } + } + } +} diff --git a/PluginConventionLibrary/Forms/FormCustomer.resx b/PluginConventionLibrary/Forms/FormCustomer.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginConventionLibrary/Forms/FormCustomer.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/PluginConventionLibrary/Forms/FormProductCategory.Designer.cs b/PluginConventionLibrary/Forms/FormProductCategory.Designer.cs new file mode 100644 index 0000000..ac972af --- /dev/null +++ b/PluginConventionLibrary/Forms/FormProductCategory.Designer.cs @@ -0,0 +1,68 @@ +namespace PluginsConventionLibrary.Forms +{ + partial class FormProductCategory + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.Control; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(490, 396); + dataGridView.TabIndex = 0; + dataGridView.CellEndEdit += dataGridView_CellEndEdit; + dataGridView.KeyDown += dataGridView_KeyDown; + // + // FormProductCategory + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(490, 396); + Controls.Add(dataGridView); + Margin = new Padding(3, 4, 3, 4); + Name = "FormProductCategory"; + Text = "Категория товаров"; + Load += FormDirection_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/PluginConventionLibrary/Forms/FormProductCategory.cs b/PluginConventionLibrary/Forms/FormProductCategory.cs new file mode 100644 index 0000000..4e2d4f4 --- /dev/null +++ b/PluginConventionLibrary/Forms/FormProductCategory.cs @@ -0,0 +1,110 @@ +using System.ComponentModel; +using ShopContracts.BindingModels; +using ShopContracts.BusinessLogicsContracts; + +namespace PluginsConventionLibrary.Forms +{ + public partial class FormProductCategory : Form + { + private readonly IProductCategoryLogic _logic; + BindingList _list; + private int? _id; + public int Id { set { _id = value; } } + public FormProductCategory(IProductCategoryLogic logic) + { + InitializeComponent(); + _logic = logic; + _list = new BindingList(); + dataGridView.AllowUserToAddRows = false; + } + + private void FormDirection_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _logic.Read(null); + _list.Clear(); + foreach (var item in list) + { + _list.Add(new ProductCategoryBindingModel + { + Id = item.Id, + Name = item.Name, + }); + } + if (_list != null) + { + dataGridView.DataSource = _list; + dataGridView.Columns[0].Visible = false; + dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) + { + var typeName = (string)dataGridView.CurrentRow.Cells[1].Value; + if (!string.IsNullOrEmpty(typeName)) + { + if (dataGridView.CurrentRow.Cells[0].Value != null) + { + _logic.CreateOrUpdate(new ProductCategoryBindingModel() + { + Id = Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value), + Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue + }); + } + else + { + _logic.CreateOrUpdate(new ProductCategoryBindingModel() + { + Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue + }); + } + } + else + { + MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + + private void dataGridView_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyData == Keys.Insert) + { + if (dataGridView.Rows.Count == 0) + { + _list.Add(new ProductCategoryBindingModel()); + dataGridView.DataSource = new BindingList(_list); + dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1]; + return; + } + if (dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value != null) + { + _list.Add(new ProductCategoryBindingModel()); + dataGridView.DataSource = new BindingList(_list); + dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1]; + return; + } + } + if (e.KeyData == Keys.Delete) + { + if (MessageBox.Show("Удалить выбранный элемент", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + _logic.Delete(new ProductCategoryBindingModel() { Id = (int)dataGridView.CurrentRow.Cells[0].Value }); + LoadData(); + } + } + } + } +} diff --git a/PluginConventionLibrary/Forms/FormProductCategory.resx b/PluginConventionLibrary/Forms/FormProductCategory.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginConventionLibrary/Forms/FormProductCategory.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/PluginConventionLibrary/MainPluginConvention.cs b/PluginConventionLibrary/MainPluginConvention.cs new file mode 100644 index 0000000..24799c8 --- /dev/null +++ b/PluginConventionLibrary/MainPluginConvention.cs @@ -0,0 +1,264 @@ +using COP; +using COP.Info; +using PluginsConventionLibrary.Forms; +using PluginsConventionLibrary.Plugins; +using System.ComponentModel.Composition; +using ShopBusinessLogic.BusinessLogics; +using ShopContracts.BindingModels; +using ShopContracts.BusinessLogicsContracts; +using static COP.ExcelComponent; +using Lab1.LogicalComponents.SupportClasses; +using LegendPosition = KOP.PDFComponents.Enums.LegendPosition; +using KOP.Addition; +using static KOP.PDFComponents.OfficePackage.PdfRowParameters; +using Aspose.Words.XAttr; +using KOP.PDFComponents.OfficePackage; +using KOP.PDFComponents; + +namespace PluginsConventionLibrary +{ + [Export(typeof(IPluginsConvention))] + public class MainPluginConvention : IPluginsConvention + { + + private KOP.MyTable tableOfValues; + private readonly ICustomerLogic _customerLogic; + private readonly IProductCategoryLogic _productCategoryLogic; + + public MainPluginConvention() + { + _customerLogic = new CustomerLogic(); + _productCategoryLogic = new ProductCategoryLogic(); + + tableOfValues = new KOP.MyTable(); + var menu = new ContextMenuStrip(); + var directionMenuItem = new ToolStripMenuItem("Категория товаров"); + menu.Items.Add(directionMenuItem); + directionMenuItem.Click += (sender, e) => + { + var formDirection = new FormProductCategory(_productCategoryLogic); + formDirection.ShowDialog(); + }; + tableOfValues.ContextMenuStrip = menu; + ReloadData(); + } + + public void ReloadData() + { + try + { + var lst = new List(); + + ColumnInfo ci1 = new ColumnInfo("ID", 100, false, "Id"); + ColumnInfo ci2 = new ColumnInfo("FIO", 100, true, "ФИО"); + ColumnInfo ci3 = new ColumnInfo("ProductCategoryName", 80, true, "Категория товара"); + ColumnInfo ci5 = new ColumnInfo("PhotoFilePath", 80, false, "PhotoFilePath"); + ColumnInfo ci4 = new ColumnInfo("Email", 80, true, "Электронная почта"); + + lst.Add(ci1); + lst.Add(ci2); + lst.Add(ci3); + lst.Add(ci4); + lst.Add(ci5); + tableOfValues.ColumnConfiguration(new TableConfiguration(lst)); + tableOfValues.ClearRows(); + var list = _customerLogic.Read(null); + if (list != null) + { + tableOfValues.AddRows(list); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// Название плагина + string IPluginsConvention.PluginName => PluginName(); + public string PluginName() + { + return "Клиенты"; + } + + public UserControl GetControl => tableOfValues; + + PluginsConventionElement IPluginsConvention.GetElement => GetElement(); + + public PluginsConventionElement GetElement() + { + tableOfValues.IndexProperty = tableOfValues.myDataGridView.CurrentRow.Index; + var student = tableOfValues.GetUser(); ; + MainPluginConventionElement element = null; + if (tableOfValues != null) + { + element = new MainPluginConventionElement + { + Id = student.Id, + FIO = student.FIO, + PhotoFilePath = student.PhotoFilePath, + Email = student.Email, + ProductCategoryName = student.ProductCategoryName, + }; + } + return (new PluginsConventionElement { Id = element.Id }); + } + + public Form GetForm(PluginsConventionElement element) + { + var formOrder = new FormCustomer(_customerLogic, _productCategoryLogic); + if (element != null) + { + formOrder.Id = element.Id; + } + return formOrder; + } + + public bool DeleteElement(PluginsConventionElement element) + { + try + { + _customerLogic.Delete(new CustomerBindingModel { Id = element.Id }); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + return true; + } + + public bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument) + { + ExcelComponent excelComponent = new(); + var list = _customerLogic.Read(null); + List images = new(); + using var dialog = new SaveFileDialog + { + Filter = "xlsx|*.xlsx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + if (list != null) + { + foreach (var item in list) + { + images.Add(new ImageInfo() { FilePath = item.PhotoFilePath }); + } + } + ExcelImageInfo info = new(dialog.FileName, "Документ с фотографиями студентов", images); + excelComponent.GenerateExcelWithImages(info); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + return true; + } + + public bool CreateTableDocument(PluginsConventionSaveDocument saveDocument) + { + Lab1.LogicalComponents.TableDocument componentWord = new(); + var list = _customerLogic.Read(null); + List data = new(); + List mergedColumns = new() + { + new int[] { 1, 2 } + }; + + List columnDefinitions = new() + { + new ColumnDefinition { Header = "ID", PropertyName = "Id", Weight = 11 }, + new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData", Weight = 11 }, + new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData1", Weight = 11 }, + new ColumnDefinition { Header = "Категория товаров", PropertyName = "ProductCategoryName", Weight = 21 } + }; + + List columnDefinitions2 = new() + { + new ColumnDefinition { Header = "ID", PropertyName = "Id", Weight = 11 }, + new ColumnDefinition { Header = "ФИО", PropertyName = "FIO", Weight = 11 }, + new ColumnDefinition { Header = "Электронная почта", PropertyName = "Email", Weight = 70 }, + new ColumnDefinition { Header = "Категория товаров", PropertyName = "ProductCategoryName", Weight = 21 } + }; + + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + if (list != null) + { + foreach (var item in list) + { + data.Add(new CustomerBindingModel() { Id = item.Id, FIO = item.FIO, Email = item.Email, ProductCategoryName = item.ProductCategoryName }); + } + } + TableDocumentInfo tableWord = new(dialog.FileName, "Таблица с клиентами", columnDefinitions, columnDefinitions2, data, mergedColumns); + Lab1.LogicalComponents.TableDocument.CreateTable(tableWord); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + return true; + } + + public bool CreateChartDocument(PluginsConventionSaveDocument saveDocument) + { + KOP.PDFComponents.PdfChartComponent gistogramPdfComponent = new(); + var listStudents = _customerLogic.Read(null); + var listDirections = _productCategoryLogic.Read(null); + List<(string, int)> data = new(); + List gistData = new(); + var Data = new Dictionary(); + using var dialog = new SaveFileDialog + { + Filter = "pdf|*.pdf" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + for (int i = 0; i < listDirections.Count; i++) + { + int count = 0; + for (int j = 0; j < listStudents.Count; j++) + { + string[] dirs = listStudents[j].ProductCategoryName.Split(";"); + foreach (var dir in dirs) + { + if (dir == listDirections[i].Name) count++; + } + } + data.Add((listDirections[i].Name, count)); + } + if (data != null) + { + foreach (var item in data) + { + Data.Add(item.Item1, new[] {item.Item2 }); + } + } + gistogramPdfComponent.CreateDocument(dialog.FileName, "Histogram", "Customers-ProductCategorys", LegendPosition.Right, Data); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + return true; + } + } +} diff --git a/PluginConventionLibrary/MainPluginConventionElement.cs b/PluginConventionLibrary/MainPluginConventionElement.cs new file mode 100644 index 0000000..48cdb06 --- /dev/null +++ b/PluginConventionLibrary/MainPluginConventionElement.cs @@ -0,0 +1,15 @@ +using PluginsConventionLibrary.Plugins; + +namespace PluginsConventionLibrary +{ + public class MainPluginConventionElement : PluginsConventionElement + { + public string ProductCategoryName { get; set; } + + public string PhotoFilePath { get; set; } + + public string FIO { get; set; } + + public string Email { get; set; } + } +} diff --git a/PluginConventionLibrary/Plugins/IPluginsConvention.cs b/PluginConventionLibrary/Plugins/IPluginsConvention.cs new file mode 100644 index 0000000..f85aa18 --- /dev/null +++ b/PluginConventionLibrary/Plugins/IPluginsConvention.cs @@ -0,0 +1,60 @@ +namespace PluginsConventionLibrary.Plugins +{ + public interface IPluginsConvention + { + /// + /// Название плагина + /// + string PluginName { get; } + + /// + /// Получение контрола для вывода набора данных + /// + UserControl GetControl { get; } + + /// + /// Получение элемента, выбранного в контроле + /// + PluginsConventionElement GetElement { get; } + + /// + /// Получение формы для создания/редактирования объекта + /// + /// + /// + Form GetForm(PluginsConventionElement element); + + /// + /// Удаление элемента + /// + /// + /// + bool DeleteElement(PluginsConventionElement element); + + /// + /// Обновление набора данных в контроле + /// + void ReloadData(); + + /// + /// Создание простого документа + /// + /// + /// + bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument); + + /// + /// Создание простого документа + /// + /// + /// + bool CreateTableDocument(PluginsConventionSaveDocument saveDocument); + + /// + /// Создание документа с диаграммой + /// + /// + /// + bool CreateChartDocument(PluginsConventionSaveDocument saveDocument); + } +} diff --git a/PluginConventionLibrary/Plugins/PluginsConventionElement.cs b/PluginConventionLibrary/Plugins/PluginsConventionElement.cs new file mode 100644 index 0000000..99f7ef9 --- /dev/null +++ b/PluginConventionLibrary/Plugins/PluginsConventionElement.cs @@ -0,0 +1,7 @@ +namespace PluginsConventionLibrary.Plugins +{ + public class PluginsConventionElement + { + public int Id { get; set; } + } +} diff --git a/PluginConventionLibrary/Plugins/PluginsConventionSaveDocument.cs b/PluginConventionLibrary/Plugins/PluginsConventionSaveDocument.cs new file mode 100644 index 0000000..a0a7ce1 --- /dev/null +++ b/PluginConventionLibrary/Plugins/PluginsConventionSaveDocument.cs @@ -0,0 +1,7 @@ +namespace PluginsConventionLibrary.Plugins +{ + public class PluginsConventionSaveDocument + { + public string FileName { get; set; } + } +} diff --git a/PluginConventionLibrary/PluginsConventionLibrary.csproj b/PluginConventionLibrary/PluginsConventionLibrary.csproj new file mode 100644 index 0000000..98a2665 --- /dev/null +++ b/PluginConventionLibrary/PluginsConventionLibrary.csproj @@ -0,0 +1,22 @@ + + + + net6.0-windows + enable + true + enable + + + + + + + + + + + + + + + diff --git a/ShopBusinessLogic/BusinessLogics/CustomerLogic.cs b/ShopBusinessLogic/BusinessLogics/CustomerLogic.cs index 8ca6c50..31c0779 100644 --- a/ShopBusinessLogic/BusinessLogics/CustomerLogic.cs +++ b/ShopBusinessLogic/BusinessLogics/CustomerLogic.cs @@ -4,61 +4,66 @@ using ShopContracts.BusinessLogicsContracts; using ShopContracts.SearchModels; using ShopContracts.StoragesContracts; using ShopContracts.ViewModels; +using ShopDatabaseImplement.Implements; namespace ShopBusinessLogic.BusinessLogics { - public class CustomerLogic : ICustomerLogic - { - private readonly ICustomerStorage _customerStorage; - public CustomerLogic(ICustomerStorage studentStorage) - { - _customerStorage = studentStorage; - } - public void CreateOrUpdate(CustomerBindingModel model) - { - var element = _customerStorage.GetElement( - new CustomerBindingModel + public class CustomerLogic : ICustomerLogic + { + private readonly ICustomerStorage _customerStorage; + public CustomerLogic(ICustomerStorage studentStorage) + { + _customerStorage = studentStorage; + } + public CustomerLogic() + { + _customerStorage = new CustomerStorage(); + } + public void CreateOrUpdate(CustomerBindingModel model) + { + var element = _customerStorage.GetElement( + new CustomerBindingModel { - FIO = model.FIO, - Email = model.Email, - PhotoFilePath = model.PhotoFilePath, - ProductCategoryName = model.ProductCategoryName, - }); - if (element != null && element.Id != model.Id) - { - throw new Exception("Клиент с таким именем уже существует."); - } - if (model.Id.HasValue) - { - _customerStorage.Update(model); - } - else - { - _customerStorage.Insert(model); - } - } + FIO = model.FIO, + Email = model.Email, + PhotoFilePath = model.PhotoFilePath, + ProductCategoryName = model.ProductCategoryName, + }); + if (element != null && element.Id != model.Id) + { + throw new Exception("Клиент с таким именем уже существует."); + } + if (model.Id.HasValue) + { + _customerStorage.Update(model); + } + else + { + _customerStorage.Insert(model); + } + } - public void Delete(CustomerBindingModel model) - { - var element = _customerStorage.GetElement(new CustomerBindingModel { Id = model.Id }); - if (element == null) - { - throw new Exception("Клиент не найден"); - } - _customerStorage.Delete(model); - } + public void Delete(CustomerBindingModel model) + { + var element = _customerStorage.GetElement(new CustomerBindingModel { Id = model.Id }); + if (element == null) + { + throw new Exception("Клиент не найден"); + } + _customerStorage.Delete(model); + } - public List Read(CustomerBindingModel? model) - { - if (model == null) - { - return _customerStorage.GetFullList(); - } - if (model.Id.HasValue) - { - return new List { _customerStorage.GetElement(model) }; - } - return _customerStorage.GetFilteredList(model); - } - } + public List Read(CustomerBindingModel model) + { + if (model == null) + { + return _customerStorage.GetFullList(); + } + if (model.Id.HasValue) + { + return new List { _customerStorage.GetElement(model) }; + } + return _customerStorage.GetFilteredList(model); + } + } } diff --git a/ShopBusinessLogic/BusinessLogics/ProductCategoryLogic.cs b/ShopBusinessLogic/BusinessLogics/ProductCategoryLogic.cs index 744ab2c..1cd836b 100644 --- a/ShopBusinessLogic/BusinessLogics/ProductCategoryLogic.cs +++ b/ShopBusinessLogic/BusinessLogics/ProductCategoryLogic.cs @@ -4,6 +4,7 @@ using ShopContracts.BusinessLogicsContracts; using ShopContracts.SearchModels; using ShopContracts.StoragesContracts; using ShopContracts.ViewModels; +using ShopDatabaseImplement.Implements; namespace ShopBusinessLogic.BusinessLogics @@ -15,8 +16,12 @@ namespace ShopBusinessLogic.BusinessLogics { _productCategoryStorage = productCategoryStorage; } + public ProductCategoryLogic() + { + _productCategoryStorage = new ProductCategoryStorage(); + } - public void CreateOrUpdate(ProductCategoryBindingModel model) + public void CreateOrUpdate(ProductCategoryBindingModel model) { var element = _productCategoryStorage.GetElement( new ProductCategoryBindingModel diff --git a/ShopBusinessLogic/ShopBusinessLogic.csproj b/ShopBusinessLogic/ShopBusinessLogic.csproj index 83c0a88..da83174 100644 --- a/ShopBusinessLogic/ShopBusinessLogic.csproj +++ b/ShopBusinessLogic/ShopBusinessLogic.csproj @@ -12,6 +12,7 @@ + diff --git a/WinFormsLibrary1.sln b/WinFormsLibrary1.sln index 6412b46..767ec1a 100644 --- a/WinFormsLibrary1.sln +++ b/WinFormsLibrary1.sln @@ -3,15 +3,17 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.10.35027.167 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopDataModels", "CustomersDataModels\ShopDataModels.csproj", "{1AAF8752-0281-4ADF-B1CA-21DB683C09F0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopDataModels", "CustomersDataModels\ShopDataModels.csproj", "{1AAF8752-0281-4ADF-B1CA-21DB683C09F0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopContracts", "ShopContracts\ShopContracts.csproj", "{3F5E14F5-BE59-47DC-B5BA-7E0786E26439}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopContracts", "ShopContracts\ShopContracts.csproj", "{3F5E14F5-BE59-47DC-B5BA-7E0786E26439}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopBusinessLogic", "ShopBusinessLogic\ShopBusinessLogic.csproj", "{A2ACE5E0-A039-4712-91E9-4751734971C3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopBusinessLogic", "ShopBusinessLogic\ShopBusinessLogic.csproj", "{A2ACE5E0-A039-4712-91E9-4751734971C3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopDatabaseImplement", "ShopDatabaseImplement\ShopDatabaseImplement.csproj", "{C488F532-5E96-46D9-9E68-451D5A4E6343}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopDatabaseImplement", "ShopDatabaseImplement\ShopDatabaseImplement.csproj", "{C488F532-5E96-46D9-9E68-451D5A4E6343}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopView", "WinFormsLibrary2\ShopView.csproj", "{48DA6809-1C4D-4264-8B81-4609BCE0A44A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopView", "WinFormsLibrary2\ShopView.csproj", "{48DA6809-1C4D-4264-8B81-4609BCE0A44A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginsConventionLibrary", "PluginConventionLibrary\PluginsConventionLibrary.csproj", "{348D0790-F294-4AD3-86A6-CA307BFBECB8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -39,6 +41,10 @@ Global {48DA6809-1C4D-4264-8B81-4609BCE0A44A}.Debug|Any CPU.Build.0 = Debug|Any CPU {48DA6809-1C4D-4264-8B81-4609BCE0A44A}.Release|Any CPU.ActiveCfg = Release|Any CPU {48DA6809-1C4D-4264-8B81-4609BCE0A44A}.Release|Any CPU.Build.0 = Release|Any CPU + {348D0790-F294-4AD3-86A6-CA307BFBECB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {348D0790-F294-4AD3-86A6-CA307BFBECB8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {348D0790-F294-4AD3-86A6-CA307BFBECB8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {348D0790-F294-4AD3-86A6-CA307BFBECB8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/WinFormsLibrary2/FormCustomer.cs b/WinFormsLibrary2/FormCustomer.cs index 29ad574..8e0c699 100644 --- a/WinFormsLibrary2/FormCustomer.cs +++ b/WinFormsLibrary2/FormCustomer.cs @@ -12,88 +12,89 @@ using Lab1.VisualComponents.Exceptions; namespace ShopView { - public partial class FormCustomer : Form - { - private readonly ILogger _logger; - private readonly ICustomerLogic _customerLogic; - private readonly IProductCategoryLogic _productCategoryLogic; - private string imagePath; - BindingList _list; - private int? _id; - public int Id { set { _id = value; } } - private string? _item; + public partial class FormCustomer : Form + { + private readonly ILogger _logger; + private readonly ICustomerLogic _customerLogic; + private readonly IProductCategoryLogic _productCategoryLogic; + private string imagePath; + BindingList _list; + private int? _id; + public int Id { set { _id = value; } } + private string? _item; - List productCategory = new(); - public FormCustomer(ILogger logger, ICustomerLogic customerLogic, IProductCategoryLogic productCategoryLogic) - { - InitializeComponent(); - _logger = logger; - _customerLogic = customerLogic; - _productCategoryLogic = productCategoryLogic; - imagePath = ""; - _list = new BindingList(); - emailField1.EmailRegex = "^\\S+@\\S+\\.\\S+$"; - emailField1.EmailExample = "example@mail.ru"; - } + List productCategory = new(); + public FormCustomer(ILogger logger, ICustomerLogic customerLogic, IProductCategoryLogic productCategoryLogic) + { + InitializeComponent(); + _logger = logger; + _customerLogic = customerLogic; + _productCategoryLogic = productCategoryLogic; + imagePath = ""; + _list = new BindingList(); + emailField1.EmailRegex = "^\\S+@\\S+\\.\\S+$"; + emailField1.EmailExample = "example@mail.ru"; + } - private void buttonSave_Click(object sender, EventArgs e) - { + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } - if (string.IsNullOrEmpty(textBoxFIO.Text)) - { - MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try - { - if (string.IsNullOrEmpty(emailField1.Value)) - { - MessageBox.Show("Введите почту!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - catch (IsNotMatchRegexException) - { - - } + try + { + if (string.IsNullOrEmpty(emailField1.Value)) + { + MessageBox.Show("Введите почту!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + } + catch (IsNotMatchRegexException) + { + MessageBox.Show("Не соответствует шаблону", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } - - if (pictureBox.Image == null) - { - MessageBox.Show("Загрузите фото", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Сохранение студента"); - try - { - _customerLogic.CreateOrUpdate(new CustomerBindingModel - { - Id = _id, - FIO = textBoxFIO.Text, - PhotoFilePath = imagePath, - Email = emailField1.Value, - ProductCategoryName = myListBox1.SelectedItem - }); ; + if (pictureBox.Image == null) + { + MessageBox.Show("Загрузите фото", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения студента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - + _logger.LogInformation("Сохранение студента"); + try + { + _customerLogic.CreateOrUpdate(new CustomerBindingModel + { + Id = _id, + FIO = textBoxFIO.Text, + PhotoFilePath = imagePath, + Email = emailField1.Value, + ProductCategoryName = myListBox1.SelectedItem + }); - private void buttonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения студента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void FormCustomer_Load(object sender, EventArgs e) - { + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void FormCustomer_Load(object sender, EventArgs e) + { LoadData(); if (_id.HasValue) { @@ -102,86 +103,80 @@ namespace ShopView var view = _customerLogic.Read(new CustomerBindingModel { Id = _id.Value })?.FirstOrDefault(); if (view != null) { - textBoxFIO.Text = view.FIO ; + textBoxFIO.Text = view.FIO; + imagePath = view.PhotoFilePath ?? string.Empty; + // Используем рефлексию для доступа к textBox1 в emailField1 var textBoxField = typeof(EmailField).GetField("textBox1", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (textBoxField?.GetValue(emailField1) is TextBox innerTextBox) { - innerTextBox.Text = view.Email; - } - - - imagePath = view.PhotoFilePath; - - if (!string.IsNullOrEmpty(view.PhotoFilePath) && File.Exists(view.PhotoFilePath)) - { - pictureBox.Image = Image.FromFile(view.PhotoFilePath); + innerTextBox.Text = view.Email ?? string.Empty; // Устанавливаем значение напрямую } + // Устанавливаем другие значения, как и раньше string[] dirs = view.ProductCategoryName.Split(";"); foreach (var dir in dirs) { myListBox1.SelectedItem = dir; } - } - else - { - _logger.LogWarning("Клиент с указанным ID не найден."); + if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath)) + { + pictureBox.Image = Image.FromFile(imagePath); + } } } catch (Exception ex) { - _logger.LogError(ex, "Ошибка при загрузке данных клиента."); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } - private void LoadData() - { - _logger.LogInformation("Загрузка категории товаров"); - try - { - var list = _productCategoryLogic.Read(null); + private void LoadData() + { + _logger.LogInformation("Загрузка категории товаров"); + try + { + var list = _productCategoryLogic.Read(null); myListBox1.Clear(); - productCategory.Clear(); - _list.Clear(); - if (list != null) - { - foreach (var item in list) - { - productCategory.Add(item.Name); - _list.Add(new ProductCategoryBindingModel + productCategory.Clear(); + _list.Clear(); + if (list != null) + { + foreach (var item in list) + { + productCategory.Add(item.Name); + _list.Add(new ProductCategoryBindingModel { - Id = item.Id, - Name = item.Name, - }); - } - } + Id = item.Id, + Name = item.Name, + }); + } + } myListBox1.AddItems(productCategory); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки категории товаров"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки категории товаров"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void buttonAddPhoto_Click(object sender, EventArgs e) - { - OpenFileDialog openFileDialog = new() - { - Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*" - }; + private void buttonAddPhoto_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new() + { + Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*" + }; - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - imagePath = openFileDialog.FileName; - pictureBox.Image = Image.FromFile(imagePath); - } - } - } -} + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + imagePath = openFileDialog.FileName; + pictureBox.Image = Image.FromFile(imagePath); + } + } + } +} \ No newline at end of file diff --git a/WinFormsLibrary2/FormMain.Designer.cs b/WinFormsLibrary2/FormMain.Designer.cs index 45980bb..550cd8c 100644 --- a/WinFormsLibrary2/FormMain.Designer.cs +++ b/WinFormsLibrary2/FormMain.Designer.cs @@ -51,7 +51,6 @@ this.tableOfValues.Location = new System.Drawing.Point(0, 0); this.tableOfValues.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.tableOfValues.Name = "tableOfValues"; - this.tableOfValues.IndexProperty = -1; this.tableOfValues.Size = new System.Drawing.Size(405, 302); this.tableOfValues.TabIndex = 0; // diff --git a/WinFormsLibrary2/FormMain.cs b/WinFormsLibrary2/FormMain.cs index 5efbf2e..12bc3bb 100644 --- a/WinFormsLibrary2/FormMain.cs +++ b/WinFormsLibrary2/FormMain.cs @@ -62,7 +62,7 @@ namespace ShopView private void FormMain_Load(object sender, EventArgs e) { - + LoadData(); } @@ -81,14 +81,12 @@ namespace ShopView ColumnInfo ci1 = new ColumnInfo("ID", 100, false, "Id"); ColumnInfo ci2 = new ColumnInfo("FIO", 100, true, "ФИО"); ColumnInfo ci3 = new ColumnInfo("ProductCategoryName", 80, true, "Категория товара"); - ColumnInfo ci5 = new ColumnInfo("PhotoFilePath", 80, false, "PhotoFilePath"); - ColumnInfo ci4 = new ColumnInfo("Email", 80, true, "Электронная почта"); + ColumnInfo ci4 = new ColumnInfo("Email", 80, true, "Электронная почта"); List lst = new List(); lst.Add(ci1); lst.Add(ci2); lst.Add(ci3); lst.Add(ci4); - lst.Add(ci5); tableOfValues.ColumnConfiguration(new TableConfiguration(lst)); } @@ -203,7 +201,7 @@ namespace ShopView { foreach (var item in list) { - data.Add(new CustomerBindingModel() { Id = item.Id, FIO = item.FIO, Email = item.Email, ProductCategoryName = item.ProductCategoryName}); + data.Add(new CustomerBindingModel() { Id = item.Id, FIO = item.FIO, Email = item.Email, ProductCategoryName = item.ProductCategoryName }); } } TableDocumentInfo tableWord = new(dialog.FileName, "Таблица с клиентами", columnDefinitions, columnDefinitions2, data, mergedColumns); @@ -249,8 +247,8 @@ namespace ShopView { foreach (var item in data) { - Data.Add(item.Item1, new[] {item.Item2 }); - + Data.Add(item.Item1, new[] { item.Item2 }); + } } PdfChartComponent pdfChartComponent = new PdfChartComponent(); @@ -275,4 +273,4 @@ namespace ShopView LoadData(); } } -} +} \ No newline at end of file diff --git a/WinFormsLibrary2/FormMainPlugins.Designer.cs b/WinFormsLibrary2/FormMainPlugins.Designer.cs new file mode 100644 index 0000000..479e4cb --- /dev/null +++ b/WinFormsLibrary2/FormMainPlugins.Designer.cs @@ -0,0 +1,174 @@ +namespace ShopView +{ + partial class FormMainPlugins + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + menuStrip = new MenuStrip(); + ControlsStripMenuItem = new ToolStripMenuItem(); + ActionsToolStripMenuItem = new ToolStripMenuItem(); + AddElementToolStripMenuItem = new ToolStripMenuItem(); + UpdElementToolStripMenuItem = new ToolStripMenuItem(); + DelElementToolStripMenuItem = new ToolStripMenuItem(); + DocsToolStripMenuItem = new ToolStripMenuItem(); + SimpleDocToolStripMenuItem = new ToolStripMenuItem(); + TableDocToolStripMenuItem = new ToolStripMenuItem(); + ChartDocToolStripMenuItem = new ToolStripMenuItem(); + panelControl = new Panel(); + excelComponent1 = new COP.ExcelComponent(components); + gistogramPdfComponent31 = new KOP.PDFComponents.PdfChartComponent(components); + componentWord21 = new Lab1.LogicalComponents.TableDocument(components); + menuStrip.SuspendLayout(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { ControlsStripMenuItem, ActionsToolStripMenuItem, DocsToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Padding = new Padding(7, 3, 0, 3); + menuStrip.Size = new Size(914, 30); + menuStrip.TabIndex = 0; + menuStrip.Text = "Меню"; + // + // ControlsStripMenuItem + // + ControlsStripMenuItem.Name = "ControlsStripMenuItem"; + ControlsStripMenuItem.Size = new Size(117, 24); + ControlsStripMenuItem.Text = "Справочники"; + // + // ActionsToolStripMenuItem + // + ActionsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { AddElementToolStripMenuItem, UpdElementToolStripMenuItem, DelElementToolStripMenuItem }); + ActionsToolStripMenuItem.Name = "ActionsToolStripMenuItem"; + ActionsToolStripMenuItem.Size = new Size(88, 24); + ActionsToolStripMenuItem.Text = "Действия"; + // + // AddElementToolStripMenuItem + // + AddElementToolStripMenuItem.Name = "AddElementToolStripMenuItem"; + AddElementToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.A; + AddElementToolStripMenuItem.Size = new Size(213, 26); + AddElementToolStripMenuItem.Text = "Добавить"; + AddElementToolStripMenuItem.Click += AddElementToolStripMenuItem_Click; + // + // UpdElementToolStripMenuItem + // + UpdElementToolStripMenuItem.Name = "UpdElementToolStripMenuItem"; + UpdElementToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U; + UpdElementToolStripMenuItem.Size = new Size(213, 26); + UpdElementToolStripMenuItem.Text = "Изменить"; + UpdElementToolStripMenuItem.Click += UpdElementToolStripMenuItem_Click; + // + // DelElementToolStripMenuItem + // + DelElementToolStripMenuItem.Name = "DelElementToolStripMenuItem"; + DelElementToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.D; + DelElementToolStripMenuItem.Size = new Size(213, 26); + DelElementToolStripMenuItem.Text = "Удалить"; + DelElementToolStripMenuItem.Click += DelElementToolStripMenuItem_Click; + // + // DocsToolStripMenuItem + // + DocsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SimpleDocToolStripMenuItem, TableDocToolStripMenuItem, ChartDocToolStripMenuItem }); + DocsToolStripMenuItem.Name = "DocsToolStripMenuItem"; + DocsToolStripMenuItem.Size = new Size(101, 24); + DocsToolStripMenuItem.Text = "Документы"; + // + // SimpleDocToolStripMenuItem + // + SimpleDocToolStripMenuItem.Name = "SimpleDocToolStripMenuItem"; + SimpleDocToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + SimpleDocToolStripMenuItem.Size = new Size(290, 26); + SimpleDocToolStripMenuItem.Text = "Excel с фото"; + SimpleDocToolStripMenuItem.Click += SimpleDocToolStripMenuItem_Click; + // + // TableDocToolStripMenuItem + // + TableDocToolStripMenuItem.Name = "TableDocToolStripMenuItem"; + TableDocToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; + TableDocToolStripMenuItem.Size = new Size(290, 26); + TableDocToolStripMenuItem.Text = "Документ с таблицей"; + TableDocToolStripMenuItem.Click += TableDocToolStripMenuItem_Click; + // + // ChartDocToolStripMenuItem + // + ChartDocToolStripMenuItem.Name = "ChartDocToolStripMenuItem"; + ChartDocToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; + ChartDocToolStripMenuItem.Size = new Size(290, 26); + ChartDocToolStripMenuItem.Text = "Диаграмма"; + ChartDocToolStripMenuItem.Click += ChartDocToolStripMenuItem_Click; + // + // panelControl + // + panelControl.Dock = DockStyle.Fill; + panelControl.Location = new Point(0, 30); + panelControl.Margin = new Padding(3, 4, 3, 4); + panelControl.Name = "panelControl"; + panelControl.Size = new Size(914, 570); + panelControl.TabIndex = 1; + // + // FormMainPlugins + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(914, 600); + Controls.Add(panelControl); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Margin = new Padding(3, 4, 3, 4); + Name = "FormMainPlugins"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Главная форма"; + WindowState = FormWindowState.Maximized; + KeyDown += FormMainPlugins_KeyDown; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.MenuStrip menuStrip; + private System.Windows.Forms.ToolStripMenuItem ControlsStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem DocsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem SimpleDocToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem TableDocToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem ChartDocToolStripMenuItem; + private System.Windows.Forms.Panel panelControl; + private System.Windows.Forms.ToolStripMenuItem ActionsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem AddElementToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem UpdElementToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem DelElementToolStripMenuItem; + private COP.ExcelComponent excelComponent1; + private KOP.PDFComponents.PdfChartComponent gistogramPdfComponent31; + private Lab1.LogicalComponents.TableDocument componentWord21; + } +} \ No newline at end of file diff --git a/WinFormsLibrary2/FormMainPlugins.cs b/WinFormsLibrary2/FormMainPlugins.cs new file mode 100644 index 0000000..e258730 --- /dev/null +++ b/WinFormsLibrary2/FormMainPlugins.cs @@ -0,0 +1,163 @@ +using PluginsConventionLibrary.Plugins; + +namespace ShopView +{ + public partial class FormMainPlugins : Form + { + private readonly Dictionary _plugins; + private string _selectedPlugin; + private ContextMenuStrip contextMenu = new ContextMenuStrip(); + public FormMainPlugins() + { + InitializeComponent(); + _plugins = LoadPlugins(); + _selectedPlugin = string.Empty; + } + private Dictionary LoadPlugins() + { + PluginsManager manager = new(); + var plugins = manager.plugins_dictionary; + + ToolStripItem[] toolStripItems = new ToolStripItem[plugins.Count]; + int i = 0; + if (plugins.Count > 0) + { + foreach (var plugin in plugins) + { + ToolStripMenuItem itemMenu = new() + { + Text = plugin.Value.PluginName + }; + itemMenu.Click += (sender, e) => + { + _selectedPlugin = plugin.Value.PluginName; + panelControl.Controls.Clear(); + panelControl.Controls.Add(_plugins[_selectedPlugin].GetControl); + panelControl.Controls[0].Dock = DockStyle.Fill; + }; + toolStripItems[i] = itemMenu; + i++; + } + ControlsStripMenuItem.DropDownItems.AddRange(toolStripItems); + } + return plugins; + } + private void FormMainPlugins_KeyDown(object sender, KeyEventArgs e) + { + if (!e.Control) + { + return; + } + switch (e.KeyCode) + { + case Keys.A: + AddNewElement(); + break; + case Keys.U: + UpdateElement(); + break; + case Keys.D: + DeleteElement(); + break; + case Keys.S: + CreateSimpleDoc(); + break; + case Keys.T: + CreateTableDoc(); + break; + case Keys.C: + CreateChartDoc(); + break; + } + } + private void AddNewElement() + { + var form = _plugins[_selectedPlugin].GetForm(null); + if (form != null && form.ShowDialog() == DialogResult.OK) + { + _plugins[_selectedPlugin].ReloadData(); + } + } + private void UpdateElement() + { + var element = _plugins[_selectedPlugin].GetElement; + if (element == null) + { + MessageBox.Show("Нет выбранного элемента", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + var form = _plugins[_selectedPlugin].GetForm(element); + if (form != null && form.ShowDialog() == DialogResult.OK) + { + _plugins[_selectedPlugin].ReloadData(); + } + } + private void DeleteElement() + { + if (MessageBox.Show("Удалить выбранный элемент", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + var element = _plugins[_selectedPlugin].GetElement; + if (element == null) + { + MessageBox.Show("Нет выбранного элемента", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (_plugins[_selectedPlugin].DeleteElement(element)) + { + _plugins[_selectedPlugin].ReloadData(); + } + } + private void CreateSimpleDoc() + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + + if (_plugins[_selectedPlugin].CreateSimpleDocument(new PluginsConventionSaveDocument { FileName = dialog.FileName })) + { + MessageBox.Show("Документ сохранен", "Создание документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Ошибка при создании документа", + "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void CreateTableDoc() + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (_plugins[_selectedPlugin].CreateTableDocument(new PluginsConventionSaveDocument())) + { + MessageBox.Show("Документ сохранен", "Создание документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Ошибка при создании документа", + "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void CreateChartDoc() + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (_plugins[_selectedPlugin].CreateChartDocument(new + PluginsConventionSaveDocument())) + { + MessageBox.Show("Документ сохранен", "Создание документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Ошибка при создании документа", + "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void AddElementToolStripMenuItem_Click(object sender, EventArgs e) => AddNewElement(); + private void UpdElementToolStripMenuItem_Click(object sender, EventArgs e) => UpdateElement(); + private void DelElementToolStripMenuItem_Click(object sender, EventArgs e) => DeleteElement(); + private void SimpleDocToolStripMenuItem_Click(object sender, EventArgs e) => CreateSimpleDoc(); + private void TableDocToolStripMenuItem_Click(object sender, EventArgs e) => CreateTableDoc(); + private void ChartDocToolStripMenuItem_Click(object sender, EventArgs e) => CreateChartDoc(); + } +} diff --git a/WinFormsLibrary2/FormMainPlugins.resx b/WinFormsLibrary2/FormMainPlugins.resx new file mode 100644 index 0000000..725d1f0 --- /dev/null +++ b/WinFormsLibrary2/FormMainPlugins.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 125, 17 + + + 275, 17 + + + 478, 17 + + \ No newline at end of file diff --git a/WinFormsLibrary2/Model/TestModel.cs b/WinFormsLibrary2/Model/TestModel.cs new file mode 100644 index 0000000..0d29b2b --- /dev/null +++ b/WinFormsLibrary2/Model/TestModel.cs @@ -0,0 +1,13 @@ +namespace ShopView +{ + public class TestModel + { + public int Id { get; set; } + + public string FIO { get; set; } + + public string ProductCategoryName { get; set; } + + public string Email { get; set; } + } +} diff --git a/WinFormsLibrary2/PluginsManager.cs b/WinFormsLibrary2/PluginsManager.cs new file mode 100644 index 0000000..e912c25 --- /dev/null +++ b/WinFormsLibrary2/PluginsManager.cs @@ -0,0 +1,43 @@ +using PluginsConventionLibrary.Plugins; +using System.ComponentModel.Composition; +using System.ComponentModel.Composition.Hosting; + +namespace ShopView +{ + public class PluginsManager + { + //Тег, указывающий, что plugins должны быть заполнены CompositionContainer + [ImportMany(typeof(IPluginsConvention))] + IEnumerable plugins { get; set; } + + public readonly Dictionary plugins_dictionary = new Dictionary(); + + public PluginsManager() + { + AggregateCatalog catalog = new AggregateCatalog(); + catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory)); + catalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"))); + + //Контейнер композиции + CompositionContainer container = new CompositionContainer(catalog); + try + { + container.ComposeParts(this); + } + catch (CompositionException compositionException) + { + MessageBox.Show(compositionException.ToString()); + } + if (plugins.Any()) + { + plugins + .ToList() + .ForEach(p => + { + if (!plugins_dictionary.Keys.Contains(p.PluginName)) + plugins_dictionary.Add(p.PluginName, p); + }); + } + } + } +} \ No newline at end of file diff --git a/WinFormsLibrary2/Program.cs b/WinFormsLibrary2/Program.cs index f79f86f..64c6754 100644 --- a/WinFormsLibrary2/Program.cs +++ b/WinFormsLibrary2/Program.cs @@ -23,7 +23,7 @@ namespace ShopView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -37,9 +37,9 @@ namespace ShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } + + services.AddTransient(); + + } } } \ No newline at end of file diff --git a/WinFormsLibrary2/ShopView.csproj b/WinFormsLibrary2/ShopView.csproj index b018d34..c29eae0 100644 --- a/WinFormsLibrary2/ShopView.csproj +++ b/WinFormsLibrary2/ShopView.csproj @@ -10,7 +10,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -19,10 +19,12 @@ + +