diff --git a/Laba3/MainForm.Designer.cs b/Laba3/MainForm.Designer.cs index 30b9dc5..3533038 100644 --- a/Laba3/MainForm.Designer.cs +++ b/Laba3/MainForm.Designer.cs @@ -1,4 +1,4 @@ -namespace Laba3 +namespace View { partial class MainForm { diff --git a/Laba3/MainForm.cs b/Laba3/MainForm.cs index c0e33f2..0c27a46 100644 --- a/Laba3/MainForm.cs +++ b/Laba3/MainForm.cs @@ -10,7 +10,7 @@ using WinFormsLibrary1; using WinFormsLibrary1.Models; using View.ViewModels; -namespace Laba3 +namespace View { public partial class MainForm : Form { diff --git a/Laba3/ProductForm.Designer.cs b/Laba3/ProductForm.Designer.cs index c64b5a8..247f34f 100644 --- a/Laba3/ProductForm.Designer.cs +++ b/Laba3/ProductForm.Designer.cs @@ -1,4 +1,4 @@ -namespace Laba3 +namespace PluginsConvention14 { partial class ProductForm { diff --git a/Laba3/ProductForm.cs b/Laba3/ProductForm.cs index 3e88d28..63fac49 100644 --- a/Laba3/ProductForm.cs +++ b/Laba3/ProductForm.cs @@ -12,7 +12,7 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace Laba3 +namespace View { public partial class ProductForm : Form { diff --git a/Laba3/Program.cs b/Laba3/Program.cs index 8d5d27d..242e123 100644 --- a/Laba3/Program.cs +++ b/Laba3/Program.cs @@ -1,7 +1,7 @@ using Data.Repositories; using Data; -namespace Laba3 +namespace View { internal static class Program { diff --git a/Library14Petrushin/Library14Petrushin.sln b/Library14Petrushin/Library14Petrushin.sln index 7d6f1d1..5985868 100644 --- a/Library14Petrushin/Library14Petrushin.sln +++ b/Library14Petrushin/Library14Petrushin.sln @@ -9,7 +9,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "View", "..\Laba3\View.cspro EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Data", "..\Models\Data.csproj", "{DC70937E-903F-4BAA-A774-80D01EC5B75A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginsConventionLibrary", "..\PluginsConventionLibrary\PluginsConventionLibrary.csproj", "{3E1D3C18-6808-408F-B8C9-CD63F22E4A4A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginsConvention14", "..\PluginsConvention14\PluginsConvention14.csproj", "{C6CB6D7F-9DCF-414B-8544-1AE4FDE373CD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -29,10 +29,10 @@ Global {DC70937E-903F-4BAA-A774-80D01EC5B75A}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC70937E-903F-4BAA-A774-80D01EC5B75A}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC70937E-903F-4BAA-A774-80D01EC5B75A}.Release|Any CPU.Build.0 = Release|Any CPU - {3E1D3C18-6808-408F-B8C9-CD63F22E4A4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3E1D3C18-6808-408F-B8C9-CD63F22E4A4A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3E1D3C18-6808-408F-B8C9-CD63F22E4A4A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3E1D3C18-6808-408F-B8C9-CD63F22E4A4A}.Release|Any CPU.Build.0 = Release|Any CPU + {C6CB6D7F-9DCF-414B-8544-1AE4FDE373CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C6CB6D7F-9DCF-414B-8544-1AE4FDE373CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C6CB6D7F-9DCF-414B-8544-1AE4FDE373CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C6CB6D7F-9DCF-414B-8544-1AE4FDE373CD}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/PluginsConvention14/Forms/MainForm.Designer.cs b/PluginsConvention14/Forms/MainForm.Designer.cs new file mode 100644 index 0000000..53728bf --- /dev/null +++ b/PluginsConvention14/Forms/MainForm.Designer.cs @@ -0,0 +1,178 @@ +namespace PluginsConvention14 +{ + partial class MainForm + { + /// + /// 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(); + menuStrip1 = new MenuStrip(); + createToolStripMenuItem = new ToolStripMenuItem(); + updateToolStripMenuItem = new ToolStripMenuItem(); + deleteToolStripMenuItem = new ToolStripMenuItem(); + manufacturerToolStripMenuItem = new ToolStripMenuItem(); + documentsToolStripMenuItem = new ToolStripMenuItem(); + pdfImageToolStripMenuItem = new ToolStripMenuItem(); + exelTableToolStripMenuItem = new ToolStripMenuItem(); + wordGistToolStripMenuItem = new ToolStripMenuItem(); + outputTableResults = new Library15Gerimovich.OutputTableResults(); + pdfImg = new Library14Petrushin.PdfImg(components); + wordDiagramComponent = new Library15Gerimovich.WordDiagramComponent(components); + componentTable = new WinFormsLibrary1.ComponentTable(components); + saveFileDialogPdf = new SaveFileDialog(); + saveFileDialogWord = new SaveFileDialog(); + saveFileDialogExel = new SaveFileDialog(); + menuStrip1.SuspendLayout(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { createToolStripMenuItem, updateToolStripMenuItem, deleteToolStripMenuItem, manufacturerToolStripMenuItem, documentsToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(480, 28); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // createToolStripMenuItem + // + createToolStripMenuItem.Name = "createToolStripMenuItem"; + createToolStripMenuItem.Size = new Size(66, 24); + createToolStripMenuItem.Text = "Create"; + createToolStripMenuItem.Click += addToolStripMenuItem_Click; + // + // updateToolStripMenuItem + // + updateToolStripMenuItem.Name = "updateToolStripMenuItem"; + updateToolStripMenuItem.Size = new Size(72, 24); + updateToolStripMenuItem.Text = "Update"; + updateToolStripMenuItem.Click += editToolStripMenuItem_Click; + // + // deleteToolStripMenuItem + // + deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; + deleteToolStripMenuItem.Size = new Size(67, 24); + deleteToolStripMenuItem.Text = "Delete"; + deleteToolStripMenuItem.Click += deleteToolStripMenuItem_Click; + // + // manufacturerToolStripMenuItem + // + manufacturerToolStripMenuItem.Name = "manufacturerToolStripMenuItem"; + manufacturerToolStripMenuItem.Size = new Size(111, 24); + manufacturerToolStripMenuItem.Text = "Manufacturer"; + manufacturerToolStripMenuItem.Click += manufacturersToolStripMenuItem_Click; + // + // documentsToolStripMenuItem + // + documentsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pdfImageToolStripMenuItem, exelTableToolStripMenuItem, wordGistToolStripMenuItem }); + documentsToolStripMenuItem.Name = "documentsToolStripMenuItem"; + documentsToolStripMenuItem.Size = new Size(98, 24); + documentsToolStripMenuItem.Text = "Documents"; + // + // pdfImageToolStripMenuItem + // + pdfImageToolStripMenuItem.Name = "pdfImageToolStripMenuItem"; + pdfImageToolStripMenuItem.Size = new Size(159, 26); + pdfImageToolStripMenuItem.Text = "Pdf Image"; + pdfImageToolStripMenuItem.Click += createSimpleDocumentToolStripMenuItem_Click; + // + // exelTableToolStripMenuItem + // + exelTableToolStripMenuItem.Name = "exelTableToolStripMenuItem"; + exelTableToolStripMenuItem.Size = new Size(159, 26); + exelTableToolStripMenuItem.Text = "Exel table"; + exelTableToolStripMenuItem.Click += createCustomTableDocumentToolStripMenuItem_Click; + // + // wordGistToolStripMenuItem + // + wordGistToolStripMenuItem.Name = "wordGistToolStripMenuItem"; + wordGistToolStripMenuItem.Size = new Size(159, 26); + wordGistToolStripMenuItem.Text = "Word gist"; + wordGistToolStripMenuItem.Click += createChartDocumentToolStripMenuItem_Click; + // + // outputTableResults + // + outputTableResults.Location = new Point(12, 32); + outputTableResults.Margin = new Padding(3, 4, 3, 4); + outputTableResults.Name = "outputTableResults"; + outputTableResults.SelectedRow = -1; + outputTableResults.Size = new Size(467, 308); + outputTableResults.TabIndex = 1; + // + // saveFileDialogPdf + // + saveFileDialogPdf.FileName = "Products.pdf"; + saveFileDialogPdf.Filter = "PDF Files (*.pdf)|*.pdf"; + saveFileDialogPdf.Title = "Save PDF Document"; + // + // saveFileDialogWord + // + saveFileDialogWord.FileName = "Diagram.docx"; + saveFileDialogWord.Filter = "Word Files (*.docx)|*.docx"; + saveFileDialogWord.Title = "Save Word Document"; + // + // saveFileDialogExel + // + saveFileDialogExel.FileName = "ProductReport.xlsx"; + saveFileDialogExel.Filter = "Excel Files (*.xlsx)|*.xlsx"; + saveFileDialogExel.Title = "Save Excel Document"; + // + // MainForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(480, 351); + Controls.Add(outputTableResults); + Controls.Add(menuStrip1); + KeyPreview = true; + MainMenuStrip = menuStrip1; + Name = "MainForm"; + Text = "Form1"; + KeyDown += MainForm_KeyDown; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private MenuStrip menuStrip1; + private ToolStripMenuItem createToolStripMenuItem; + private ToolStripMenuItem updateToolStripMenuItem; + private Library15Gerimovich.OutputTableResults outputTableResults; + private ToolStripMenuItem deleteToolStripMenuItem; + private ToolStripMenuItem manufacturerToolStripMenuItem; + private ToolStripMenuItem documentsToolStripMenuItem; + private ToolStripMenuItem pdfImageToolStripMenuItem; + private ToolStripMenuItem exelTableToolStripMenuItem; + private ToolStripMenuItem wordGistToolStripMenuItem; + private Library14Petrushin.PdfImg pdfImg; + private Library15Gerimovich.WordDiagramComponent wordDiagramComponent; + private WinFormsLibrary1.ComponentTable componentTable; + } +} diff --git a/PluginsConvention14/Forms/MainForm.cs b/PluginsConvention14/Forms/MainForm.cs new file mode 100644 index 0000000..23c22ac --- /dev/null +++ b/PluginsConvention14/Forms/MainForm.cs @@ -0,0 +1,284 @@ +using Data; +using Data.Repositories; +using View; +using System.Windows.Forms; +using Data.Models; +using Library14Petrushin; +using Library15Gerimovich.OfficePackage.HelperModels; +using Library15Gerimovich; +using WinFormsLibrary1; +using WinFormsLibrary1.Models; +using View.ViewModels; + +namespace PluginsConvention14 +{ + public partial class MainForm : Form + { + private readonly IProductRepository _productRepository; + private readonly IManufacturerRepository _manufacturerRepository; + private SaveFileDialog saveFileDialogPdf; + private SaveFileDialog saveFileDialogWord; + private SaveFileDialog saveFileDialogExel; + + public MainForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository) + { + InitializeComponent(); + _productRepository = productRepository; + _manufacturerRepository = manufacturerRepository; + InitializeOutputTableResults(); + LoadProducts(); + } + + private void InitializeOutputTableResults() + { + outputTableResults.ConfigureColumns(new List + { + new ColumnInfo("", 0, false, "Id"), + new ColumnInfo("Name", 150, true, "Name"), + new ColumnInfo("ManufacturerNameManufacturerName", 150, true, "ManufacturerName"), + new ColumnInfo("DeliveryDate", 50, true, "DeliveryDate"), + }); + + } + + private void LoadProducts() + { + var products = _productRepository.GetAllProducts(); + outputTableResults.ClearGrid(); + foreach (var product in products) + { + outputTableResults.InsertValue(product); + } + } + + private void addToolStripMenuItem_Click(object sender, EventArgs e) + { + var productForm = new ProductForm(_productRepository, _manufacturerRepository); + if (productForm.ShowDialog() == DialogResult.OK) + { + LoadProducts(); + } + } + + private void editToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + var selectedProductId = outputTableResults.GetSelectedObject().Id; + var selectedProduct = _productRepository.GetProductById(selectedProductId); + var productForm = new ProductForm(_productRepository, _manufacturerRepository, selectedProduct); + if (productForm.ShowDialog() == DialogResult.OK) + { + LoadProducts(); + } + } + catch (Exception ex) { + MessageBox.Show(ex.ToString()); + } + } + + private void deleteToolStripMenuItem_Click(object sender, EventArgs e) + { + var selectedProductId = outputTableResults.GetSelectedObject().Id; + if (MessageBox.Show("Are you sure you want to delete this product?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _productRepository.DeleteProduct(selectedProductId); + LoadProducts(); + } + } + + private void manufacturersToolStripMenuItem_Click(object sender, EventArgs e) + { + var manufacturerForm = new ManufacturerForm(_manufacturerRepository); + manufacturerForm.ShowDialog(); + } + + private void createSimpleDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем изображения из базы данных + var images = GetImagesFromDatabase(); + + if (images.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogPdf.ShowDialog() == DialogResult.OK) + { + // Создаем компонент PdfImg + var pdfImg = new Library14Petrushin.PdfImg(); + + // Путь для сохранения PDF-документа + string fileName = saveFileDialogPdf.FileName; + + // Заголовок документа + string documentTitle = "Product Images"; + + // Создаем PDF-документ + pdfImg.CreatePdfDocument(fileName, documentTitle, images); + + // Уведомление об успешной загрузке + MessageBox.Show("PDF document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No images found in the database."); + } + } + + private void createCustomTableDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем все продукты из базы данных + var products = GetAllProducts(); + + if (products.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogExel.ShowDialog() == DialogResult.OK) + { + // Создаем объекты MergeCell и Column + var mergeCells = new List + { + new MergeCell("Product", new int[] {1, 2}) + }; + + var columns = new List + { + new Column("Id", "Id", 10), + new Column("Name", "Name", 20), + new Column("ManufacturerName", "ManufacturerName", 20), + new Column("DeliveryDate", "DeliveryDate", 20) + }; + + // Создаем компонент ComponentTable + var componentTable = new ComponentTable(); + + // Конвертируем продукты в представление для таблицы + var tableItems = ProductTableItem.ConvertProductsToTableItems(products); + + // Создаем документ Excel + componentTable.CreateDocument(saveFileDialogExel.FileName, "Product Report", mergeCells, columns, tableItems); + + // Уведомление об успешной загрузке + MessageBox.Show("Excel document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No products found in the database."); + } + } + + private void createChartDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем данные о количестве продукции каждого производителя + var productCounts = GetProductCountsByManufacturer(); + + if (productCounts.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogWord.ShowDialog() == DialogResult.OK) + { + // Создаем объект WordDiagramInfo + var diagramInfo = new WordDiagramInfo + { + FileName = saveFileDialogWord.FileName, + Title = "Product Count by Manufacturer", + ChartTitle = "Product Count", + LegendLocation = Library15Gerimovich.OfficePackage.HelperEnums.WordDiagramLegendLocation.Top, + Series = new WordDiagramSeries + { + SeriesName = "Product Count", + Data = productCounts + } + }; + + // Создаем диаграмму в Word + wordDiagramComponent.CreateDiagram(diagramInfo); + + // Уведомление об успешной загрузке + MessageBox.Show("Word document with chart created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No products found in the database."); + } + } + + // бизнес логика + + private void MainForm_KeyDown(object sender, KeyEventArgs e) + { + if (e.Control) + { + switch (e.KeyCode) + { + case Keys.A: + addToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.U: + editToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.D: + deleteToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.S: + createSimpleDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.T: + createCustomTableDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.C: + createChartDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + } + } + } + + private List GetImagesFromDatabase() + { + var images = new List(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (product.Image != null) + { + // Создаем временный файл для сохранения изображения + string tempFilePath = Path.GetTempFileName(); + File.WriteAllBytes(tempFilePath, product.Image); + + // Добавляем путь к временному файлу в список + images.Add(new ImageData { ImagePath = tempFilePath }); + } + } + + return images; + } + + private Dictionary GetProductCountsByManufacturer() + { + var productCounts = new Dictionary(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (productCounts.ContainsKey(product.ManufacturerName)) + { + productCounts[product.ManufacturerName]++; + } + else + { + productCounts[product.ManufacturerName] = 1; + } + } + + return productCounts; + } + + private List GetAllProducts() + { + return _productRepository.GetAllProducts().ToList(); + } + } +} diff --git a/PluginsConvention14/Forms/MainForm.resx b/PluginsConvention14/Forms/MainForm.resx new file mode 100644 index 0000000..6ce8bc4 --- /dev/null +++ b/PluginsConvention14/Forms/MainForm.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 572, 17 + + + 708, 17 + + + 813, 17 + + + 1039, 17 + + + 17, 17 + + + 195, 17 + + + 388, 17 + + \ No newline at end of file diff --git a/PluginsConvention14/Forms/ManufacturerForm.Designer.cs b/PluginsConvention14/Forms/ManufacturerForm.Designer.cs new file mode 100644 index 0000000..fdb5cae --- /dev/null +++ b/PluginsConvention14/Forms/ManufacturerForm.Designer.cs @@ -0,0 +1,64 @@ +namespace ViewPluginsConvention14 +{ + partial class ManufacturerForm + { + /// + /// 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.Size = new Size(711, 426); + dataGridView.TabIndex = 0; + dataGridView.CellValueChanged += dataGridView_CellValueChanged; + dataGridView.UserAddedRow += dataGridView_UserAddedRow; + dataGridView.UserDeletingRow += dataGridView_UserDeletingRow; + dataGridView.KeyDown += dataGridView_KeyDown; + // + // ManufacturerForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(731, 450); + Controls.Add(dataGridView); + Name = "ManufacturerForm"; + Text = "ManufacturerForm"; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/PluginsConvention14/Forms/ManufacturerForm.cs b/PluginsConvention14/Forms/ManufacturerForm.cs new file mode 100644 index 0000000..cf22e6f --- /dev/null +++ b/PluginsConvention14/Forms/ManufacturerForm.cs @@ -0,0 +1,95 @@ +using Data.Models; +using Data.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PluginsConvention14 +{ + public partial class ManufacturerForm : Form + { + private readonly IManufacturerRepository _manufacturerRepository; + + public ManufacturerForm(IManufacturerRepository manufacturerRepository) + { + InitializeComponent(); + _manufacturerRepository = manufacturerRepository; + LoadManufacturers(); + } + + private void LoadManufacturers() + { + var manufacturers = _manufacturerRepository.GetAllManufacturers().ToList(); + dataGridView.DataSource = manufacturers; + } + + private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + var manufacturer = dataGridView.Rows[e.RowIndex].DataBoundItem as Manufacturer; + if (manufacturer != null) + { + _manufacturerRepository.UpdateManufacturer(manufacturer); + } + } + } + + private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) + { + var manufacturer = e.Row.DataBoundItem as Manufacturer; + if (manufacturer != null) + { + if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _manufacturerRepository.DeleteManufacturer(manufacturer.Id); + } + else + { + e.Cancel = true; + } + } + } + + private void dataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e) + { + var manufacturer = new Manufacturer { Name = "" }; + _manufacturerRepository.AddManufacturer(manufacturer); + LoadManufacturers(); + } + + + // реализация через нажатие клавишь + + private void dataGridView_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Insert) + { + var manufacturer = new Manufacturer { Name = "" }; + _manufacturerRepository.AddManufacturer(manufacturer); + LoadManufacturers(); + } + else if (e.KeyCode == Keys.Delete) + { + if (dataGridView.SelectedRows.Count > 0) + { + var selectedManufacturer = dataGridView.SelectedRows[0].DataBoundItem as Manufacturer; + if (selectedManufacturer != null) + { + if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _manufacturerRepository.DeleteManufacturer(selectedManufacturer.Id); + LoadManufacturers(); + } + } + } + } + } + } +} diff --git a/PluginsConvention14/Forms/ManufacturerForm.resx b/PluginsConvention14/Forms/ManufacturerForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginsConvention14/Forms/ManufacturerForm.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/PluginsConvention14/Forms/ProductForm.Designer.cs b/PluginsConvention14/Forms/ProductForm.Designer.cs new file mode 100644 index 0000000..247f34f --- /dev/null +++ b/PluginsConvention14/Forms/ProductForm.Designer.cs @@ -0,0 +1,121 @@ +namespace PluginsConvention14 +{ + partial class ProductForm + { + /// + /// 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() + { + dtpDeliveryDate = new WinFormsLibrary1.DateInputControl(); + cmbManufacturer = new WinFormsLibrary1.ComboBoxUserControl(); + txtName = new Library14Petrushin.TextBoxRange(); + pbImage = new PictureBox(); + button1 = new Button(); + button2 = new Button(); + ((System.ComponentModel.ISupportInitialize)pbImage).BeginInit(); + SuspendLayout(); + // + // dtpDeliveryDate + // + dtpDeliveryDate.DateFormat = null; + dtpDeliveryDate.Location = new Point(13, 137); + dtpDeliveryDate.Margin = new Padding(4, 5, 4, 5); + dtpDeliveryDate.Name = "dtpDeliveryDate"; + dtpDeliveryDate.Size = new Size(186, 110); + dtpDeliveryDate.TabIndex = 0; + // + // cmbManufacturer + // + cmbManufacturer.Location = new Point(12, 218); + cmbManufacturer.Margin = new Padding(4, 5, 4, 5); + cmbManufacturer.Name = "cmbManufacturer"; + cmbManufacturer.SelectedValue = ""; + cmbManufacturer.Size = new Size(201, 40); + cmbManufacturer.TabIndex = 1; + // + // txtName + // + txtName.Location = new Point(12, 12); + txtName.MaxLength = null; + txtName.MinLength = null; + txtName.Name = "txtName"; + txtName.Size = new Size(315, 108); + txtName.TabIndex = 2; + // + // pbImage + // + pbImage.Location = new Point(320, 32); + pbImage.Name = "pbImage"; + pbImage.Size = new Size(451, 344); + pbImage.TabIndex = 3; + pbImage.TabStop = false; + // + // button1 + // + button1.Location = new Point(320, 399); + button1.Name = "button1"; + button1.Size = new Size(110, 29); + button1.TabIndex = 4; + button1.Text = "Choose img"; + button1.UseVisualStyleBackColor = true; + button1.Click += btnBrowse_Click; + // + // button2 + // + button2.Location = new Point(12, 326); + button2.Name = "button2"; + button2.Size = new Size(94, 29); + button2.TabIndex = 5; + button2.Text = "Save"; + button2.UseVisualStyleBackColor = true; + button2.Click += btnSave_Click; + // + // ProductForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(button2); + Controls.Add(button1); + Controls.Add(pbImage); + Controls.Add(txtName); + Controls.Add(cmbManufacturer); + Controls.Add(dtpDeliveryDate); + Name = "ProductForm"; + Text = "ProductForm"; + ((System.ComponentModel.ISupportInitialize)pbImage).EndInit(); + ResumeLayout(false); + } + + #endregion + + private WinFormsLibrary1.DateInputControl dtpDeliveryDate; + private WinFormsLibrary1.ComboBoxUserControl cmbManufacturer; + private Library14Petrushin.TextBoxRange txtName; + private PictureBox pbImage; + private Button button1; + private Button button2; + } +} \ No newline at end of file diff --git a/PluginsConvention14/Forms/ProductForm.cs b/PluginsConvention14/Forms/ProductForm.cs new file mode 100644 index 0000000..f73451f --- /dev/null +++ b/PluginsConvention14/Forms/ProductForm.cs @@ -0,0 +1,116 @@ +using Data; +using Data.Models; +using Data.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PluginsConvention14 +{ + public partial class ProductForm : Form + { + private readonly IProductRepository _productRepository; + private readonly IManufacturerRepository _manufacturerRepository; + private Product _product; + private bool _isNewProduct; + private const int MINL = 3; + private const int MAXL= 10; + + public ProductForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository, Product product = null) + { + InitializeComponent(); + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + + _productRepository = productRepository; + _manufacturerRepository = manufacturerRepository; + + + var manufacturers = _manufacturerRepository.GetAllManufacturers().Select(m => m.Name).ToList(); + // cmbManufacturer.Data = manufacturers; + foreach (var manufacturer in manufacturers) + { + cmbManufacturer.AddItem(manufacturer); + } + + _product = product; + _isNewProduct = product == null; + txtName.MinLength = MINL; + txtName.MaxLength = MAXL; + dtpDeliveryDate.DateFormat = "dd MMMM yyyy"; + + if (!_isNewProduct) + { + txtName.InputValue = _product.Name; + cmbManufacturer.SelectedValue = _product.ManufacturerName; + dtpDeliveryDate.Date = _product.DeliveryDate; + + if (_product.Image != null) + { + using (var ms = new MemoryStream(_product.Image)) + { + pbImage.Image = Image.FromStream(ms); + } + } + } + } + + private void btnBrowse_Click(object sender, EventArgs e) + { + using (var openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp"; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + pbImage.Image = Image.FromFile(openFileDialog.FileName); + } + } + } + + private void btnSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(txtName.InputValue)) + { + MessageBox.Show("Name is required."); + return; + } + + if (_isNewProduct) + { + _product = new Product(); + } + + _product.Name = txtName.InputValue; + _product.ManufacturerName = cmbManufacturer.SelectedValue.ToString(); + _product.DeliveryDate = dtpDeliveryDate.Date; + + if (pbImage.Image != null) + { + using (var ms = new MemoryStream()) + { + pbImage.Image.Save(ms, pbImage.Image.RawFormat); + _product.Image = ms.ToArray(); + } + } + + if (_isNewProduct) + { + _productRepository.AddProduct(_product); + } + else + { + _productRepository.UpdateProduct(_product); + } + + + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/PluginsConvention14/Forms/ProductForm.resx b/PluginsConvention14/Forms/ProductForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginsConvention14/Forms/ProductForm.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/PluginsConvention14/MyPlugin/MainPluginConvention.cs b/PluginsConvention14/MyPlugin/MainPluginConvention.cs new file mode 100644 index 0000000..9ca425c --- /dev/null +++ b/PluginsConvention14/MyPlugin/MainPluginConvention.cs @@ -0,0 +1,306 @@ +using PluginsConventionLibrary.Plugins; +using System.Composition; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Library15Gerimovich; +using Data.Repositories; +using Data.Models; +using Data; +using View.ViewModels; +using WinFormsLibrary1; +using Library15Gerimovich.OfficePackage.HelperModels; + +namespace PluginsConvention14.MyPlugin +{ + [Export(typeof(IPluginsConvention))] + public class MainPluginConvention : IPluginsConvention + { + + private OutputTableResults оutputTableResults; + private readonly IProductRepository _productRepository; + private readonly IManufacturerRepository _manufacturerRepository; + + public MainPluginConvention() + { + var dbContext = new ApplicationDbContext(); + _productRepository = new ProductRepository(dbContext); + _manufacturerRepository = new ManufacturerRepository(dbContext); + + оutputTableResults = new OutputTableResults(); + var menu = new ContextMenuStrip(); + var skillMenuItem = new ToolStripMenuItem("Формы"); + menu.Items.Add(skillMenuItem); + skillMenuItem.Click += (sender, e) => + { + var formSkill = new ManufacturerForm(_manufacturerRepository); + formSkill.ShowDialog(); + }; + оutputTableResults.ContextMenuStrip = menu; + ReloadData(); + } + + /// Название плагина + string IPluginsConvention.PluginName => PluginName(); + public string PluginName() + { + return "Products"; + } + + public UserControl GetControl => оutputTableResults; + + PluginsConventionElement IPluginsConvention.GetElement => GetElement(); + + public PluginsConventionElement GetElement() + { + var product = оutputTableResults.GetSelectedObject(); ; + MainPluginConventionElement element = null; + if (оutputTableResults != null) + { + element = new MainPluginConventionElement + { + Id = product.Id, + Name = product.Name, + ManufacturerName = product.ManufacturerName, + DeliveryDate = product.DeliveryDate, + }; + } + return (new PluginsConventionElement { Id = element.Id }); + } + + public Form GetForm(PluginsConventionElement element) + { + if (element != null) + { + var formOrder = new ProductForm(_productRepository, _manufacturerRepository, _productRepository.GetProductById(element.Id)); + return formOrder; + } + else + { + var formOrder = new ProductForm(_productRepository, _manufacturerRepository); + return formOrder; + } + } + + public bool DeleteElement(PluginsConventionElement element) + { + try + { + _productRepository.DeleteProduct(element.Id); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + return true; + } + + public void ReloadData() + { + var products = _productRepository.GetAllProducts(); + + оutputTableResults.ClearGrid(); + foreach (var product in products) + { + оutputTableResults.InsertValue(product); + } + } + public bool CreatePdf(PluginsConventionSaveDocument saveDocument) + { + try + { + // Получаем изображения из базы данных + var images = GetImagesFromDatabase(); + + if (images.Count > 0) + { + string fileName = ""; + using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }) + { + if (dialog.ShowDialog() == DialogResult.OK) + { + fileName = dialog.FileName.ToString(); + } + } + // Создаем компонент PdfImg + var pdfImg = new Library14Petrushin.PdfImg(); + + // Заголовок документа + string documentTitle = "Product Images"; + + // Создаем PDF-документ + pdfImg.CreatePdfDocument(fileName, documentTitle, images); + + // Уведомление об успешной загрузке + MessageBox.Show("PDF document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + + } + } + catch (Exception) + { + return false; + } + return true; + } + + private List GetImagesFromDatabase() + { + var images = new List(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (product.Image != null) + { + // Создаем временный файл для сохранения изображения + string tempFilePath = Path.GetTempFileName(); + File.WriteAllBytes(tempFilePath, product.Image); + + // Добавляем путь к временному файлу в список + images.Add(new Library14Petrushin.ImageData { ImagePath = tempFilePath }); + } + } + + return images; + } + + public bool CreateExcel(PluginsConventionSaveDocument saveDocument) + { + try + { + + + // Получаем все продукты из базы данных + var products = GetAllProducts(); + + if (products.Count > 0) + { + string fileName = ""; + using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }) + { + if (dialog.ShowDialog() == DialogResult.OK) + { + fileName = dialog.FileName.ToString(); + } + } + // Создаем объекты MergeCell и Column + var mergeCells = new List + { + new WinFormsLibrary1.Models.MergeCell("Product", new int[] {1, 2}) + }; + + var columns = new List + { + new WinFormsLibrary1.Models.Column("Id", "Id", 10), + new WinFormsLibrary1.Models.Column("Name", "Name", 20), + new WinFormsLibrary1.Models.Column("ManufacturerName", "ManufacturerName", 20), + new WinFormsLibrary1.Models.Column("DeliveryDate", "DeliveryDate", 20) + }; + + // Создаем компонент ComponentTable + var componentTable = new ComponentTable(); + + // Конвертируем продукты в представление для таблицы + var tableItems = ProductTableItem.ConvertProductsToTableItems(products); + + // Создаем документ Excel + componentTable.CreateDocument(fileName, "Product Report", mergeCells, columns, tableItems); + + // Уведомление об успешной загрузке + MessageBox.Show("Excel document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + }else + { + MessageBox.Show("No products found in the database."); + } + } + + catch (Exception) + { + return false; + } + return true; + } + + private List GetAllProducts() + { + return _productRepository.GetAllProducts().ToList(); + } + + public bool CreateWord(PluginsConventionSaveDocument saveDocument) + { + try + { + + string fileName = ""; + using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" }) + { + if (dialog.ShowDialog() == DialogResult.OK) + { + fileName = dialog.FileName.ToString(); + } + } + + // Получаем данные о количестве продукции каждого производителя + var productCounts = GetProductCountsByManufacturer(); + + if (productCounts.Count > 0) + { + // Создаем объект WordDiagramInfo + var diagramInfo = new WordDiagramInfo + { + FileName = fileName, + Title = "Product Count by Manufacturer", + ChartTitle = "Product Count", + LegendLocation = Library15Gerimovich.OfficePackage.HelperEnums.WordDiagramLegendLocation.Top, + Series = new WordDiagramSeries + { + SeriesName = "Product Count", + Data = productCounts + } + }; + + var wordDiagramComponent = new WordDiagramComponent(); + + // Создаем диаграмму в Word + wordDiagramComponent.CreateDiagram(diagramInfo); + + // Уведомление об успешной загрузке + MessageBox.Show("Word document with chart created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("No products found in the database."); + } + + } + catch (Exception) + { + return false; + } + return true; + } + + private Dictionary GetProductCountsByManufacturer() + { + var productCounts = new Dictionary(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (productCounts.ContainsKey(product.ManufacturerName)) + { + productCounts[product.ManufacturerName]++; + } + else + { + productCounts[product.ManufacturerName] = 1; + } + } + + return productCounts; + } + } +} diff --git a/PluginsConvention14/MyPlugin/MainPluginsConventionElement.cs b/PluginsConvention14/MyPlugin/MainPluginsConventionElement.cs new file mode 100644 index 0000000..e3ae721 --- /dev/null +++ b/PluginsConvention14/MyPlugin/MainPluginsConventionElement.cs @@ -0,0 +1,28 @@ +using Data.Models; +using PluginsConventionLibrary.Plugins; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using View.ViewModels; + +namespace PluginsConvention14.MyPlugin +{ + public class MainPluginConventionElement : PluginsConventionElement + { + public string Name { get; set; } + public string ManufacturerName { get; set; } + public string DeliveryDate { get; set; } + public static List ConvertProductsToTableItems(List products) + { + return products.Select(p => new ProductTableItem + { + Id = p.Id.ToString(), + Name = p.Name, + ManufacturerName = p.ManufacturerName, + DeliveryDate = p.DeliveryDate.ToShortDateString() + }).ToList(); + } + } +} diff --git a/PluginsConvention14/Plugins/IPluginsConvention.cs b/PluginsConvention14/Plugins/IPluginsConvention.cs new file mode 100644 index 0000000..664ebc4 --- /dev/null +++ b/PluginsConvention14/Plugins/IPluginsConvention.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +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 CreateWord(PluginsConventionSaveDocument saveDocument); + + /// + /// Создание простого документа + /// + /// + /// + bool CreateExcel(PluginsConventionSaveDocument saveDocument); + + /// + /// Создание документа с диаграммой + /// + /// + /// + bool CreatePdf(PluginsConventionSaveDocument saveDocument); + } +} diff --git a/PluginsConvention14/Plugins/PluginsConventionElement.cs b/PluginsConvention14/Plugins/PluginsConventionElement.cs new file mode 100644 index 0000000..1dea201 --- /dev/null +++ b/PluginsConvention14/Plugins/PluginsConventionElement.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PluginsConventionLibrary.Plugins +{ + public class PluginsConventionElement + { + public int Id { get; set; } + } +} diff --git a/PluginsConvention14/Plugins/PluginsConventionSaveDocument.cs b/PluginsConvention14/Plugins/PluginsConventionSaveDocument.cs new file mode 100644 index 0000000..614962e --- /dev/null +++ b/PluginsConvention14/Plugins/PluginsConventionSaveDocument.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PluginsConventionLibrary.Plugins +{ + public class PluginsConventionSaveDocument + { + public string FileName { get; set; } + } +} diff --git a/PluginsConvention14/PluginsConvention14.csproj b/PluginsConvention14/PluginsConvention14.csproj new file mode 100644 index 0000000..1cd0837 --- /dev/null +++ b/PluginsConvention14/PluginsConvention14.csproj @@ -0,0 +1,34 @@ + + + + net8.0-windows + enable + true + enable + + + + + + + + + + + + + + + + + Form + + + Form + + + Form + + + + diff --git a/PluginsConventionLibrary/Forms/MainForm.Designer.cs b/PluginsConventionLibrary/Forms/MainForm.Designer.cs new file mode 100644 index 0000000..30b9dc5 --- /dev/null +++ b/PluginsConventionLibrary/Forms/MainForm.Designer.cs @@ -0,0 +1,178 @@ +namespace Laba3 +{ + partial class MainForm + { + /// + /// 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(); + menuStrip1 = new MenuStrip(); + createToolStripMenuItem = new ToolStripMenuItem(); + updateToolStripMenuItem = new ToolStripMenuItem(); + deleteToolStripMenuItem = new ToolStripMenuItem(); + manufacturerToolStripMenuItem = new ToolStripMenuItem(); + documentsToolStripMenuItem = new ToolStripMenuItem(); + pdfImageToolStripMenuItem = new ToolStripMenuItem(); + exelTableToolStripMenuItem = new ToolStripMenuItem(); + wordGistToolStripMenuItem = new ToolStripMenuItem(); + outputTableResults = new Library15Gerimovich.OutputTableResults(); + pdfImg = new Library14Petrushin.PdfImg(components); + wordDiagramComponent = new Library15Gerimovich.WordDiagramComponent(components); + componentTable = new WinFormsLibrary1.ComponentTable(components); + saveFileDialogPdf = new SaveFileDialog(); + saveFileDialogWord = new SaveFileDialog(); + saveFileDialogExel = new SaveFileDialog(); + menuStrip1.SuspendLayout(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { createToolStripMenuItem, updateToolStripMenuItem, deleteToolStripMenuItem, manufacturerToolStripMenuItem, documentsToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(480, 28); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // createToolStripMenuItem + // + createToolStripMenuItem.Name = "createToolStripMenuItem"; + createToolStripMenuItem.Size = new Size(66, 24); + createToolStripMenuItem.Text = "Create"; + createToolStripMenuItem.Click += addToolStripMenuItem_Click; + // + // updateToolStripMenuItem + // + updateToolStripMenuItem.Name = "updateToolStripMenuItem"; + updateToolStripMenuItem.Size = new Size(72, 24); + updateToolStripMenuItem.Text = "Update"; + updateToolStripMenuItem.Click += editToolStripMenuItem_Click; + // + // deleteToolStripMenuItem + // + deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; + deleteToolStripMenuItem.Size = new Size(67, 24); + deleteToolStripMenuItem.Text = "Delete"; + deleteToolStripMenuItem.Click += deleteToolStripMenuItem_Click; + // + // manufacturerToolStripMenuItem + // + manufacturerToolStripMenuItem.Name = "manufacturerToolStripMenuItem"; + manufacturerToolStripMenuItem.Size = new Size(111, 24); + manufacturerToolStripMenuItem.Text = "Manufacturer"; + manufacturerToolStripMenuItem.Click += manufacturersToolStripMenuItem_Click; + // + // documentsToolStripMenuItem + // + documentsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pdfImageToolStripMenuItem, exelTableToolStripMenuItem, wordGistToolStripMenuItem }); + documentsToolStripMenuItem.Name = "documentsToolStripMenuItem"; + documentsToolStripMenuItem.Size = new Size(98, 24); + documentsToolStripMenuItem.Text = "Documents"; + // + // pdfImageToolStripMenuItem + // + pdfImageToolStripMenuItem.Name = "pdfImageToolStripMenuItem"; + pdfImageToolStripMenuItem.Size = new Size(159, 26); + pdfImageToolStripMenuItem.Text = "Pdf Image"; + pdfImageToolStripMenuItem.Click += createSimpleDocumentToolStripMenuItem_Click; + // + // exelTableToolStripMenuItem + // + exelTableToolStripMenuItem.Name = "exelTableToolStripMenuItem"; + exelTableToolStripMenuItem.Size = new Size(159, 26); + exelTableToolStripMenuItem.Text = "Exel table"; + exelTableToolStripMenuItem.Click += createCustomTableDocumentToolStripMenuItem_Click; + // + // wordGistToolStripMenuItem + // + wordGistToolStripMenuItem.Name = "wordGistToolStripMenuItem"; + wordGistToolStripMenuItem.Size = new Size(159, 26); + wordGistToolStripMenuItem.Text = "Word gist"; + wordGistToolStripMenuItem.Click += createChartDocumentToolStripMenuItem_Click; + // + // outputTableResults + // + outputTableResults.Location = new Point(12, 32); + outputTableResults.Margin = new Padding(3, 4, 3, 4); + outputTableResults.Name = "outputTableResults"; + outputTableResults.SelectedRow = -1; + outputTableResults.Size = new Size(467, 308); + outputTableResults.TabIndex = 1; + // + // saveFileDialogPdf + // + saveFileDialogPdf.FileName = "Products.pdf"; + saveFileDialogPdf.Filter = "PDF Files (*.pdf)|*.pdf"; + saveFileDialogPdf.Title = "Save PDF Document"; + // + // saveFileDialogWord + // + saveFileDialogWord.FileName = "Diagram.docx"; + saveFileDialogWord.Filter = "Word Files (*.docx)|*.docx"; + saveFileDialogWord.Title = "Save Word Document"; + // + // saveFileDialogExel + // + saveFileDialogExel.FileName = "ProductReport.xlsx"; + saveFileDialogExel.Filter = "Excel Files (*.xlsx)|*.xlsx"; + saveFileDialogExel.Title = "Save Excel Document"; + // + // MainForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(480, 351); + Controls.Add(outputTableResults); + Controls.Add(menuStrip1); + KeyPreview = true; + MainMenuStrip = menuStrip1; + Name = "MainForm"; + Text = "Form1"; + KeyDown += MainForm_KeyDown; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private MenuStrip menuStrip1; + private ToolStripMenuItem createToolStripMenuItem; + private ToolStripMenuItem updateToolStripMenuItem; + private Library15Gerimovich.OutputTableResults outputTableResults; + private ToolStripMenuItem deleteToolStripMenuItem; + private ToolStripMenuItem manufacturerToolStripMenuItem; + private ToolStripMenuItem documentsToolStripMenuItem; + private ToolStripMenuItem pdfImageToolStripMenuItem; + private ToolStripMenuItem exelTableToolStripMenuItem; + private ToolStripMenuItem wordGistToolStripMenuItem; + private Library14Petrushin.PdfImg pdfImg; + private Library15Gerimovich.WordDiagramComponent wordDiagramComponent; + private WinFormsLibrary1.ComponentTable componentTable; + } +} diff --git a/PluginsConventionLibrary/Forms/MainForm.cs b/PluginsConventionLibrary/Forms/MainForm.cs new file mode 100644 index 0000000..c0e33f2 --- /dev/null +++ b/PluginsConventionLibrary/Forms/MainForm.cs @@ -0,0 +1,284 @@ +using Data; +using Data.Repositories; +using View; +using System.Windows.Forms; +using Data.Models; +using Library14Petrushin; +using Library15Gerimovich.OfficePackage.HelperModels; +using Library15Gerimovich; +using WinFormsLibrary1; +using WinFormsLibrary1.Models; +using View.ViewModels; + +namespace Laba3 +{ + public partial class MainForm : Form + { + private readonly IProductRepository _productRepository; + private readonly IManufacturerRepository _manufacturerRepository; + private SaveFileDialog saveFileDialogPdf; + private SaveFileDialog saveFileDialogWord; + private SaveFileDialog saveFileDialogExel; + + public MainForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository) + { + InitializeComponent(); + _productRepository = productRepository; + _manufacturerRepository = manufacturerRepository; + InitializeOutputTableResults(); + LoadProducts(); + } + + private void InitializeOutputTableResults() + { + outputTableResults.ConfigureColumns(new List + { + new ColumnInfo("", 0, false, "Id"), + new ColumnInfo("Name", 150, true, "Name"), + new ColumnInfo("ManufacturerNameManufacturerName", 150, true, "ManufacturerName"), + new ColumnInfo("DeliveryDate", 50, true, "DeliveryDate"), + }); + + } + + private void LoadProducts() + { + var products = _productRepository.GetAllProducts(); + outputTableResults.ClearGrid(); + foreach (var product in products) + { + outputTableResults.InsertValue(product); + } + } + + private void addToolStripMenuItem_Click(object sender, EventArgs e) + { + var productForm = new ProductForm(_productRepository, _manufacturerRepository); + if (productForm.ShowDialog() == DialogResult.OK) + { + LoadProducts(); + } + } + + private void editToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + var selectedProductId = outputTableResults.GetSelectedObject().Id; + var selectedProduct = _productRepository.GetProductById(selectedProductId); + var productForm = new ProductForm(_productRepository, _manufacturerRepository, selectedProduct); + if (productForm.ShowDialog() == DialogResult.OK) + { + LoadProducts(); + } + } + catch (Exception ex) { + MessageBox.Show(ex.ToString()); + } + } + + private void deleteToolStripMenuItem_Click(object sender, EventArgs e) + { + var selectedProductId = outputTableResults.GetSelectedObject().Id; + if (MessageBox.Show("Are you sure you want to delete this product?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _productRepository.DeleteProduct(selectedProductId); + LoadProducts(); + } + } + + private void manufacturersToolStripMenuItem_Click(object sender, EventArgs e) + { + var manufacturerForm = new ManufacturerForm(_manufacturerRepository); + manufacturerForm.ShowDialog(); + } + + private void createSimpleDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем изображения из базы данных + var images = GetImagesFromDatabase(); + + if (images.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogPdf.ShowDialog() == DialogResult.OK) + { + // Создаем компонент PdfImg + var pdfImg = new Library14Petrushin.PdfImg(); + + // Путь для сохранения PDF-документа + string fileName = saveFileDialogPdf.FileName; + + // Заголовок документа + string documentTitle = "Product Images"; + + // Создаем PDF-документ + pdfImg.CreatePdfDocument(fileName, documentTitle, images); + + // Уведомление об успешной загрузке + MessageBox.Show("PDF document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No images found in the database."); + } + } + + private void createCustomTableDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем все продукты из базы данных + var products = GetAllProducts(); + + if (products.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogExel.ShowDialog() == DialogResult.OK) + { + // Создаем объекты MergeCell и Column + var mergeCells = new List + { + new MergeCell("Product", new int[] {1, 2}) + }; + + var columns = new List + { + new Column("Id", "Id", 10), + new Column("Name", "Name", 20), + new Column("ManufacturerName", "ManufacturerName", 20), + new Column("DeliveryDate", "DeliveryDate", 20) + }; + + // Создаем компонент ComponentTable + var componentTable = new ComponentTable(); + + // Конвертируем продукты в представление для таблицы + var tableItems = ProductTableItem.ConvertProductsToTableItems(products); + + // Создаем документ Excel + componentTable.CreateDocument(saveFileDialogExel.FileName, "Product Report", mergeCells, columns, tableItems); + + // Уведомление об успешной загрузке + MessageBox.Show("Excel document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No products found in the database."); + } + } + + private void createChartDocumentToolStripMenuItem_Click(object sender, EventArgs e) + { + // Получаем данные о количестве продукции каждого производителя + var productCounts = GetProductCountsByManufacturer(); + + if (productCounts.Count > 0) + { + // Показываем диалоговое окно для выбора пути сохранения + if (saveFileDialogWord.ShowDialog() == DialogResult.OK) + { + // Создаем объект WordDiagramInfo + var diagramInfo = new WordDiagramInfo + { + FileName = saveFileDialogWord.FileName, + Title = "Product Count by Manufacturer", + ChartTitle = "Product Count", + LegendLocation = Library15Gerimovich.OfficePackage.HelperEnums.WordDiagramLegendLocation.Top, + Series = new WordDiagramSeries + { + SeriesName = "Product Count", + Data = productCounts + } + }; + + // Создаем диаграмму в Word + wordDiagramComponent.CreateDiagram(diagramInfo); + + // Уведомление об успешной загрузке + MessageBox.Show("Word document with chart created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + else + { + MessageBox.Show("No products found in the database."); + } + } + + // бизнес логика + + private void MainForm_KeyDown(object sender, KeyEventArgs e) + { + if (e.Control) + { + switch (e.KeyCode) + { + case Keys.A: + addToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.U: + editToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.D: + deleteToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.S: + createSimpleDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.T: + createCustomTableDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + case Keys.C: + createChartDocumentToolStripMenuItem_Click(null, EventArgs.Empty); + break; + } + } + } + + private List GetImagesFromDatabase() + { + var images = new List(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (product.Image != null) + { + // Создаем временный файл для сохранения изображения + string tempFilePath = Path.GetTempFileName(); + File.WriteAllBytes(tempFilePath, product.Image); + + // Добавляем путь к временному файлу в список + images.Add(new ImageData { ImagePath = tempFilePath }); + } + } + + return images; + } + + private Dictionary GetProductCountsByManufacturer() + { + var productCounts = new Dictionary(); + var products = _productRepository.GetAllProducts(); + + foreach (var product in products) + { + if (productCounts.ContainsKey(product.ManufacturerName)) + { + productCounts[product.ManufacturerName]++; + } + else + { + productCounts[product.ManufacturerName] = 1; + } + } + + return productCounts; + } + + private List GetAllProducts() + { + return _productRepository.GetAllProducts().ToList(); + } + } +} diff --git a/PluginsConventionLibrary/Forms/MainForm.resx b/PluginsConventionLibrary/Forms/MainForm.resx new file mode 100644 index 0000000..6ce8bc4 --- /dev/null +++ b/PluginsConventionLibrary/Forms/MainForm.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 572, 17 + + + 708, 17 + + + 813, 17 + + + 1039, 17 + + + 17, 17 + + + 195, 17 + + + 388, 17 + + \ No newline at end of file diff --git a/PluginsConventionLibrary/Forms/ManufacturerForm.Designer.cs b/PluginsConventionLibrary/Forms/ManufacturerForm.Designer.cs new file mode 100644 index 0000000..89fec90 --- /dev/null +++ b/PluginsConventionLibrary/Forms/ManufacturerForm.Designer.cs @@ -0,0 +1,64 @@ +namespace View +{ + partial class ManufacturerForm + { + /// + /// 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.Size = new Size(711, 426); + dataGridView.TabIndex = 0; + dataGridView.CellValueChanged += dataGridView_CellValueChanged; + dataGridView.UserAddedRow += dataGridView_UserAddedRow; + dataGridView.UserDeletingRow += dataGridView_UserDeletingRow; + dataGridView.KeyDown += dataGridView_KeyDown; + // + // ManufacturerForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(731, 450); + Controls.Add(dataGridView); + Name = "ManufacturerForm"; + Text = "ManufacturerForm"; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/PluginsConventionLibrary/Forms/ManufacturerForm.cs b/PluginsConventionLibrary/Forms/ManufacturerForm.cs new file mode 100644 index 0000000..23638fb --- /dev/null +++ b/PluginsConventionLibrary/Forms/ManufacturerForm.cs @@ -0,0 +1,95 @@ +using Data.Models; +using Data.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace View +{ + public partial class ManufacturerForm : Form + { + private readonly IManufacturerRepository _manufacturerRepository; + + public ManufacturerForm(IManufacturerRepository manufacturerRepository) + { + InitializeComponent(); + _manufacturerRepository = manufacturerRepository; + LoadManufacturers(); + } + + private void LoadManufacturers() + { + var manufacturers = _manufacturerRepository.GetAllManufacturers().ToList(); + dataGridView.DataSource = manufacturers; + } + + private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + var manufacturer = dataGridView.Rows[e.RowIndex].DataBoundItem as Manufacturer; + if (manufacturer != null) + { + _manufacturerRepository.UpdateManufacturer(manufacturer); + } + } + } + + private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) + { + var manufacturer = e.Row.DataBoundItem as Manufacturer; + if (manufacturer != null) + { + if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _manufacturerRepository.DeleteManufacturer(manufacturer.Id); + } + else + { + e.Cancel = true; + } + } + } + + private void dataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e) + { + var manufacturer = new Manufacturer { Name = "" }; + _manufacturerRepository.AddManufacturer(manufacturer); + LoadManufacturers(); + } + + + // реализация через нажатие клавишь + + private void dataGridView_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Insert) + { + var manufacturer = new Manufacturer { Name = "" }; + _manufacturerRepository.AddManufacturer(manufacturer); + LoadManufacturers(); + } + else if (e.KeyCode == Keys.Delete) + { + if (dataGridView.SelectedRows.Count > 0) + { + var selectedManufacturer = dataGridView.SelectedRows[0].DataBoundItem as Manufacturer; + if (selectedManufacturer != null) + { + if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _manufacturerRepository.DeleteManufacturer(selectedManufacturer.Id); + LoadManufacturers(); + } + } + } + } + } + } +} diff --git a/PluginsConventionLibrary/Forms/ManufacturerForm.resx b/PluginsConventionLibrary/Forms/ManufacturerForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginsConventionLibrary/Forms/ManufacturerForm.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/PluginsConventionLibrary/Forms/ProductForm.Designer.cs b/PluginsConventionLibrary/Forms/ProductForm.Designer.cs new file mode 100644 index 0000000..c64b5a8 --- /dev/null +++ b/PluginsConventionLibrary/Forms/ProductForm.Designer.cs @@ -0,0 +1,121 @@ +namespace Laba3 +{ + partial class ProductForm + { + /// + /// 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() + { + dtpDeliveryDate = new WinFormsLibrary1.DateInputControl(); + cmbManufacturer = new WinFormsLibrary1.ComboBoxUserControl(); + txtName = new Library14Petrushin.TextBoxRange(); + pbImage = new PictureBox(); + button1 = new Button(); + button2 = new Button(); + ((System.ComponentModel.ISupportInitialize)pbImage).BeginInit(); + SuspendLayout(); + // + // dtpDeliveryDate + // + dtpDeliveryDate.DateFormat = null; + dtpDeliveryDate.Location = new Point(13, 137); + dtpDeliveryDate.Margin = new Padding(4, 5, 4, 5); + dtpDeliveryDate.Name = "dtpDeliveryDate"; + dtpDeliveryDate.Size = new Size(186, 110); + dtpDeliveryDate.TabIndex = 0; + // + // cmbManufacturer + // + cmbManufacturer.Location = new Point(12, 218); + cmbManufacturer.Margin = new Padding(4, 5, 4, 5); + cmbManufacturer.Name = "cmbManufacturer"; + cmbManufacturer.SelectedValue = ""; + cmbManufacturer.Size = new Size(201, 40); + cmbManufacturer.TabIndex = 1; + // + // txtName + // + txtName.Location = new Point(12, 12); + txtName.MaxLength = null; + txtName.MinLength = null; + txtName.Name = "txtName"; + txtName.Size = new Size(315, 108); + txtName.TabIndex = 2; + // + // pbImage + // + pbImage.Location = new Point(320, 32); + pbImage.Name = "pbImage"; + pbImage.Size = new Size(451, 344); + pbImage.TabIndex = 3; + pbImage.TabStop = false; + // + // button1 + // + button1.Location = new Point(320, 399); + button1.Name = "button1"; + button1.Size = new Size(110, 29); + button1.TabIndex = 4; + button1.Text = "Choose img"; + button1.UseVisualStyleBackColor = true; + button1.Click += btnBrowse_Click; + // + // button2 + // + button2.Location = new Point(12, 326); + button2.Name = "button2"; + button2.Size = new Size(94, 29); + button2.TabIndex = 5; + button2.Text = "Save"; + button2.UseVisualStyleBackColor = true; + button2.Click += btnSave_Click; + // + // ProductForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(button2); + Controls.Add(button1); + Controls.Add(pbImage); + Controls.Add(txtName); + Controls.Add(cmbManufacturer); + Controls.Add(dtpDeliveryDate); + Name = "ProductForm"; + Text = "ProductForm"; + ((System.ComponentModel.ISupportInitialize)pbImage).EndInit(); + ResumeLayout(false); + } + + #endregion + + private WinFormsLibrary1.DateInputControl dtpDeliveryDate; + private WinFormsLibrary1.ComboBoxUserControl cmbManufacturer; + private Library14Petrushin.TextBoxRange txtName; + private PictureBox pbImage; + private Button button1; + private Button button2; + } +} \ No newline at end of file diff --git a/PluginsConventionLibrary/Forms/ProductForm.cs b/PluginsConventionLibrary/Forms/ProductForm.cs new file mode 100644 index 0000000..3e88d28 --- /dev/null +++ b/PluginsConventionLibrary/Forms/ProductForm.cs @@ -0,0 +1,116 @@ +using Data; +using Data.Models; +using Data.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Laba3 +{ + public partial class ProductForm : Form + { + private readonly IProductRepository _productRepository; + private readonly IManufacturerRepository _manufacturerRepository; + private Product _product; + private bool _isNewProduct; + private const int MINL = 3; + private const int MAXL= 10; + + public ProductForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository, Product product = null) + { + InitializeComponent(); + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + + _productRepository = productRepository; + _manufacturerRepository = manufacturerRepository; + + + var manufacturers = _manufacturerRepository.GetAllManufacturers().Select(m => m.Name).ToList(); + // cmbManufacturer.Data = manufacturers; + foreach (var manufacturer in manufacturers) + { + cmbManufacturer.AddItem(manufacturer); + } + + _product = product; + _isNewProduct = product == null; + txtName.MinLength = MINL; + txtName.MaxLength = MAXL; + dtpDeliveryDate.DateFormat = "dd MMMM yyyy"; + + if (!_isNewProduct) + { + txtName.InputValue = _product.Name; + cmbManufacturer.SelectedValue = _product.ManufacturerName; + dtpDeliveryDate.Date = _product.DeliveryDate; + + if (_product.Image != null) + { + using (var ms = new MemoryStream(_product.Image)) + { + pbImage.Image = Image.FromStream(ms); + } + } + } + } + + private void btnBrowse_Click(object sender, EventArgs e) + { + using (var openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp"; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + pbImage.Image = Image.FromFile(openFileDialog.FileName); + } + } + } + + private void btnSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(txtName.InputValue)) + { + MessageBox.Show("Name is required."); + return; + } + + if (_isNewProduct) + { + _product = new Product(); + } + + _product.Name = txtName.InputValue; + _product.ManufacturerName = cmbManufacturer.SelectedValue.ToString(); + _product.DeliveryDate = dtpDeliveryDate.Date; + + if (pbImage.Image != null) + { + using (var ms = new MemoryStream()) + { + pbImage.Image.Save(ms, pbImage.Image.RawFormat); + _product.Image = ms.ToArray(); + } + } + + if (_isNewProduct) + { + _productRepository.AddProduct(_product); + } + else + { + _productRepository.UpdateProduct(_product); + } + + + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/PluginsConventionLibrary/Forms/ProductForm.resx b/PluginsConventionLibrary/Forms/ProductForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PluginsConventionLibrary/Forms/ProductForm.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/PluginsConventionLibrary/PluginsConventionLibrary.csproj b/PluginsConventionLibrary/PluginsConventionLibrary.csproj index 9fccf9f..5fe0d97 100644 --- a/PluginsConventionLibrary/PluginsConventionLibrary.csproj +++ b/PluginsConventionLibrary/PluginsConventionLibrary.csproj @@ -7,8 +7,24 @@ - + + + + + + + + Form + + + Form + + + Form + + +