From f8fc0b4584fe98a8efe3d71665bed8920d0128da Mon Sep 17 00:00:00 2001 From: dyakonovr Date: Mon, 28 Oct 2024 20:58:57 +0400 Subject: [PATCH] done --- BusinessLogic/BusinessLogic.csproj | 13 + BusinessLogic/ManufacturerLogic.cs | 65 ++++ BusinessLogic/ProductLogic.cs | 76 ++++ .../BindingModels/ManufacturerBindingModel.cs | 14 + .../BindingModels/ProductBindingModel.cs | 18 + .../IManufacturerLogic.cs | 17 + .../BusinessLogicContracts/IProductLogic.cs | 18 + Contracts/Contracts.csproj | 9 + Contracts/ReportModels/ProductReportModel.cs | 17 + .../StorageContracts/IManufacturerStorage.cs | 20 ++ Contracts/StorageContracts/IProductStorage.cs | 23 ++ Contracts/ViewModels/ManufacturerViewModel.cs | 14 + Contracts/ViewModels/ProductViewModel.cs | 24 ++ DatabaseImplement/DatabaseImplement.csproj | 22 ++ .../Implements/ManufacturerStorage.cs | 121 +++++++ .../Implements/ProductStorage.cs | 144 ++++++++ .../20241012142150_Init.Designer.cs | 74 ++++ .../Migrations/20241012142150_Init.cs | 51 +++ .../ProductsDatabaseModelSnapshot.cs | 72 ++++ DatabaseImplement/Models/Manufacturer.cs | 17 + DatabaseImplement/Models/Product.cs | 22 ++ DatabaseImplement/ProductsDatabase.cs | 25 ++ README.md | 2 - ShopProducts.sln | 43 +++ ShopProducts/FormManufacturers.Designer.cs | 63 ++++ ShopProducts/FormManufacturers.cs | 117 ++++++ .../FormManufacturers.resx | 0 ShopProducts/FormProduct.Designer.cs | 189 ++++++++++ ShopProducts/FormProduct.cs | 160 +++++++++ .../FormProduct.resx | 0 ShopProducts/FormProducts.Designer.cs | 147 ++++++++ ShopProducts/FormProducts.cs | 250 +++++++++++++ .../FormProducts.resx | 11 +- ShopProducts/Program.cs | 44 +++ ShopProducts/ShopProducts.csproj | 27 ++ WinFormsApp1/Form1.Designer.cs | 334 ------------------ WinFormsApp1/Form1.cs | 233 ------------ WinFormsApp1/Program.cs | 17 - WinFormsApp1/WinFormsApp1.csproj | 15 - WinFormsLibrary1.sln | 31 -- WinFormsLibrary1/Configs/Diagram/Location.cs | 16 - .../Configs/Diagram/PdfWithDiagramConfig.cs | 28 -- .../Configs/Image/PdfWithImageConfig.cs | 23 -- .../Configs/Table/PdfWithTableConfig.cs | 88 ----- .../CustomCheckedListBox.Designer.cs | 59 ---- WinFormsLibrary1/CustomCheckedListBox.cs | 80 ----- WinFormsLibrary1/CustomDataTree.Designer.cs | 55 --- WinFormsLibrary1/CustomDataTree.cs | 114 ------ WinFormsLibrary1/CustomTextBox.Designer.cs | 58 --- WinFormsLibrary1/CustomTextBox.cs | 66 ---- WinFormsLibrary1/CustomTextBox.resx | 120 ------- WinFormsLibrary1/DataTreeNodeConfig.cs | 18 - .../Errors/RangeNotSetException.cs | 13 - .../Errors/TextLengthOutOfRangeException.cs | 20 -- WinFormsLibrary1/Models/Employee.cs | 22 -- WinFormsLibrary1/Models/Human.cs | 22 -- WinFormsLibrary1/PdfWithDiagram.Designer.cs | 36 -- WinFormsLibrary1/PdfWithDiagram.cs | 117 ------ WinFormsLibrary1/PdfWithImages.Designer.cs | 36 -- WinFormsLibrary1/PdfWithImages.cs | 177 ---------- WinFormsLibrary1/PdfWithTable.Designer.cs | 36 -- WinFormsLibrary1/PdfWithTable.cs | 110 ------ WinFormsLibrary1/WinFormsLibrary1.csproj | 15 - 63 files changed, 1926 insertions(+), 1962 deletions(-) create mode 100644 BusinessLogic/BusinessLogic.csproj create mode 100644 BusinessLogic/ManufacturerLogic.cs create mode 100644 BusinessLogic/ProductLogic.cs create mode 100644 Contracts/BindingModels/ManufacturerBindingModel.cs create mode 100644 Contracts/BindingModels/ProductBindingModel.cs create mode 100644 Contracts/BusinessLogicContracts/IManufacturerLogic.cs create mode 100644 Contracts/BusinessLogicContracts/IProductLogic.cs create mode 100644 Contracts/Contracts.csproj create mode 100644 Contracts/ReportModels/ProductReportModel.cs create mode 100644 Contracts/StorageContracts/IManufacturerStorage.cs create mode 100644 Contracts/StorageContracts/IProductStorage.cs create mode 100644 Contracts/ViewModels/ManufacturerViewModel.cs create mode 100644 Contracts/ViewModels/ProductViewModel.cs create mode 100644 DatabaseImplement/DatabaseImplement.csproj create mode 100644 DatabaseImplement/Implements/ManufacturerStorage.cs create mode 100644 DatabaseImplement/Implements/ProductStorage.cs create mode 100644 DatabaseImplement/Migrations/20241012142150_Init.Designer.cs create mode 100644 DatabaseImplement/Migrations/20241012142150_Init.cs create mode 100644 DatabaseImplement/Migrations/ProductsDatabaseModelSnapshot.cs create mode 100644 DatabaseImplement/Models/Manufacturer.cs create mode 100644 DatabaseImplement/Models/Product.cs create mode 100644 DatabaseImplement/ProductsDatabase.cs delete mode 100644 README.md create mode 100644 ShopProducts.sln create mode 100644 ShopProducts/FormManufacturers.Designer.cs create mode 100644 ShopProducts/FormManufacturers.cs rename WinFormsLibrary1/CustomCheckedListBox.resx => ShopProducts/FormManufacturers.resx (100%) create mode 100644 ShopProducts/FormProduct.Designer.cs create mode 100644 ShopProducts/FormProduct.cs rename WinFormsLibrary1/CustomDataTree.resx => ShopProducts/FormProduct.resx (100%) create mode 100644 ShopProducts/FormProducts.Designer.cs create mode 100644 ShopProducts/FormProducts.cs rename WinFormsApp1/Form1.resx => ShopProducts/FormProducts.resx (89%) create mode 100644 ShopProducts/Program.cs create mode 100644 ShopProducts/ShopProducts.csproj delete mode 100644 WinFormsApp1/Form1.Designer.cs delete mode 100644 WinFormsApp1/Form1.cs delete mode 100644 WinFormsApp1/Program.cs delete mode 100644 WinFormsApp1/WinFormsApp1.csproj delete mode 100644 WinFormsLibrary1.sln delete mode 100644 WinFormsLibrary1/Configs/Diagram/Location.cs delete mode 100644 WinFormsLibrary1/Configs/Diagram/PdfWithDiagramConfig.cs delete mode 100644 WinFormsLibrary1/Configs/Image/PdfWithImageConfig.cs delete mode 100644 WinFormsLibrary1/Configs/Table/PdfWithTableConfig.cs delete mode 100644 WinFormsLibrary1/CustomCheckedListBox.Designer.cs delete mode 100644 WinFormsLibrary1/CustomCheckedListBox.cs delete mode 100644 WinFormsLibrary1/CustomDataTree.Designer.cs delete mode 100644 WinFormsLibrary1/CustomDataTree.cs delete mode 100644 WinFormsLibrary1/CustomTextBox.Designer.cs delete mode 100644 WinFormsLibrary1/CustomTextBox.cs delete mode 100644 WinFormsLibrary1/CustomTextBox.resx delete mode 100644 WinFormsLibrary1/DataTreeNodeConfig.cs delete mode 100644 WinFormsLibrary1/Errors/RangeNotSetException.cs delete mode 100644 WinFormsLibrary1/Errors/TextLengthOutOfRangeException.cs delete mode 100644 WinFormsLibrary1/Models/Employee.cs delete mode 100644 WinFormsLibrary1/Models/Human.cs delete mode 100644 WinFormsLibrary1/PdfWithDiagram.Designer.cs delete mode 100644 WinFormsLibrary1/PdfWithDiagram.cs delete mode 100644 WinFormsLibrary1/PdfWithImages.Designer.cs delete mode 100644 WinFormsLibrary1/PdfWithImages.cs delete mode 100644 WinFormsLibrary1/PdfWithTable.Designer.cs delete mode 100644 WinFormsLibrary1/PdfWithTable.cs delete mode 100644 WinFormsLibrary1/WinFormsLibrary1.csproj diff --git a/BusinessLogic/BusinessLogic.csproj b/BusinessLogic/BusinessLogic.csproj new file mode 100644 index 0000000..1072df0 --- /dev/null +++ b/BusinessLogic/BusinessLogic.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/BusinessLogic/ManufacturerLogic.cs b/BusinessLogic/ManufacturerLogic.cs new file mode 100644 index 0000000..df4e663 --- /dev/null +++ b/BusinessLogic/ManufacturerLogic.cs @@ -0,0 +1,65 @@ +using Contracts.BindingModels; +using Contracts.BusinessLogicContracts; +using Contracts.StorageContracts; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class ManufacturerLogic : IManufacturerLogic + { + private readonly IManufacturerStorage _ManufacturerStorage; + public ManufacturerLogic(IManufacturerStorage ManufacturerStorage) + { + _ManufacturerStorage = ManufacturerStorage; + } + + public void CreateOrUpdate(ManufacturerBindingModel model) + { + var element = _ManufacturerStorage.GetElement( + new ManufacturerBindingModel + { + Name = model.Name + }); + if (element != null && element.Id != model.Id) + { + throw new Exception("Такой статус уже существует"); + } + if (model.Id.HasValue) + { + _ManufacturerStorage.Update(model); + } + else + { + _ManufacturerStorage.Insert(model); + } + } + + public void Delete(ManufacturerBindingModel model) + { + var element = _ManufacturerStorage.GetElement(new ManufacturerBindingModel { Id = model.Id }); + if (element == null) + { + throw new Exception("Статус не найден"); + } + _ManufacturerStorage.Delete(model); + } + + public List Read(ManufacturerBindingModel model) + { + if (model == null) + { + return _ManufacturerStorage.GetFullList(); + } + if (model.Id.HasValue) + { + return new List { _ManufacturerStorage.GetElement(model) }; + } + return _ManufacturerStorage.GetFilteredList(model); + } + } +} diff --git a/BusinessLogic/ProductLogic.cs b/BusinessLogic/ProductLogic.cs new file mode 100644 index 0000000..866959f --- /dev/null +++ b/BusinessLogic/ProductLogic.cs @@ -0,0 +1,76 @@ +using Contracts.BindingModels; +using Contracts.BusinessLogicContracts; +using Contracts.StorageContracts; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class ProductLogic : IProductLogic + { + private readonly IProductStorage _ProductStorage; + public ProductLogic(IProductStorage ProductStorage) + { + _ProductStorage = ProductStorage; + } + public void CreateOrUpdate(ProductBindingModel model) + { + var element = _ProductStorage.GetElement( + new ProductBindingModel + { + DeliveryDate = model.DeliveryDate, + Name = model.Name, + Manufacturers = model.Manufacturers, + Image = model.Image + }); + if (element != null && element.Id != model.Id) + { + throw new Exception("Клиент с таким именем уже существует"); + } + if (model.Id.HasValue) + { + _ProductStorage.Update(model); + } + else + { + _ProductStorage.Insert(model); + } + } + + public void Delete(ProductBindingModel model) + { + var element = _ProductStorage.GetElement(new ProductBindingModel { Id = model.Id }); + if (element == null) + { + throw new Exception("Клиент не найден"); + } + _ProductStorage.Delete(model); + } + + public List Read(ProductBindingModel model) + { + if (model == null) + { + return _ProductStorage.GetFullList(); + } + if (model.Id.HasValue) + { + return new List { _ProductStorage.GetElement(model) }; + } + return _ProductStorage.GetFilteredList(model); + } + + public List<(int, double)> GetWordInfo() + { + var data = _ProductStorage.GetProductCountByManufacturer(); + + return data + .Select((g, index) => (Index: index + 1, Value: (double)g.Count)) + .ToList(); + } + } +} diff --git a/Contracts/BindingModels/ManufacturerBindingModel.cs b/Contracts/BindingModels/ManufacturerBindingModel.cs new file mode 100644 index 0000000..5c7d525 --- /dev/null +++ b/Contracts/BindingModels/ManufacturerBindingModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.BindingModels +{ + public class ManufacturerBindingModel + { + public int? Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Contracts/BindingModels/ProductBindingModel.cs b/Contracts/BindingModels/ProductBindingModel.cs new file mode 100644 index 0000000..b8fe47b --- /dev/null +++ b/Contracts/BindingModels/ProductBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.BindingModels +{ + public class ProductBindingModel + { + public int? Id { get; set; } + public string Name { get; set; } + public byte[] Image { get; set; } + public string Manufacturers { get; set; } + public DateTime DeliveryDate { get; set; } + } +} diff --git a/Contracts/BusinessLogicContracts/IManufacturerLogic.cs b/Contracts/BusinessLogicContracts/IManufacturerLogic.cs new file mode 100644 index 0000000..d57b288 --- /dev/null +++ b/Contracts/BusinessLogicContracts/IManufacturerLogic.cs @@ -0,0 +1,17 @@ +using Contracts.BindingModels; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.BusinessLogicContracts +{ + public interface IManufacturerLogic + { + List Read(ManufacturerBindingModel model); + void CreateOrUpdate(ManufacturerBindingModel model); + void Delete(ManufacturerBindingModel model); + } +} diff --git a/Contracts/BusinessLogicContracts/IProductLogic.cs b/Contracts/BusinessLogicContracts/IProductLogic.cs new file mode 100644 index 0000000..014be6c --- /dev/null +++ b/Contracts/BusinessLogicContracts/IProductLogic.cs @@ -0,0 +1,18 @@ +using Contracts.BindingModels; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.BusinessLogicContracts +{ + public interface IProductLogic + { + List Read(ProductBindingModel model); + List<(int, double)> GetWordInfo(); + void CreateOrUpdate(ProductBindingModel model); + void Delete(ProductBindingModel model); + } +} diff --git a/Contracts/Contracts.csproj b/Contracts/Contracts.csproj new file mode 100644 index 0000000..27ac386 --- /dev/null +++ b/Contracts/Contracts.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/Contracts/ReportModels/ProductReportModel.cs b/Contracts/ReportModels/ProductReportModel.cs new file mode 100644 index 0000000..8105863 --- /dev/null +++ b/Contracts/ReportModels/ProductReportModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.ReportModels +{ + public class ProductReportModel + { + public int? Id { get; set; } + public string Name { get; set; } + public string Image { get; set; } + public string Manufacturers { get; set; } + public string DeliveryDate { get; set; } + } +} diff --git a/Contracts/StorageContracts/IManufacturerStorage.cs b/Contracts/StorageContracts/IManufacturerStorage.cs new file mode 100644 index 0000000..06ec984 --- /dev/null +++ b/Contracts/StorageContracts/IManufacturerStorage.cs @@ -0,0 +1,20 @@ +using Contracts.BindingModels; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.StorageContracts +{ + public interface IManufacturerStorage + { + List GetFullList(); + List GetFilteredList(ManufacturerBindingModel model); + ManufacturerViewModel GetElement(ManufacturerBindingModel model); + void Insert(ManufacturerBindingModel model); + void Update(ManufacturerBindingModel model); + void Delete(ManufacturerBindingModel model); + } +} diff --git a/Contracts/StorageContracts/IProductStorage.cs b/Contracts/StorageContracts/IProductStorage.cs new file mode 100644 index 0000000..9de86b0 --- /dev/null +++ b/Contracts/StorageContracts/IProductStorage.cs @@ -0,0 +1,23 @@ +using Contracts.BindingModels; +using Contracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.StorageContracts +{ + public interface IProductStorage + { + List GetFullList(); + List GetFilteredList(ProductBindingModel model); + ProductViewModel GetElement(ProductBindingModel model); + + List<(string Manufacturer, int Count)> GetProductCountByManufacturer(); + + void Insert(ProductBindingModel model); + void Update(ProductBindingModel model); + void Delete(ProductBindingModel model); + } +} diff --git a/Contracts/ViewModels/ManufacturerViewModel.cs b/Contracts/ViewModels/ManufacturerViewModel.cs new file mode 100644 index 0000000..0e2ae26 --- /dev/null +++ b/Contracts/ViewModels/ManufacturerViewModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.ViewModels +{ + public class ManufacturerViewModel + { + public int? Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Contracts/ViewModels/ProductViewModel.cs b/Contracts/ViewModels/ProductViewModel.cs new file mode 100644 index 0000000..45dc6af --- /dev/null +++ b/Contracts/ViewModels/ProductViewModel.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contracts.ViewModels +{ + public class ProductViewModel + { + public int? Id { get; set; } + + [DisplayName("Название")] + public string Name { get; set; } + + [DisplayName("Изображение")] + public byte[] Image { get; set; } + [DisplayName("Производитель")] + public string Manufacturers { get; set; } + [DisplayName("Дата поставки")] + public DateTime DeliveryDate { get; set; } + } +} diff --git a/DatabaseImplement/DatabaseImplement.csproj b/DatabaseImplement/DatabaseImplement.csproj new file mode 100644 index 0000000..35b9c11 --- /dev/null +++ b/DatabaseImplement/DatabaseImplement.csproj @@ -0,0 +1,22 @@ + + + + net6.0 + enable + enable + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/DatabaseImplement/Implements/ManufacturerStorage.cs b/DatabaseImplement/Implements/ManufacturerStorage.cs new file mode 100644 index 0000000..faedfcb --- /dev/null +++ b/DatabaseImplement/Implements/ManufacturerStorage.cs @@ -0,0 +1,121 @@ +using Contracts.BindingModels; +using Contracts.StorageContracts; +using Contracts.ViewModels; +using DatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.NetworkInformation; +using System.Text; +using System.Threading.Tasks; + +namespace DatabaseImplement.Implements +{ + public class ManufacturerStorage : IManufacturerStorage + { + public void Delete(ManufacturerBindingModel model) + { + var context = new ProductsDatabase(); + var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id); + if (Manufacturer != null) + { + context.Manufacturers.Remove(Manufacturer); + context.SaveChanges(); + } + else + { + throw new Exception("Производитель не найден"); + } + } + + public ManufacturerViewModel GetElement(ManufacturerBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new ProductsDatabase(); + + var manufacturer = context.Manufacturers + .ToList() + .FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name); + return manufacturer != null ? CreateModel(manufacturer) : null; + } + + + public List GetFilteredList(ManufacturerBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new ProductsDatabase(); + return context.Manufacturers + .Where(rec => rec.Name.Contains(model.Name)) + .Select(CreateModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new ProductsDatabase(); + return context.Manufacturers + .Select(CreateModel) + .ToList(); + } + + public void Insert(ManufacturerBindingModel model) + { + var context = new ProductsDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + context.Manufacturers.Add(CreateModel(model, new Manufacturer())); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + public void Update(ManufacturerBindingModel model) + { + var context = new ProductsDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id); + if (Manufacturer == null) + { + throw new Exception("Производитель не найден"); + } + CreateModel(model, Manufacturer); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + private static Manufacturer CreateModel(ManufacturerBindingModel model, Manufacturer Manufacturer) + { + Manufacturer.Name = model.Name; + return Manufacturer; + } + + private static ManufacturerViewModel CreateModel(Manufacturer Manufacturer) + { + return new ManufacturerViewModel + { + Id = Manufacturer.Id, + Name = Manufacturer.Name + }; + } + } +} diff --git a/DatabaseImplement/Implements/ProductStorage.cs b/DatabaseImplement/Implements/ProductStorage.cs new file mode 100644 index 0000000..fcb7bf9 --- /dev/null +++ b/DatabaseImplement/Implements/ProductStorage.cs @@ -0,0 +1,144 @@ +using Contracts.BindingModels; +using Contracts.StorageContracts; +using Contracts.ViewModels; +using DatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DatabaseImplement.Implements +{ + + public class ProductStorage : IProductStorage + { + public void Delete(ProductBindingModel model) + { + var context = new ProductsDatabase(); + var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id); + if (Product != null) + { + context.Products.Remove(Product); + context.SaveChanges(); + } + else + { + throw new Exception("Продукт не найден"); + } + } + + public ProductViewModel GetElement(ProductBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new ProductsDatabase(); + var Product = context.Products + .ToList() + .FirstOrDefault(rec => rec.Id == model.Id); + return Product != null ? CreateModel(Product) : null; + } + + public List GetFilteredList(ProductBindingModel model) + { + var context = new ProductsDatabase(); + return context.Products + .ToList() + .Select(CreateModel) + .ToList(); + } + + public List<(string Manufacturer, int Count)> GetProductCountByManufacturer() + { + var context = new ProductsDatabase(); + return context.Products + .GroupBy(p => p.Manufacturers) + .Select(g => new { Manufacturer = g.Key, Count = g.Count() }) + .AsEnumerable() // Приведение к Enumerable, чтобы продолжить обработку в памяти + .Select(g => (g.Manufacturer, g.Count)) + .ToList(); + } + + private ProductViewModel CustomCreateModel(Product product) + { + return new ProductViewModel + { + Manufacturers = product.Manufacturers, + }; + } + + public List GetFullList() + { + using (var context = new ProductsDatabase()) + { + return context.Products + .ToList() + .Select(CreateModel) + .ToList(); + } + } + + public void Insert(ProductBindingModel model) + { + var context = new ProductsDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + context.Products.Add(CreateModel(model, new Product())); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + public void Update(ProductBindingModel model) + { + var context = new ProductsDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id); + if (Product == null) + { + throw new Exception("Продукт не найден"); + } + CreateModel(model, Product); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + private static Product CreateModel(ProductBindingModel model, Product Product) + { + Product.DeliveryDate = model.DeliveryDate; + Product.Name = model.Name; + Product.Manufacturers = model.Manufacturers; + Product.Image = model.Image; + + return Product; + } + + private ProductViewModel CreateModel(Product Product) + { + return new ProductViewModel + { + Id = Product.Id, + Image = Product.Image, + Name = Product.Name, + Manufacturers = Product.Manufacturers, + DeliveryDate = Product.DeliveryDate + }; + } + } +} diff --git a/DatabaseImplement/Migrations/20241012142150_Init.Designer.cs b/DatabaseImplement/Migrations/20241012142150_Init.Designer.cs new file mode 100644 index 0000000..a2c2eff --- /dev/null +++ b/DatabaseImplement/Migrations/20241012142150_Init.Designer.cs @@ -0,0 +1,74 @@ +// +using System; +using DatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DatabaseImplement.Migrations +{ + [DbContext(typeof(ProductsDatabase))] + [Migration("20241012142150_Init")] + partial class Init + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.33") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); + + modelBuilder.Entity("DatabaseImplement.Models.Manufacturer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Manufacturers"); + }); + + modelBuilder.Entity("DatabaseImplement.Models.Product", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("DeliveryDate") + .HasColumnType("datetime2"); + + b.Property("Image") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("Manufacturers") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DatabaseImplement/Migrations/20241012142150_Init.cs b/DatabaseImplement/Migrations/20241012142150_Init.cs new file mode 100644 index 0000000..b4f37b6 --- /dev/null +++ b/DatabaseImplement/Migrations/20241012142150_Init.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DatabaseImplement.Migrations +{ + public partial class Init : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Manufacturers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Manufacturers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Products", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(max)", nullable: false), + Image = table.Column(type: "varbinary(max)", nullable: false), + Manufacturers = table.Column(type: "nvarchar(max)", nullable: false), + DeliveryDate = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Products", x => x.Id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Manufacturers"); + + migrationBuilder.DropTable( + name: "Products"); + } + } +} diff --git a/DatabaseImplement/Migrations/ProductsDatabaseModelSnapshot.cs b/DatabaseImplement/Migrations/ProductsDatabaseModelSnapshot.cs new file mode 100644 index 0000000..e9ea69a --- /dev/null +++ b/DatabaseImplement/Migrations/ProductsDatabaseModelSnapshot.cs @@ -0,0 +1,72 @@ +// +using System; +using DatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace DatabaseImplement.Migrations +{ + [DbContext(typeof(ProductsDatabase))] + partial class ProductsDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.33") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); + + modelBuilder.Entity("DatabaseImplement.Models.Manufacturer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Manufacturers"); + }); + + modelBuilder.Entity("DatabaseImplement.Models.Product", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("DeliveryDate") + .HasColumnType("datetime2"); + + b.Property("Image") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("Manufacturers") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DatabaseImplement/Models/Manufacturer.cs b/DatabaseImplement/Models/Manufacturer.cs new file mode 100644 index 0000000..78b001b --- /dev/null +++ b/DatabaseImplement/Models/Manufacturer.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DatabaseImplement.Models +{ + public class Manufacturer + { + public int Id { get; set; } + + [Required] + public string Name { get; set; } + } +} diff --git a/DatabaseImplement/Models/Product.cs b/DatabaseImplement/Models/Product.cs new file mode 100644 index 0000000..e036d5b --- /dev/null +++ b/DatabaseImplement/Models/Product.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DatabaseImplement.Models +{ + public class Product + { + public int Id { get; set; } + [Required] + public string Name { get; set; } + [Required] + public byte[] Image { get; set; } + [Required] + public string Manufacturers { get; set; } + [Required] + public DateTime DeliveryDate { get; set; } + } +} diff --git a/DatabaseImplement/ProductsDatabase.cs b/DatabaseImplement/ProductsDatabase.cs new file mode 100644 index 0000000..2b6f5eb --- /dev/null +++ b/DatabaseImplement/ProductsDatabase.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.NetworkInformation; +using System.Text; +using System.Threading.Tasks; +using DatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace DatabaseImplement +{ + public class ProductsDatabase : DbContext + { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (optionsBuilder.IsConfigured == false) + { + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-SPMUS7R;Initial Catalog=ProductsDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + } + base.OnConfiguring(optionsBuilder); + } + public virtual DbSet Products { set; get; } + public virtual DbSet Manufacturers { set; get; } + } +} diff --git a/README.md b/README.md deleted file mode 100644 index e0f2c6d..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# PIbd-33_Dyakonov_R_R_COP_14 - diff --git a/ShopProducts.sln b/ShopProducts.sln new file mode 100644 index 0000000..3600486 --- /dev/null +++ b/ShopProducts.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34408.163 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopProducts", "ShopProducts\ShopProducts.csproj", "{E8F82DF1-6741-454A-B96D-C1F2FB29134D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Contracts", "Contracts\Contracts.csproj", "{F2440E2E-293A-4107-980B-EC0020529692}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BusinessLogic", "BusinessLogic\BusinessLogic.csproj", "{344C1681-67A5-485B-8E99-89F7D5866078}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseImplement", "DatabaseImplement\DatabaseImplement.csproj", "{80BABD36-989A-4181-9159-23A0BD3CF04A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Release|Any CPU.Build.0 = Release|Any CPU + {F2440E2E-293A-4107-980B-EC0020529692}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2440E2E-293A-4107-980B-EC0020529692}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2440E2E-293A-4107-980B-EC0020529692}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2440E2E-293A-4107-980B-EC0020529692}.Release|Any CPU.Build.0 = Release|Any CPU + {344C1681-67A5-485B-8E99-89F7D5866078}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {344C1681-67A5-485B-8E99-89F7D5866078}.Debug|Any CPU.Build.0 = Debug|Any CPU + {344C1681-67A5-485B-8E99-89F7D5866078}.Release|Any CPU.ActiveCfg = Release|Any CPU + {344C1681-67A5-485B-8E99-89F7D5866078}.Release|Any CPU.Build.0 = Release|Any CPU + {80BABD36-989A-4181-9159-23A0BD3CF04A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {80BABD36-989A-4181-9159-23A0BD3CF04A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {80BABD36-989A-4181-9159-23A0BD3CF04A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80BABD36-989A-4181-9159-23A0BD3CF04A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1B480F8A-27B6-4A43-896B-4B570320DF49} + EndGlobalSection +EndGlobal diff --git a/ShopProducts/FormManufacturers.Designer.cs b/ShopProducts/FormManufacturers.Designer.cs new file mode 100644 index 0000000..eb99f3c --- /dev/null +++ b/ShopProducts/FormManufacturers.Designer.cs @@ -0,0 +1,63 @@ +namespace ShopProducts +{ + partial class FormManufacturers + { + /// + /// 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() + { + dataGridView1 = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); + SuspendLayout(); + // + // dataGridView1 + // + dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView1.Location = new Point(12, 12); + dataGridView1.Name = "dataGridView1"; + dataGridView1.RowTemplate.Height = 25; + dataGridView1.Size = new Size(642, 350); + dataGridView1.TabIndex = 0; + dataGridView1.CellContentClick += dataGridView1_CellContentClick; + dataGridView1.KeyDown += dataGridView1_KeyDown; + // + // FormManufacturers + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(663, 374); + Controls.Add(dataGridView1); + Name = "FormManufacturers"; + Text = "FormManufacturers"; + Load += FormManufacturers_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView1; + } +} \ No newline at end of file diff --git a/ShopProducts/FormManufacturers.cs b/ShopProducts/FormManufacturers.cs new file mode 100644 index 0000000..d42e7a3 --- /dev/null +++ b/ShopProducts/FormManufacturers.cs @@ -0,0 +1,117 @@ +using Contracts.BindingModels; +using Contracts.BusinessLogicContracts; +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 ShopProducts +{ + public partial class FormManufacturers : Form + { + private readonly IManufacturerLogic _manufacturerLogic; + BindingList list; + public FormManufacturers(IManufacturerLogic manufacturerLogic) + { + InitializeComponent(); + _manufacturerLogic = manufacturerLogic; + list = new BindingList(); + // dataGridView1.AllowUserToAddRows = false; + } + + private void LoadData() + { + try + { + var list1 = _manufacturerLogic.Read(null); + list.Clear(); + foreach (var item in list1) + { + list.Add(new ManufacturerBindingModel + { + Id = item.Id, + Name = item.Name, + }); + } + if (list != null) + { + dataGridView1.DataSource = list; + dataGridView1.Columns[0].Visible = false; + dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormManufacturers_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) + { + var typeName = (string)dataGridView1.CurrentRow.Cells[1].Value; + if (!string.IsNullOrEmpty(typeName)) + { + if (dataGridView1.CurrentRow.Cells[0].Value != null) + { + _manufacturerLogic.CreateOrUpdate(new ManufacturerBindingModel() + { + Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value), + Name = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue + }); + } + else + { + _manufacturerLogic.CreateOrUpdate(new ManufacturerBindingModel() + { + Name = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue + }); + } + } + else + { + MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + + private void dataGridView1_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyData == Keys.Insert) + { + if (dataGridView1.Rows.Count == 0) + { + list.Add(new ManufacturerBindingModel()); + dataGridView1.DataSource = new BindingList(list); + dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1]; + return; + } + if (dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value != null) + { + list.Add(new ManufacturerBindingModel()); + dataGridView1.DataSource = new BindingList(list); + dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1]; + return; + } + } + if (e.KeyData == Keys.Delete) + { + if (MessageBox.Show("Удалить выбранный элемент", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + _manufacturerLogic.Delete(new ManufacturerBindingModel() { Id = (int)dataGridView1.CurrentRow.Cells[0].Value }); + LoadData(); + } + } + } + } +} diff --git a/WinFormsLibrary1/CustomCheckedListBox.resx b/ShopProducts/FormManufacturers.resx similarity index 100% rename from WinFormsLibrary1/CustomCheckedListBox.resx rename to ShopProducts/FormManufacturers.resx diff --git a/ShopProducts/FormProduct.Designer.cs b/ShopProducts/FormProduct.Designer.cs new file mode 100644 index 0000000..c436e37 --- /dev/null +++ b/ShopProducts/FormProduct.Designer.cs @@ -0,0 +1,189 @@ +namespace ShopProducts +{ + partial class FormProduct + { + /// + /// 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() + { + textBoxName = new TextBox(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + customComboBoxManufacturers = new ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle(); + label4 = new Label(); + customTextBoxDate = new ControlsLibraryNet60.Input.ControlInputRegexDate(); + buttonSave = new Button(); + buttonCancel = new Button(); + imageFileLabel = new Label(); + pickFileButton = new Button(); + SuspendLayout(); + // + // textBoxName + // + textBoxName.Location = new Point(14, 36); + textBoxName.Margin = new Padding(3, 4, 3, 4); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(261, 27); + textBoxName.TabIndex = 0; + textBoxName.TextChanged += textBoxName_TextChanged; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(14, 12); + label1.Name = "label1"; + label1.Size = new Size(49, 20); + label1.TabIndex = 1; + label1.Text = "Name"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(13, 71); + label2.Name = "label2"; + label2.Size = new Size(51, 20); + label2.TabIndex = 2; + label2.Text = "Image"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(13, 129); + label3.Name = "label3"; + label3.Size = new Size(103, 20); + label3.TabIndex = 4; + label3.Text = "Manufacturers"; + // + // customComboBoxManufacturers + // + customComboBoxManufacturers.Location = new Point(16, 153); + customComboBoxManufacturers.Margin = new Padding(6, 4, 6, 4); + customComboBoxManufacturers.Name = "customComboBoxManufacturers"; + customComboBoxManufacturers.SelectedElement = ""; + customComboBoxManufacturers.Size = new Size(256, 32); + customComboBoxManufacturers.TabIndex = 5; + customComboBoxManufacturers.SelectedElementChange += customComboBoxManufacturers_SelectedElementChange; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(16, 189); + label4.Name = "label4"; + label4.Size = new Size(41, 20); + label4.TabIndex = 6; + label4.Text = "Date"; + // + // customTextBoxDate + // + customTextBoxDate.Location = new Point(16, 213); + customTextBoxDate.Margin = new Padding(6, 4, 6, 4); + customTextBoxDate.Name = "customTextBoxDate"; + customTextBoxDate.Pattern = "^\\d{1,2} \\w{3,8} \\d{4}$"; + customTextBoxDate.Size = new Size(256, 31); + customTextBoxDate.TabIndex = 7; + customTextBoxDate.Value = ""; + customTextBoxDate.ElementChanged += customTextBoxDate_ElementChanged; + // + // buttonSave + // + buttonSave.Location = new Point(16, 272); + buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(86, 31); + buttonSave.TabIndex = 8; + buttonSave.Text = "Save"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(186, 272); + buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(86, 31); + buttonCancel.TabIndex = 9; + buttonCancel.Text = "Cancel"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // imageFileLabel + // + imageFileLabel.AutoSize = true; + imageFileLabel.Location = new Point(16, 101); + imageFileLabel.Name = "imageFileLabel"; + imageFileLabel.Size = new Size(54, 20); + imageFileLabel.TabIndex = 10; + imageFileLabel.Text = "No file"; + // + // pickFileButton + // + pickFileButton.Location = new Point(135, 97); + pickFileButton.Name = "pickFileButton"; + pickFileButton.Size = new Size(140, 29); + pickFileButton.TabIndex = 11; + pickFileButton.Text = "Pick file"; + pickFileButton.UseVisualStyleBackColor = true; + pickFileButton.Click += pickFileButton_Click; + // + // FormProduct + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(287, 331); + Controls.Add(pickFileButton); + Controls.Add(imageFileLabel); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(customTextBoxDate); + Controls.Add(label4); + Controls.Add(customComboBoxManufacturers); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(textBoxName); + Margin = new Padding(3, 4, 3, 4); + Name = "FormProduct"; + Text = "FormProduct"; + Load += FormProduct_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxName; + private Label label1; + private Label label2; + private Label label3; + private ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle customComboBoxManufacturers; + private Label label4; + private ControlsLibraryNet60.Input.ControlInputRegexDate customTextBoxDate; + private Button buttonSave; + private Button buttonCancel; + private Label imageFileLabel; + private Button pickFileButton; + } +} \ No newline at end of file diff --git a/ShopProducts/FormProduct.cs b/ShopProducts/FormProduct.cs new file mode 100644 index 0000000..9d01859 --- /dev/null +++ b/ShopProducts/FormProduct.cs @@ -0,0 +1,160 @@ +using Contracts.BindingModels; +using Contracts.BusinessLogicContracts; +using Contracts.ViewModels; +using DocumentFormat.OpenXml.Office2010.Excel; +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 ShopProducts +{ + // ^\d{2}\s(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}$ + + public partial class FormProduct : Form + { + public int Id { set { id = value; } } + + private readonly IProductLogic _logic; + private readonly IManufacturerLogic _logicM; + + private int? id; + private bool _wasChanged = false; + + private byte[]? productImage = null; + public FormProduct(IProductLogic logic, IManufacturerLogic logicM) + { + InitializeComponent(); + _logic = logic; + _logicM = logicM; + } + + private void buttonSave_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните имя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (productImage == null) + { + MessageBox.Show("Выберите фото", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(customComboBoxManufacturers.SelectedElement)) + { + MessageBox.Show("Выберите производителя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(customTextBoxDate.Value)) + { + MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + var date = DateTime.ParseExact(customTextBoxDate.Value, "dd MMMM yyyy", new System.Globalization.CultureInfo("ru-RU")); + _logic.CreateOrUpdate(new ProductBindingModel + { + Id = id, + Image = productImage, + Name = textBoxName.Text, + Manufacturers = customComboBoxManufacturers.SelectedElement.ToString(), + DeliveryDate = date, + }); + 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) + { + if (_wasChanged) + { + DialogResult dialogResult = MessageBox.Show("Есть внесенные изменения, вы точно хотите выйти?", "Предупреждение", MessageBoxButtons.YesNo); + if (dialogResult == DialogResult.Yes) + { + Close(); + } + return; + } + DialogResult = DialogResult.Cancel; + Close(); + } + + private void textBoxName_TextChanged(object sender, EventArgs e) + { + _wasChanged = true; + } + + private void textBoxImage_TextChanged(object sender, EventArgs e) + { + _wasChanged = true; + } + + private void customComboBoxManufacturers_SelectedElementChange(object sender, EventArgs e) + { + _wasChanged = true; + } + + private void customTextBoxDate_ElementChanged(object sender, EventArgs e) + { + _wasChanged = true; + } + + private void FormProduct_Load(object sender, EventArgs e) + { + List mViews = _logicM.Read(null); + if (mViews != null) + { + for (int i = 0; i < mViews.Count; i++) + { + customComboBoxManufacturers.AddElement(mViews[i].Name); + } + } + + if (id.HasValue) + { + ProductViewModel product = _logic.Read(new ProductBindingModel { Id = id.Value })?[0]; + if (product != null) + { + textBoxName.Text = product.Name; + ChangeImageFile(product.Image); + customComboBoxManufacturers.SelectedElement = product.Manufacturers; + var date = product.DeliveryDate.ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("ru-RU")); + customTextBoxDate.Value = date; + } + } + } + + private void pickFileButton_Click(object sender, EventArgs e) + { + using OpenFileDialog openFileDialog = new OpenFileDialog + { + Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp" + }; + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + ChangeImageFile(File.ReadAllBytes(openFileDialog.FileName)); + } + } + + private void ChangeImageFile(byte[]? bytes) + { + productImage = bytes; + imageFileLabel.Text = bytes == null ? "No file" : "File picked"; + } + } +} diff --git a/WinFormsLibrary1/CustomDataTree.resx b/ShopProducts/FormProduct.resx similarity index 100% rename from WinFormsLibrary1/CustomDataTree.resx rename to ShopProducts/FormProduct.resx diff --git a/ShopProducts/FormProducts.Designer.cs b/ShopProducts/FormProducts.Designer.cs new file mode 100644 index 0000000..bed137e --- /dev/null +++ b/ShopProducts/FormProducts.Designer.cs @@ -0,0 +1,147 @@ +namespace ShopProducts +{ + partial class FormProducts + { + /// + /// 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(); + controlDataTableRow1 = new ControlsLibraryNet60.Data.ControlDataTableRow(); + contextMenuStrip1 = new ContextMenuStrip(components); + сохранитьВордtoolStripMenuItem = new ToolStripMenuItem(); + сохранитьЭксельtoolStripMenuItem = new ToolStripMenuItem(); + сохранитьПдфtoolStripMenuItem = new ToolStripMenuItem(); + удалитьtoolStripMenuItem = new ToolStripMenuItem(); + редактироватьtoolStripMenuItem = new ToolStripMenuItem(); + добавитьtoolStripMenuItem = new ToolStripMenuItem(); + справочникtoolStripMenuItem = new ToolStripMenuItem(); + pdfWithImages1 = new WinFormsLibrary1.PdfWithImages(components); + componentDocumentWithTableHeaderRowExcel1 = new ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableHeaderRowExcel(components); + componentDocumentWithChartBarWord1 = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components); + contextMenuStrip1.SuspendLayout(); + SuspendLayout(); + // + // controlDataTableRow1 + // + controlDataTableRow1.Location = new Point(89, 53); + controlDataTableRow1.Margin = new Padding(5, 4, 5, 4); + controlDataTableRow1.Name = "controlDataTableRow1"; + controlDataTableRow1.SelectedRowIndex = -1; + controlDataTableRow1.Size = new Size(730, 479); + controlDataTableRow1.TabIndex = 0; + // + // contextMenuStrip1 + // + contextMenuStrip1.ImageScalingSize = new Size(20, 20); + contextMenuStrip1.Items.AddRange(new ToolStripItem[] { сохранитьВордtoolStripMenuItem, сохранитьЭксельtoolStripMenuItem, сохранитьПдфtoolStripMenuItem, удалитьtoolStripMenuItem, редактироватьtoolStripMenuItem, добавитьtoolStripMenuItem, справочникtoolStripMenuItem }); + contextMenuStrip1.Name = "contextMenuStrip1"; + contextMenuStrip1.Size = new Size(255, 172); + // + // сохранитьВордtoolStripMenuItem + // + сохранитьВордtoolStripMenuItem.Name = "сохранитьВордtoolStripMenuItem"; + сохранитьВордtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + сохранитьВордtoolStripMenuItem.Size = new Size(254, 24); + сохранитьВордtoolStripMenuItem.Text = "Сохранить Ворд"; + сохранитьВордtoolStripMenuItem.Click += сохранитьВордToolStripMenuItem_Click; + // + // сохранитьЭксельtoolStripMenuItem + // + сохранитьЭксельtoolStripMenuItem.Name = "сохранитьЭксельtoolStripMenuItem"; + сохранитьЭксельtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; + сохранитьЭксельtoolStripMenuItem.Size = new Size(254, 24); + сохранитьЭксельtoolStripMenuItem.Text = "Сохранить Эксель"; + сохранитьЭксельtoolStripMenuItem.Click += сохранитьЭксельToolStripMenuItem_Click; + // + // сохранитьПдфtoolStripMenuItem + // + сохранитьПдфtoolStripMenuItem.Name = "сохранитьПдфtoolStripMenuItem"; + сохранитьПдфtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; + сохранитьПдфtoolStripMenuItem.Size = new Size(254, 24); + сохранитьПдфtoolStripMenuItem.Text = "Сохранить ПДФ"; + сохранитьПдфtoolStripMenuItem.Click += сохранитьПдфToolStripMenuItem_Click; + // + // удалитьtoolStripMenuItem + // + удалитьtoolStripMenuItem.Name = "удалитьtoolStripMenuItem"; + удалитьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.D; + удалитьtoolStripMenuItem.Size = new Size(254, 24); + удалитьtoolStripMenuItem.Text = "Удалить"; + удалитьtoolStripMenuItem.Click += удалитьToolStripMenuItem_Click; + // + // редактироватьtoolStripMenuItem + // + редактироватьtoolStripMenuItem.Name = "редактироватьtoolStripMenuItem"; + редактироватьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U; + редактироватьtoolStripMenuItem.Size = new Size(254, 24); + редактироватьtoolStripMenuItem.Text = "Редактировать"; + редактироватьtoolStripMenuItem.Click += редактироватьToolStripMenuItem_Click; + // + // добавитьtoolStripMenuItem + // + добавитьtoolStripMenuItem.Name = "добавитьtoolStripMenuItem"; + добавитьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.A; + добавитьtoolStripMenuItem.Size = new Size(254, 24); + добавитьtoolStripMenuItem.Text = "Добавить"; + добавитьtoolStripMenuItem.Click += добавитьToolStripMenuItem_Click; + // + // справочникtoolStripMenuItem + // + справочникtoolStripMenuItem.Name = "справочникtoolStripMenuItem"; + справочникtoolStripMenuItem.Size = new Size(254, 24); + справочникtoolStripMenuItem.Text = "Справочник"; + справочникtoolStripMenuItem.Click += справочникToolStripMenuItem_Click; + // + // FormProducts + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(914, 600); + Controls.Add(controlDataTableRow1); + Margin = new Padding(3, 4, 3, 4); + Name = "FormProducts"; + Text = "Form1"; + Load += FormProducts_Load; + contextMenuStrip1.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private ControlsLibraryNet60.Data.ControlDataTableRow controlDataTableRow1; + private ContextMenuStrip contextMenuStrip1; + private ToolStripMenuItem сохранитьВордtoolStripMenuItem; + private ToolStripMenuItem сохранитьЭксельtoolStripMenuItem; + private ToolStripMenuItem сохранитьПдфtoolStripMenuItem; + private ToolStripMenuItem удалитьtoolStripMenuItem; + private ToolStripMenuItem редактироватьtoolStripMenuItem; + private ToolStripMenuItem добавитьtoolStripMenuItem; + private ToolStripMenuItem справочникtoolStripMenuItem; + private WinFormsLibrary1.PdfWithImages pdfWithImages1; + private ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableHeaderRowExcel componentDocumentWithTableHeaderRowExcel1; + private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord1; + } +} diff --git a/ShopProducts/FormProducts.cs b/ShopProducts/FormProducts.cs new file mode 100644 index 0000000..9903a12 --- /dev/null +++ b/ShopProducts/FormProducts.cs @@ -0,0 +1,250 @@ +using ComponentsLibraryNet60.Models; +using Contracts.BindingModels; +using Contracts.BusinessLogicContracts; +using Contracts.ViewModels; +using ControlsLibraryNet60.Models; +using DocumentFormat.OpenXml.Drawing.Charts; +using WinFormsLibrary1.Configs.Image; + +namespace ShopProducts +{ + public partial class FormProducts : Form + { + private readonly IProductLogic _productLogic; + public FormProducts(IProductLogic productLogic) + { + InitializeComponent(); + _productLogic = productLogic; + controlDataTableRow1.ContextMenuStrip = contextMenuStrip1; + InitTable(); + } + + private void InitTable() + { + var tableConfig = new List + { + new DataTableColumnConfig + { + ColumnHeader = "Id", + PropertyName = "Id", + Visible = false + }, + new DataTableColumnConfig + { + ColumnHeader = "Name", + PropertyName = "Name", + Visible = true + }, + new DataTableColumnConfig + { + ColumnHeader = "Manufacturers", + PropertyName = "Manufacturers", + Visible = true + }, + new DataTableColumnConfig + { + ColumnHeader = "Delivery date", + PropertyName = "DeliveryDate", + Visible = true + } + }; + + controlDataTableRow1.LoadColumns(tableConfig); + } + + private void LoadData() + { + try + { + controlDataTableRow1.Clear(); + + var list = _productLogic.Read(null); + for (int i = 0; i < list.Count; i++) + { + controlDataTableRow1.AddRow(list[i]); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormProducts_Load(object sender, EventArgs e) + { + LoadData(); + } + private void AddNewElement() + { + var service = Program.ServiceProvider?.GetService(typeof(FormProduct)); + if (service is FormProduct form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void UpdateElement() + { + var selectedProduct = controlDataTableRow1.GetSelectedObject(); + if (selectedProduct != null) + { + var service = Program.ServiceProvider?.GetService(typeof(FormProduct)); + if (service is FormProduct form) + { + form.Id = Convert.ToInt32(selectedProduct.Id); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + else + { + MessageBox.Show(" "); + } + } + + private void DeleteElement() + { + if (MessageBox.Show(" ", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + var selectedProduct = controlDataTableRow1.GetSelectedObject(); + try + { + int id = Convert.ToInt32(selectedProduct.Id); + _productLogic.Delete(new ProductBindingModel { Id = id }); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + } + + private void CreateWord() + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "Word Document (*.docx)|*.docx"; + saveFileDialog.Title = " Word "; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + var data = _productLogic.GetWordInfo(); + componentDocumentWithChartBarWord1.CreateDoc(new ComponentDocumentWithChartConfig + { + FilePath = saveFileDialog.FileName, + Header = " ", + ChartTitle = "- ", + LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom, + Data = new Dictionary> + { + { "TTT", data } + } + }); + + MessageBox.Show("Word !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + + private void CreateExcel() + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "Excel Workbook (*.xlsx)|*.xlsx"; + saveFileDialog.Title = " Excel "; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + var list = _productLogic.Read(null); + componentDocumentWithTableHeaderRowExcel1.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig + { + FilePath = saveFileDialog.FileName, + Header = "", + UseUnion = true, + ColumnsRowsWidth = new List<(int, int)> { (5, 0), (10, 0), (10, 0), (10, 0) }, + ColumnUnion = new List<(int StartIndex, int Count)> { (1, 2) }, + Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)> + { + (0, 0, "ID", "Id"), + (1, 0, "", ""), + (1, 1, "", "Name"), + (2, 1, "", "Manufacturers"), + (3, 0, " ", "DeliveryDate"), + }, + Data = list + }); + + MessageBox.Show("Excel !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + + private void CreatePdf() + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf"; + saveFileDialog.Title = " PDF "; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + var productImages = _productLogic.Read(null).Select(p => p.Image).ToList(); + var config = new PdfWithImageConfig + { + FilePath = saveFileDialog.FileName, + Header = " ", + Images = productImages + }; + pdfWithImages1.CreatePdf(config); + MessageBox.Show("PDF !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + CreateWord(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + CreateExcel(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + CreatePdf(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + DeleteElement(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + UpdateElement(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + AddNewElement(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormManufacturers)); + if (service is FormManufacturers form) + { + form.ShowDialog(); + } + } + } +} diff --git a/WinFormsApp1/Form1.resx b/ShopProducts/FormProducts.resx similarity index 89% rename from WinFormsApp1/Form1.resx rename to ShopProducts/FormProducts.resx index ce966af..5952d99 100644 --- a/WinFormsApp1/Form1.resx +++ b/ShopProducts/FormProducts.resx @@ -117,7 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 + + 202, 17 + + + 368, 17 + + + 17, 58 + \ No newline at end of file diff --git a/ShopProducts/Program.cs b/ShopProducts/Program.cs new file mode 100644 index 0000000..fed88cf --- /dev/null +++ b/ShopProducts/Program.cs @@ -0,0 +1,44 @@ +using BusinessLogic; +using Contracts.BusinessLogicContracts; +using Contracts.StorageContracts; +using DatabaseImplement.Implements; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace ShopProducts +{ + internal static class Program + { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + Application.Run(_serviceProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + }); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } +} \ No newline at end of file diff --git a/ShopProducts/ShopProducts.csproj b/ShopProducts/ShopProducts.csproj new file mode 100644 index 0000000..e8f47d1 --- /dev/null +++ b/ShopProducts/ShopProducts.csproj @@ -0,0 +1,27 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + \ No newline at end of file diff --git a/WinFormsApp1/Form1.Designer.cs b/WinFormsApp1/Form1.Designer.cs deleted file mode 100644 index 485317c..0000000 --- a/WinFormsApp1/Form1.Designer.cs +++ /dev/null @@ -1,334 +0,0 @@ -namespace WinFormsApp1 -{ - partial class Form1 - { - /// - /// 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(); - customCheckedListBox = new WinFormsLibrary1.CustomCheckedListBox(); - addInListboxItemButton = new Button(); - clearListboxButton = new Button(); - listboxItemValuetextBox = new TextBox(); - getSelectedItemButton = new Button(); - selectedItemLabel = new Label(); - customTextBox = new WinFormsLibrary1.CustomTextBox(); - errorCustomTextBoxLabel = new Label(); - checkCustomTextBoxButton = new Button(); - customDataTree = new WinFormsLibrary1.CustomDataTree(); - label1 = new Label(); - nameTextBox = new TextBox(); - label2 = new Label(); - positionTextBox = new TextBox(); - label3 = new Label(); - addEmployeeButton = new Button(); - departamentComboBox = new ComboBox(); - getSelectedTreeItemButton = new Button(); - pdfWithImages1 = new WinFormsLibrary1.PdfWithImages(components); - listBoxImages = new ListBox(); - button1 = new Button(); - createPdfButton = new Button(); - pdfTableButton = new Button(); - pdfDiagramButton = new Button(); - SuspendLayout(); - // - // customCheckedListBox - // - customCheckedListBox.Location = new Point(25, 9); - customCheckedListBox.Margin = new Padding(3, 2, 3, 2); - customCheckedListBox.Name = "customCheckedListBox"; - customCheckedListBox.SelectedElement = ""; - customCheckedListBox.Size = new Size(130, 156); - customCheckedListBox.TabIndex = 0; - // - // addInListboxItemButton - // - addInListboxItemButton.Location = new Point(175, 35); - addInListboxItemButton.Margin = new Padding(3, 2, 3, 2); - addInListboxItemButton.Name = "addInListboxItemButton"; - addInListboxItemButton.Size = new Size(130, 28); - addInListboxItemButton.TabIndex = 1; - addInListboxItemButton.Text = "Add or select item"; - addInListboxItemButton.UseVisualStyleBackColor = true; - addInListboxItemButton.Click += addInListboxItemButton_Click; - // - // clearListboxButton - // - clearListboxButton.Location = new Point(175, 68); - clearListboxButton.Margin = new Padding(3, 2, 3, 2); - clearListboxButton.Name = "clearListboxButton"; - clearListboxButton.Size = new Size(130, 28); - clearListboxButton.TabIndex = 2; - clearListboxButton.Text = "Clear listbox"; - clearListboxButton.UseVisualStyleBackColor = true; - clearListboxButton.Click += clearListboxButton_Click; - // - // listboxItemValuetextBox - // - listboxItemValuetextBox.Location = new Point(175, 9); - listboxItemValuetextBox.Margin = new Padding(3, 2, 3, 2); - listboxItemValuetextBox.Name = "listboxItemValuetextBox"; - listboxItemValuetextBox.Size = new Size(131, 23); - listboxItemValuetextBox.TabIndex = 3; - // - // getSelectedItemButton - // - getSelectedItemButton.Location = new Point(175, 125); - getSelectedItemButton.Margin = new Padding(3, 2, 3, 2); - getSelectedItemButton.Name = "getSelectedItemButton"; - getSelectedItemButton.Size = new Size(130, 32); - getSelectedItemButton.TabIndex = 4; - getSelectedItemButton.Text = "Get selected item"; - getSelectedItemButton.UseVisualStyleBackColor = true; - getSelectedItemButton.Click += getSelectedItemButton_Click; - // - // selectedItemLabel - // - selectedItemLabel.AutoSize = true; - selectedItemLabel.Location = new Point(175, 108); - selectedItemLabel.Name = "selectedItemLabel"; - selectedItemLabel.Size = new Size(84, 15); - selectedItemLabel.TabIndex = 5; - selectedItemLabel.Text = "Selected item: "; - // - // customTextBox - // - customTextBox.Location = new Point(370, 9); - customTextBox.Margin = new Padding(3, 2, 3, 2); - customTextBox.MaxLength = 5; - customTextBox.MinLength = 0; - customTextBox.Name = "customTextBox"; - customTextBox.Size = new Size(208, 23); - customTextBox.TabIndex = 6; - customTextBox.Value = ""; - // - // errorCustomTextBoxLabel - // - errorCustomTextBoxLabel.AutoSize = true; - errorCustomTextBoxLabel.Location = new Point(370, 68); - errorCustomTextBoxLabel.Name = "errorCustomTextBoxLabel"; - errorCustomTextBoxLabel.Size = new Size(0, 15); - errorCustomTextBoxLabel.TabIndex = 7; - // - // checkCustomTextBoxButton - // - checkCustomTextBoxButton.Location = new Point(370, 35); - checkCustomTextBoxButton.Margin = new Padding(3, 2, 3, 2); - checkCustomTextBoxButton.Name = "checkCustomTextBoxButton"; - checkCustomTextBoxButton.Size = new Size(208, 28); - checkCustomTextBoxButton.TabIndex = 8; - checkCustomTextBoxButton.Text = "Check"; - checkCustomTextBoxButton.UseVisualStyleBackColor = true; - checkCustomTextBoxButton.Click += checkCustomTextBoxButton_Click; - // - // customDataTree - // - customDataTree.Location = new Point(25, 189); - customDataTree.Name = "customDataTree"; - customDataTree.Size = new Size(281, 193); - customDataTree.TabIndex = 9; - // - // label1 - // - label1.AutoSize = true; - label1.Location = new Point(342, 277); - label1.Name = "label1"; - label1.Size = new Size(39, 15); - label1.TabIndex = 10; - label1.Text = "Name"; - // - // nameTextBox - // - nameTextBox.Location = new Point(343, 295); - nameTextBox.Name = "nameTextBox"; - nameTextBox.Size = new Size(152, 23); - nameTextBox.TabIndex = 11; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new Point(342, 233); - label2.Name = "label2"; - label2.Size = new Size(50, 15); - label2.TabIndex = 12; - label2.Text = "Position"; - // - // positionTextBox - // - positionTextBox.Location = new Point(343, 251); - positionTextBox.Name = "positionTextBox"; - positionTextBox.Size = new Size(152, 23); - positionTextBox.TabIndex = 13; - // - // label3 - // - label3.AutoSize = true; - label3.Location = new Point(343, 189); - label3.Name = "label3"; - label3.Size = new Size(76, 15); - label3.TabIndex = 14; - label3.Text = "Departament"; - // - // addEmployeeButton - // - addEmployeeButton.Location = new Point(342, 324); - addEmployeeButton.Name = "addEmployeeButton"; - addEmployeeButton.Size = new Size(152, 22); - addEmployeeButton.TabIndex = 15; - addEmployeeButton.Text = "Add employee"; - addEmployeeButton.UseVisualStyleBackColor = true; - addEmployeeButton.Click += addEmployeeButton_Click; - // - // departamentComboBox - // - departamentComboBox.FormattingEnabled = true; - departamentComboBox.Location = new Point(342, 207); - departamentComboBox.Name = "departamentComboBox"; - departamentComboBox.Size = new Size(152, 23); - departamentComboBox.TabIndex = 16; - // - // getSelectedTreeItemButton - // - getSelectedTreeItemButton.Location = new Point(342, 352); - getSelectedTreeItemButton.Name = "getSelectedTreeItemButton"; - getSelectedTreeItemButton.Size = new Size(152, 30); - getSelectedTreeItemButton.TabIndex = 17; - getSelectedTreeItemButton.Text = "Get selected"; - getSelectedTreeItemButton.UseVisualStyleBackColor = true; - getSelectedTreeItemButton.Click += getSelectedTreeItemButton_Click; - // - // listBoxImages - // - listBoxImages.FormattingEnabled = true; - listBoxImages.ItemHeight = 15; - listBoxImages.Location = new Point(25, 398); - listBoxImages.Name = "listBoxImages"; - listBoxImages.Size = new Size(280, 124); - listBoxImages.TabIndex = 18; - // - // button1 - // - button1.Location = new Point(25, 528); - button1.Name = "button1"; - button1.Size = new Size(139, 23); - button1.TabIndex = 19; - button1.Text = "Выбрать изображения"; - button1.UseVisualStyleBackColor = true; - button1.Click += button1_Click; - // - // createPdfButton - // - createPdfButton.Location = new Point(170, 528); - createPdfButton.Name = "createPdfButton"; - createPdfButton.Size = new Size(135, 23); - createPdfButton.TabIndex = 20; - createPdfButton.Text = "Создать PDF"; - createPdfButton.UseVisualStyleBackColor = true; - createPdfButton.Click += createPdfButton_Click; - // - // pdfTableButton - // - pdfTableButton.Location = new Point(342, 398); - pdfTableButton.Name = "pdfTableButton"; - pdfTableButton.Size = new Size(152, 23); - pdfTableButton.TabIndex = 21; - pdfTableButton.Text = "Создать таблицу в PDF"; - pdfTableButton.UseVisualStyleBackColor = true; - pdfTableButton.Click += pdfTableButton_Click; - // - // pdfDiagramButton - // - pdfDiagramButton.Location = new Point(342, 427); - pdfDiagramButton.Name = "pdfDiagramButton"; - pdfDiagramButton.Size = new Size(152, 23); - pdfDiagramButton.TabIndex = 22; - pdfDiagramButton.Text = "Создать диаграмму"; - pdfDiagramButton.UseVisualStyleBackColor = true; - pdfDiagramButton.Click += pdfDiagramButton_Click; - // - // Form1 - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(700, 566); - Controls.Add(pdfDiagramButton); - Controls.Add(pdfTableButton); - Controls.Add(createPdfButton); - Controls.Add(button1); - Controls.Add(listBoxImages); - Controls.Add(getSelectedTreeItemButton); - Controls.Add(departamentComboBox); - Controls.Add(addEmployeeButton); - Controls.Add(label3); - Controls.Add(positionTextBox); - Controls.Add(label2); - Controls.Add(nameTextBox); - Controls.Add(label1); - Controls.Add(customDataTree); - Controls.Add(checkCustomTextBoxButton); - Controls.Add(errorCustomTextBoxLabel); - Controls.Add(customTextBox); - Controls.Add(selectedItemLabel); - Controls.Add(getSelectedItemButton); - Controls.Add(listboxItemValuetextBox); - Controls.Add(clearListboxButton); - Controls.Add(addInListboxItemButton); - Controls.Add(customCheckedListBox); - Margin = new Padding(3, 2, 3, 2); - Name = "Form1"; - Text = "Form1"; - ResumeLayout(false); - PerformLayout(); - } - - #endregion - - private WinFormsLibrary1.CustomCheckedListBox customCheckedListBox; - private Button addInListboxItemButton; - private Button clearListboxButton; - private TextBox listboxItemValuetextBox; - private Button getSelectedItemButton; - private Label selectedItemLabel; - private WinFormsLibrary1.CustomTextBox customTextBox; - private Label errorCustomTextBoxLabel; - private Button checkCustomTextBoxButton; - private WinFormsLibrary1.CustomDataTree customDataTree; - private Label label1; - private TextBox nameTextBox; - private Label label2; - private TextBox positionTextBox; - private Label label3; - private Button addEmployeeButton; - private ComboBox departamentComboBox; - private Button getSelectedTreeItemButton; - private WinFormsLibrary1.PdfWithImages pdfWithImages1; - private ListBox listBoxImages; - private Button button1; - private Button createPdfButton; - private Button pdfTableButton; - private Button pdfDiagramButton; - } -} diff --git a/WinFormsApp1/Form1.cs b/WinFormsApp1/Form1.cs deleted file mode 100644 index ded07d5..0000000 --- a/WinFormsApp1/Form1.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System.Security.Cryptography.Xml; -using WinFormsLibrary1; -using WinFormsLibrary1.Configs.Diagram; -using WinFormsLibrary1.Configs.Image; -using WinFormsLibrary1.Models; -using WinFormsLibrary1.Errors; -using WinFormsLibrary1.Configs.Diagram; -using WinFormsLibrary1.Configs.Table; -using PdfSharp.Pdf.Content.Objects; - -namespace WinFormsApp1 -{ - public partial class Form1 : Form - { - private PdfWithImages pdfWithImages = new PdfWithImages(); - private List selectedImages = new List(); - - private PdfWithTable pdfWithTable = new PdfWithTable(); - - private PdfWithDiagram pdfWithDiagram = new PdfWithDiagram(); - - public Form1() - { - InitializeComponent(); - FillCustomCheckedListBox(); - FillCustomDataTree(); - } - - private void FillCustomCheckedListBox() - { - List list = new List() { " 1", " 2", " 3" }; - for (int i = 0; i < list.Count; i++) - { - customCheckedListBox.AddItem(list[i]); - } - } - - private void FillCustomDataTree() - { - departamentComboBox.Items.Add(" "); - departamentComboBox.Items.Add(" "); - departamentComboBox.Items.Add("IT "); - - DataTreeNodeConfig config = new DataTreeNodeConfig(new List { "Department", "Position", "Name" }); - customDataTree.LoadConfig(config); - - List employees = new List - { - new Employee(" ", "", " "), - new Employee(" ", "", " "), - new Employee(" ", "", " "), - new Employee(" ", "", "IT "), - new Employee(" ", "", " "), - }; - - foreach (var employee in employees) - { - customDataTree.AddObject(employee); - } - } - - private void addInListboxItemButton_Click(object sender, EventArgs e) - { - string value = listboxItemValuetextBox.Text; - if (customCheckedListBox.Items.Contains(value)) customCheckedListBox.SelectedElement = value; - else customCheckedListBox.AddItem(value); - } - - private void clearListboxButton_Click(object sender, EventArgs e) - { - customCheckedListBox.Clear(); - } - - private void getSelectedItemButton_Click(object sender, EventArgs e) - { - string value = customCheckedListBox.SelectedElement; - - if (value == string.Empty) selectedItemLabel.Text = "Selected item: ~empty value~"; - else selectedItemLabel.Text = "Selected item: " + value; - } - - private void checkCustomTextBoxButton_Click(object sender, EventArgs e) - { - try - { - errorCustomTextBoxLabel.Text = customTextBox.Value == string.Empty ? "~empty value~" : customTextBox.Value; - } - catch (RangeNotSetException ex) - { - // , . - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Warning); - } - catch (TextLengthOutOfRangeException ex) - { - // , . - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Warning); - } - } - - private void addEmployeeButton_Click(object sender, EventArgs e) - { - if (positionTextBox.Text == null || nameTextBox.Text == null || departamentComboBox.SelectedItem == null) - { - return; - } - customDataTree.AddObject(new(nameTextBox.Text, positionTextBox.Text, departamentComboBox.SelectedItem.ToString())); - customDataTree.Update(); - } - - private void getSelectedTreeItemButton_Click(object sender, EventArgs e) - { - Employee employee = customDataTree.GetSelectedObject(); - if (employee == null) - { - return; - } - positionTextBox.Text = employee.Position; - nameTextBox.Text = employee.Name; - departamentComboBox.SelectedItem = employee.Department; - } - - // PDF WITH IMAGE - private void button1_Click(object sender, EventArgs e) - { - using OpenFileDialog openFileDialog = new OpenFileDialog - { - Multiselect = true, - Filter = "|*.jpg;*.jpeg;*.png;*.bmp" - }; - - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - // - selectedImages.Clear(); - listBoxImages.Items.Clear(); - - // - foreach (string filePath in openFileDialog.FileNames) - { - selectedImages.Add(File.ReadAllBytes(filePath)); - listBoxImages.Items.Add(Path.GetFileName(filePath)); - } - } - } - - private void createPdfButton_Click(object sender, EventArgs e) - { - if (selectedImages.Count == 0) - { - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - // PDF- - var config = new PdfWithImageConfig - { - FilePath = "PdfWithImage.pdf", - Header = " ", - Images = selectedImages - }; - - // PDF - pdfWithImages.CreatePdf(config); - - MessageBox.Show("PDF !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - - // PDF WITH TABLE - private void pdfTableButton_Click(object sender, EventArgs e) - { - PdfWithTableConfig config = new PdfWithTableConfig - { - FileName = "PdfWithTable.pdf", - DocumentTitle = " ", - RowHeights = new List { 1, 1, 1 }, - Headers = new Dictionary> - { - { " ", new List {"", ""} }, - { "", new List() } - }, - PropertiesPerRow = new List { "Name", "Surname", "Age" }, - Data = new List - { - new Human("", "", 30), - new Human("", "", 25), - new Human("", "", 35) - } - }; - - try - { - // PDF - pdfWithTable.CreatePdf(config); - MessageBox.Show("PDF- !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - MessageBox.Show($" PDF: {ex.Message}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - // PDF TO DIAGRAM - private void pdfDiagramButton_Click(object sender, EventArgs e) - { - try - { - pdfWithDiagram.CreateDoc(new PdfWithDiagramConfig - { - FilePath = "PdfWithPieDiagram.pdf", - Header = "", - ChartTitle = " ", - LegendLocation = WinFormsLibrary1.Configs.Diagram.Location.Bottom, - Data = new Dictionary> - { - { - "Product A", new List<(string Name, double Value)> - { - ("1111", 30.0), - ("2", 20.0), - ("3", 50.0) - } - } - } - }); - MessageBox.Show("PDF !", ""); - } - catch (Exception ex) - { - MessageBox.Show($": {ex.Message}"); - } - } - } -} diff --git a/WinFormsApp1/Program.cs b/WinFormsApp1/Program.cs deleted file mode 100644 index 93decce..0000000 --- a/WinFormsApp1/Program.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace WinFormsApp1 -{ - internal static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1.csproj b/WinFormsApp1/WinFormsApp1.csproj deleted file mode 100644 index aa5e600..0000000 --- a/WinFormsApp1/WinFormsApp1.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - WinExe - net6.0-windows - enable - true - enable - - - - - - - \ No newline at end of file diff --git a/WinFormsLibrary1.sln b/WinFormsLibrary1.sln deleted file mode 100644 index 57bac88..0000000 --- a/WinFormsLibrary1.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34525.116 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsLibrary1", "WinFormsLibrary1\WinFormsLibrary1.csproj", "{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{B0B10C32-032F-49CB-9ED6-70A0DEE05587}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Release|Any CPU.Build.0 = Release|Any CPU - {B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BC3841E0-E2BA-4201-9D85-36D4B65C22E5} - EndGlobalSection -EndGlobal diff --git a/WinFormsLibrary1/Configs/Diagram/Location.cs b/WinFormsLibrary1/Configs/Diagram/Location.cs deleted file mode 100644 index 6fe3f01..0000000 --- a/WinFormsLibrary1/Configs/Diagram/Location.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Configs.Diagram -{ - public enum Location - { - Left, - Right, - Top, - Bottom - } -} diff --git a/WinFormsLibrary1/Configs/Diagram/PdfWithDiagramConfig.cs b/WinFormsLibrary1/Configs/Diagram/PdfWithDiagramConfig.cs deleted file mode 100644 index 29b7a52..0000000 --- a/WinFormsLibrary1/Configs/Diagram/PdfWithDiagramConfig.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Configs.Diagram -{ - public class PdfWithDiagramConfig - { - public string FilePath { get; set; } - public string Header { get; set; } - public string ChartTitle { get; set; } - public Location LegendLocation { get; set; } - public Dictionary> Data { get; set; } - - public void CheckFields() - { - if (string.IsNullOrEmpty(FilePath)) - throw new ArgumentNullException(nameof(FilePath), "File path cannot be null or empty."); - if (string.IsNullOrEmpty(Header)) - throw new ArgumentNullException(nameof(Header), "Header cannot be null or empty."); - if (Data == null || !Data.Any()) - throw new ArgumentNullException(nameof(Data), "Data cannot be null or empty."); - } - } - -} diff --git a/WinFormsLibrary1/Configs/Image/PdfWithImageConfig.cs b/WinFormsLibrary1/Configs/Image/PdfWithImageConfig.cs deleted file mode 100644 index 735c8fe..0000000 --- a/WinFormsLibrary1/Configs/Image/PdfWithImageConfig.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Configs.Image -{ - public class PdfWithImageConfig - { - public string FilePath { get; set; } - public string Header { get; set; } - public List Images { get; set; } - - public void CheckFields() - { - if (string.IsNullOrWhiteSpace(FilePath) || string.IsNullOrWhiteSpace(Header) || Images == null || Images.Count == 0) - { - throw new ArgumentException("Все поля должны быть заполнены."); - } - } - } -} diff --git a/WinFormsLibrary1/Configs/Table/PdfWithTableConfig.cs b/WinFormsLibrary1/Configs/Table/PdfWithTableConfig.cs deleted file mode 100644 index 737d5ba..0000000 --- a/WinFormsLibrary1/Configs/Table/PdfWithTableConfig.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Configs.Table -{ - public class PdfWithTableConfig - { - /// - /// Имя файла для сохранения PDF-документа. - /// - public string FileName { get; set; } - - /// - /// Заголовок документа PDF. - /// - public string DocumentTitle { get; set; } - - /// - /// Список высот строк таблицы в виде массива двойных значений. - /// - public List RowHeights { get; set; } - - /// - /// Заголовки таблицы, где ключ - имя обобщающего столбца, а значение - список заголовков для соответствующего столбца. - /// ВАЖНО: если строка не имеет обобщающего столбца, то заголовком будет ключ (список будет пустой) - /// - /// var Headers = new Dictionary - /// { - /// {"Личные данные", new List("Имя", "Фамилия")}, - /// {"Возраст", new List()}, - /// } - /// - /// ------------------------------ - /// | | Имя | - /// | Личные данные |------------| - /// | | Фамилия | - /// |----------------------------| - /// | Возраст | - /// ------------------------------ - /// - /// - public Dictionary> Headers { get; set; } - - /// - /// Список названий свойств, соответствующих данным, которые будут отображаться в строках таблицы. - /// - public List PropertiesPerRow { get; set; } - - /// - /// Данные для заполнения таблицы, представляющие собой список объектов типа T. - /// - public List Data { get; set; } - - /// - /// Проверяет корректность полей конфигурации. - /// Вызывает исключение, если какое-либо поле не соответствует требованиям. - /// - public void CheckFields() - { - if (string.IsNullOrWhiteSpace(FileName)) - throw new ArgumentException("Имя файла не может быть пустым.", nameof(FileName)); - - if (string.IsNullOrWhiteSpace(DocumentTitle)) - throw new ArgumentException("Название документа не может быть пустым.", nameof(DocumentTitle)); - - if (Headers == null || Headers.Count == 0) - throw new ArgumentException("Заголовки для шапки не могут быть пустыми.", nameof(Headers)); - - if (Data == null || Data.Count == 0) - throw new ArgumentException("Данные для таблицы не могут быть пустыми.", nameof(Data)); - - if (RowHeights == null || RowHeights.Count == 0) - throw new ArgumentException("Высоты строк не могут быть пустыми.", nameof(RowHeights)); - - if (PropertiesPerRow.Any(string.IsNullOrWhiteSpace)) - throw new ArgumentException("Список названий свойств не может содержать пустые строки.", nameof(PropertiesPerRow)); - - if (RowHeights.Count != PropertiesPerRow.Count) - throw new ArgumentException("Количество высот строк должно соответствовать количеству названий свойств.", nameof(RowHeights)); - - if (Data.Count != PropertiesPerRow.Count) - throw new ArgumentException("Количество данных должно соответствовать количеству названий свойств.", nameof(Data)); - } - } -} diff --git a/WinFormsLibrary1/CustomCheckedListBox.Designer.cs b/WinFormsLibrary1/CustomCheckedListBox.Designer.cs deleted file mode 100644 index b94667b..0000000 --- a/WinFormsLibrary1/CustomCheckedListBox.Designer.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class CustomCheckedListBox - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - checkedListBox = new CheckedListBox(); - SuspendLayout(); - // - // checkedListBox - // - checkedListBox.Dock = DockStyle.Fill; - checkedListBox.FormattingEnabled = true; - checkedListBox.Location = new Point(0, 0); - checkedListBox.Name = "checkedListBox"; - checkedListBox.Size = new Size(281, 235); - checkedListBox.TabIndex = 0; - checkedListBox.ItemCheck += checkedListBox_ItemCheck; - checkedListBox.SelectedIndexChanged += checkedListBox_SelectedIndexChanged; - // - // CustomCheckedListBox - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - Controls.Add(checkedListBox); - Name = "CustomCheckedListBox"; - Size = new Size(281, 235); - ResumeLayout(false); - } - - #endregion - - private CheckedListBox checkedListBox; - } -} diff --git a/WinFormsLibrary1/CustomCheckedListBox.cs b/WinFormsLibrary1/CustomCheckedListBox.cs deleted file mode 100644 index 023ae3c..0000000 --- a/WinFormsLibrary1/CustomCheckedListBox.cs +++ /dev/null @@ -1,80 +0,0 @@ -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 WinFormsLibrary1 -{ - public partial class CustomCheckedListBox : UserControl - { - public CheckedListBox.ObjectCollection Items => checkedListBox.Items; - private EventHandler _changeEvent; - public CustomCheckedListBox() - { - InitializeComponent(); - } - - public void Clear() - { - checkedListBox.Items.Clear(); - } - - public string SelectedElement - { - get - { - if (checkedListBox.SelectedIndex > -1 && checkedListBox.GetItemChecked(checkedListBox.SelectedIndex)) - { - return checkedListBox.SelectedItem.ToString(); - } - - return string.Empty; - } - set - { - if (checkedListBox.Items.Contains(value)) - { - checkedListBox.SelectedItem = value; - checkedListBox.SetItemChecked(checkedListBox.Items.IndexOf(value), true); - } - } - } - private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e) - { - if (e.NewValue == CheckState.Checked && checkedListBox.CheckedItems.Count > 0) - { - checkedListBox.ItemCheck -= checkedListBox_ItemCheck; - checkedListBox.SetItemChecked(checkedListBox.CheckedIndices[0], value: false); - checkedListBox.ItemCheck += checkedListBox_ItemCheck; - } - } - public void AddItem(string item) - { - if (item == string.Empty) return; - checkedListBox.Items.Add(item); - } - private void checkedListBox_SelectedIndexChanged(object sender, EventArgs e) - { - _changeEvent?.Invoke(sender, e); - } - - // Cобытие, вызываемое при смене значения - public event EventHandler ChangeEvent - { - add - { - _changeEvent += value; - } - remove - { - _changeEvent -= value; - } - - } - } -} diff --git a/WinFormsLibrary1/CustomDataTree.Designer.cs b/WinFormsLibrary1/CustomDataTree.Designer.cs deleted file mode 100644 index f66d5a8..0000000 --- a/WinFormsLibrary1/CustomDataTree.Designer.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class CustomDataTree - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - treeView = new TreeView(); - SuspendLayout(); - // - // treeView - // - treeView.Dock = DockStyle.Fill; - treeView.Location = new Point(0, 0); - treeView.Name = "treeView"; - treeView.Size = new Size(150, 150); - treeView.TabIndex = 0; - // - // CustomDataTree - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - Controls.Add(treeView); - Name = "CustomDataTree"; - ResumeLayout(false); - } - - #endregion - - private TreeView treeView; - } -} diff --git a/WinFormsLibrary1/CustomDataTree.cs b/WinFormsLibrary1/CustomDataTree.cs deleted file mode 100644 index d19cb4c..0000000 --- a/WinFormsLibrary1/CustomDataTree.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace WinFormsLibrary1 -{ - public partial class CustomDataTree : UserControl - { - // Публичное свойство для установки и получения иерархии - protected DataTreeNodeConfig Levels { get; set; } - public CustomDataTree() - { - InitializeComponent(); - } - - public void Clear() - { - treeView.Nodes.Clear(); - } - - public void LoadConfig(DataTreeNodeConfig levels) - { - if (levels != null) - { - Levels = levels; - } - } - - // Публичный метод для получения выбранной записи (для конечного элемента дерева) - public T GetSelectedObject() where T : class, new() - { - if (treeView.SelectedNode == null || Levels == null || treeView.SelectedNode.Nodes.Count > 0) - { - // сделать ошибки - return null; - } - - T val = new T(); - - TreeNode currentNode = treeView.SelectedNode; - int levelIndex = Levels.NodeNames.Count - 1; - - while (currentNode != null && levelIndex >= 0) - { - // имя свойства - string nodeName = Levels.NodeNames[levelIndex]; - string value = currentNode.Text; - - // Получаем свойство по имени и устанавливаем его значение - PropertyInfo property = val.GetType().GetProperty(nodeName); - property?.SetValue(val, Convert.ChangeType(value, property.PropertyType)); - - // Переходим к родительскому узлу - currentNode = currentNode.Parent; - levelIndex--; - } - - // Если не прошли все уровни - if (levelIndex >= 0) - { - return null; - } - - return val; - } - - - // Метод для добавления объекта в TreeView - public void AddObject(T element) - { - if (Levels == null || element == null) - { - return; - } - - TreeNodeCollection currentNodeCollection = treeView.Nodes; - - for (int i = 0; i < Levels.NodeNames.Count; i++) - { - string nodeName = Levels.NodeNames[i]; - PropertyInfo property = element.GetType().GetProperty(nodeName); - if (property == null) continue; - - string nodeValue = property.GetValue(element, null)?.ToString() ?? nodeName; - - // Проверяем, существует ли уже ветка с таким именем - TreeNode existingNode = null; - foreach (TreeNode node in currentNodeCollection) - { - if (node.Text == nodeValue) - { - existingNode = node; - break; - } - } - - // Если ветка не существует - if (existingNode == null) - { - existingNode = currentNodeCollection.Add(nodeValue); - } - - currentNodeCollection = existingNode.Nodes; - } - } - } -} diff --git a/WinFormsLibrary1/CustomTextBox.Designer.cs b/WinFormsLibrary1/CustomTextBox.Designer.cs deleted file mode 100644 index 59f9763..0000000 --- a/WinFormsLibrary1/CustomTextBox.Designer.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class CustomTextBox - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - textBox = new TextBox(); - SuspendLayout(); - // - // textBox - // - textBox.Dock = DockStyle.Fill; - textBox.Location = new Point(0, 0); - textBox.Name = "textBox"; - textBox.Size = new Size(93, 27); - textBox.TabIndex = 0; - textBox.TextChanged += textBox1_TextChanged; - // - // CustomTextBox - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - Controls.Add(textBox); - Name = "CustomTextBox"; - Size = new Size(93, 21); - ResumeLayout(false); - PerformLayout(); - } - - #endregion - - private TextBox textBox; - } -} diff --git a/WinFormsLibrary1/CustomTextBox.cs b/WinFormsLibrary1/CustomTextBox.cs deleted file mode 100644 index 34fea2c..0000000 --- a/WinFormsLibrary1/CustomTextBox.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using WinFormsLibrary1.Errors; -using static System.Windows.Forms.VisualStyles.VisualStyleElement; - -namespace WinFormsLibrary1 -{ - public partial class CustomTextBox : UserControl - { - public int? MinLength { get; set; } = null; - public int? MaxLength { get; set; } = null; - - public event EventHandler ValueChanged; - - public string Value - { - get - { - if (MinLength == null || MaxLength == null) - throw new RangeNotSetException(); - - if (textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength) - throw new TextLengthOutOfRangeException(MinLength ?? -1, MaxLength ?? -1); - - return textBox.Text; - } - set - { - if (MinLength == null || MaxLength == null - || textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength) - return; - - textBox.Text = value; - } - } - - public string CheckValue(string v) - { - if (MinLength == null || MaxLength == null) - throw new RangeNotSetException(); - - if (v.Length < MinLength || v.Length > MaxLength) - throw new TextLengthOutOfRangeException(MinLength ?? -1, MaxLength ?? -1); - - return v; - - } - - public CustomTextBox() - { - InitializeComponent(); - } - - private void textBox1_TextChanged(object sender, EventArgs e) - { - ValueChanged?.Invoke(this, EventArgs.Empty); - } - } -} diff --git a/WinFormsLibrary1/CustomTextBox.resx b/WinFormsLibrary1/CustomTextBox.resx deleted file mode 100644 index af32865..0000000 --- a/WinFormsLibrary1/CustomTextBox.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/WinFormsLibrary1/DataTreeNodeConfig.cs b/WinFormsLibrary1/DataTreeNodeConfig.cs deleted file mode 100644 index 11302e9..0000000 --- a/WinFormsLibrary1/DataTreeNodeConfig.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1 -{ - public class DataTreeNodeConfig - { - public List NodeNames { get; set; } = new List(); - - public DataTreeNodeConfig(List nodeNames, bool alwaysCreateNewBranch = false) - { - NodeNames = nodeNames; - } - } -} diff --git a/WinFormsLibrary1/Errors/RangeNotSetException.cs b/WinFormsLibrary1/Errors/RangeNotSetException.cs deleted file mode 100644 index 5c04e7b..0000000 --- a/WinFormsLibrary1/Errors/RangeNotSetException.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Errors -{ - public class RangeNotSetException : Exception - { - public RangeNotSetException() : base("Диапазон длины текста не задан.") { } - } -} diff --git a/WinFormsLibrary1/Errors/TextLengthOutOfRangeException.cs b/WinFormsLibrary1/Errors/TextLengthOutOfRangeException.cs deleted file mode 100644 index 3664594..0000000 --- a/WinFormsLibrary1/Errors/TextLengthOutOfRangeException.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Errors -{ - public class TextLengthOutOfRangeException : Exception - { - public int MinLength { get; } - public int MaxLength { get; } - - public TextLengthOutOfRangeException(int minLength, int maxLength) : base($"Длина текста не входит в заданный диапазон [{minLength}, {maxLength}].") - { - MinLength = minLength; - MaxLength = maxLength; - } - } -} diff --git a/WinFormsLibrary1/Models/Employee.cs b/WinFormsLibrary1/Models/Employee.cs deleted file mode 100644 index 1365813..0000000 --- a/WinFormsLibrary1/Models/Employee.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Models -{ - public class Employee - { - public string Name { get; set; } - public string Position { get; set; } - public string Department { get; set; } - public Employee() { } - public Employee(string name, string position, string department) - { - Name = name; - Position = position; - Department = department; - } - } -} diff --git a/WinFormsLibrary1/Models/Human.cs b/WinFormsLibrary1/Models/Human.cs deleted file mode 100644 index 821f554..0000000 --- a/WinFormsLibrary1/Models/Human.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Models -{ - public class Human - { - public string Name { get; set; } - public string Surname { get; set; } - public int Age { get; set; } - public Human() { } - public Human(string name, string surname, int age) - { - Name = name; - Surname = surname; - Age = age; - } - } -} diff --git a/WinFormsLibrary1/PdfWithDiagram.Designer.cs b/WinFormsLibrary1/PdfWithDiagram.Designer.cs deleted file mode 100644 index 726d2d0..0000000 --- a/WinFormsLibrary1/PdfWithDiagram.Designer.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class PdfWithDiagram - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - } - - #endregion - } -} diff --git a/WinFormsLibrary1/PdfWithDiagram.cs b/WinFormsLibrary1/PdfWithDiagram.cs deleted file mode 100644 index 7568bfd..0000000 --- a/WinFormsLibrary1/PdfWithDiagram.cs +++ /dev/null @@ -1,117 +0,0 @@ -using MigraDoc.DocumentObjectModel.Shapes; -using MigraDoc.DocumentObjectModel; -using MigraDoc.Rendering; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using MigraDoc.DocumentObjectModel.Shapes.Charts; -using WinFormsLibrary1.Configs.Diagram; - -namespace WinFormsLibrary1 -{ - public partial class PdfWithDiagram : Component - { - public PdfWithDiagram() - { - InitializeComponent(); - } - - public PdfWithDiagram(IContainer container) - { - container.Add(this); - - InitializeComponent(); - } - - private Document _document; - private Chart _chart; - - private Document Document - { - get - { - if (_document == null) - { - _document = new Document(); - } - return _document; - } - } - - public void CreateHeader(string header) - { - var section = Document.AddSection(); - var paragraph = section.AddParagraph(header); - paragraph.Format.Font.Color = Colors.Black; - paragraph.Format.Font.Bold = true; - } - - private void ConfigChart(PdfWithDiagramConfig config) - { - ((Shape)_chart).Width = Unit.FromCentimeter(16.0); - ((Shape)_chart).Height = Unit.FromCentimeter(12.0); - _chart.TopArea.AddParagraph(config.ChartTitle); - _chart.XAxis.MajorTickMark = (TickMarkType)2; - _chart.YAxis.MajorTickMark = (TickMarkType)2; - _chart.YAxis.HasMajorGridlines = true; - _chart.PlotArea.LineFormat.Width = new Unit(1); - _chart.PlotArea.LineFormat.Visible = true; - switch (config.LegendLocation) - { - case Location.Left: - _chart.LeftArea.AddLegend(); - break; - case Location.Right: - _chart.RightArea.AddLegend(); - break; - case Location.Top: - _chart.TopArea.AddLegend(); - break; - case Location.Bottom: - _chart.BottomArea.AddLegend(); - break; - } - } - - public void CreatePieChart(PdfWithDiagramConfig config) - { - _chart = new Chart(ChartType.Pie2D); - foreach (var kvp in config.Data) - { - Series series = _chart.SeriesCollection.AddSeries(); - series.Name = kvp.Key; - series.Add(kvp.Value.Select(x => x.Value).ToArray()); // Используем Value для данных - } - _chart.XValues.AddXSeries().Add(config.Data.First().Value.Select(x => x.Name).ToArray()); // Используем Date для оси X - ConfigChart(config); - } - - public void SaveDoc(string filepath) - { - if (string.IsNullOrEmpty(filepath)) - throw new ArgumentNullException(nameof(filepath), "File path cannot be null or empty."); - if (_document == null) - throw new ArgumentNullException(nameof(_document), "Document is not created."); - if (_chart != null) - _document.LastSection.Add(_chart); - PdfDocumentRenderer documentRenderer = new PdfDocumentRenderer(true) - { - Document = _document - }; - documentRenderer.RenderDocument(); - documentRenderer.PdfDocument.Save(filepath); - } - - public void CreateDoc(PdfWithDiagramConfig config) - { - config.CheckFields(); - CreateHeader(config.Header); - CreatePieChart(config); - SaveDoc(config.FilePath); - } - } -} diff --git a/WinFormsLibrary1/PdfWithImages.Designer.cs b/WinFormsLibrary1/PdfWithImages.Designer.cs deleted file mode 100644 index ff21e7c..0000000 --- a/WinFormsLibrary1/PdfWithImages.Designer.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class PdfWithImages - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - } - - #endregion - } -} diff --git a/WinFormsLibrary1/PdfWithImages.cs b/WinFormsLibrary1/PdfWithImages.cs deleted file mode 100644 index 3dcad9a..0000000 --- a/WinFormsLibrary1/PdfWithImages.cs +++ /dev/null @@ -1,177 +0,0 @@ -using MigraDoc.DocumentObjectModel; -using MigraDoc.Rendering; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WinFormsLibrary1.Configs.Image; - -namespace WinFormsLibrary1 -{ - public partial class PdfWithImages : Component - { - private Document _document = null; - - private Section _section = null; - - private List _images = null; - - private Document Document - { - get - { - if (_document == null) - { - _document = new Document(); - } - - return _document; - } - } - - private Section Section - { - get - { - if (_section == null) - { - _section = Document.AddSection(); - } - - return _section; - } - } - - private List Images - { - get - { - if (_images == null) - { - _images = new List(); - } - - return _images; - } - } - public PdfWithImages() - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - InitializeComponent(); - } - - public PdfWithImages(IContainer container) - { - container.Add(this); - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - InitializeComponent(); - } - public void CreatePdf(PdfWithImageConfig config) - { - config.CheckFields(); - CreateHeader(config.Header); - foreach (var image in config.Images) - { - CreateImage(image); - } - - SavePdf(config.FilePath); - } - - public void CreateHeader(string header) - { - var paragraph = Section.AddParagraph(header); - paragraph.Format.Font.Name = "Arial"; - paragraph.Format.Font.Bold = true; - paragraph.Format.Font.Size = 20; - paragraph.Format.SpaceAfter = 10; - } - - public void SavePdf(string filepath) - { - if (string.IsNullOrWhiteSpace(filepath)) - { - throw new ArgumentNullException("Имя файла не задано"); - } - - if (_document == null || _section == null) - { - throw new ArgumentNullException("Документ не сформирован, сохранять нечего"); - } - - var pdfRenderer = new PdfDocumentRenderer(true) - { - Document = _document, - }; - pdfRenderer.RenderDocument(); - pdfRenderer.Save(filepath); - } - - public void CreateImage(byte[] image) - { - if (image == null || image.Length == 0) - { - throw new ArgumentNullException("Картинка не загружена"); - } - - Images.Add(image); - - var imageFileName = Path.GetTempFileName(); - File.WriteAllBytes(imageFileName, image); - - var img = Section.AddImage(imageFileName); - img.Width = Unit.FromCentimeter(15); // Можно настроить ширину изображения - img.LockAspectRatio = true; - Section.AddParagraph(); - - - - - /*if (image == null || image.Length == 0) - { - throw new ArgumentNullException("Картинка не загружена"); - } - - Images.Add(image); - - // Создаём временный файл - var imageFileName = Path.GetTempFileName(); - File.WriteAllBytes(imageFileName, image); - - // Открываем изображение и проверяем его ориентацию - using (var img = System.Drawing.Image.FromFile(imageFileName)) - { - // Проверяем ориентацию и вращаем, если необходимо - if (Array.IndexOf(img.PropertyIdList, 274) > -1) - { - var orientation = (int)img.GetPropertyItem(274).Value[0]; - switch (orientation) - { - case 3: // Переворот на 180 градусов - img.RotateFlip(RotateFlipType.Rotate180FlipNone); - break; - case 6: // Поворот на 90 градусов вправо - img.RotateFlip(RotateFlipType.Rotate90FlipNone); - break; - case 8: // Поворот на 90 градусов влево - img.RotateFlip(RotateFlipType.Rotate270FlipNone); - break; - } - } - // Сохраняем отредактированное изображение - img.Save(imageFileName); - } - - // Вставляем изображение в PDF - var pdfImage = Section.AddImage(imageFileName); - pdfImage.Width = Unit.FromCentimeter(15); // Можно настроить ширину изображения - pdfImage.LockAspectRatio = true; - - // Добавляем пустую строку после изображения - Section.AddParagraph();*/ - } - } -} diff --git a/WinFormsLibrary1/PdfWithTable.Designer.cs b/WinFormsLibrary1/PdfWithTable.Designer.cs deleted file mode 100644 index fdf30a3..0000000 --- a/WinFormsLibrary1/PdfWithTable.Designer.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class PdfWithTable - { - /// - /// Обязательная переменная конструктора. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Освободить все используемые ресурсы. - /// - /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Код, автоматически созданный конструктором компонентов - - /// - /// Требуемый метод для поддержки конструктора — не изменяйте - /// содержимое этого метода с помощью редактора кода. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - } - - #endregion - } -} diff --git a/WinFormsLibrary1/PdfWithTable.cs b/WinFormsLibrary1/PdfWithTable.cs deleted file mode 100644 index ce8e4dc..0000000 --- a/WinFormsLibrary1/PdfWithTable.cs +++ /dev/null @@ -1,110 +0,0 @@ -using MigraDoc.DocumentObjectModel; -using MigraDoc.DocumentObjectModel.IO; -using MigraDoc.DocumentObjectModel.Tables; -using MigraDoc.Rendering; -using PdfSharp.Pdf; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Text; -using WinFormsLibrary1.Configs.Table; - -namespace WinFormsLibrary1 -{ - public partial class PdfWithTable : Component - { - public void CreatePdf(PdfWithTableConfig config) - { - config.CheckFields(); - - // Создание документа - var document = new Document(); - var section = document.AddSection(); - - // Установка заголовка - var titleParagraph = section.AddParagraph(config.DocumentTitle); - titleParagraph.Format.Alignment = ParagraphAlignment.Center; - titleParagraph.Format.Font.Size = 16; - titleParagraph.Format.Font.Bold = true; - titleParagraph.Format.SpaceAfter = 20; - - // Создание таблицы - var table = section.AddTable(); - table.Borders.Width = 0.75; - - // Создание столбцов - for (int i = 0; i < config.Data.Count + 2; i++) - { - var column = table.AddColumn(Unit.FromCentimeter(3)); // Ширину можно настроить - column.Format.Alignment = ParagraphAlignment.Center; - } - - // Создание заголовков - for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++) - { - var row = table.AddRow(); - row.Height = Unit.FromCentimeter(config.RowHeights[rowIndex]); // Высота строки - - foreach (Cell cell in row.Cells) - { - cell.VerticalAlignment = VerticalAlignment.Center; - cell.Format.Alignment = ParagraphAlignment.Center; - } - } - - int rowNum = 0; - foreach (var kvp in config.Headers) - { - string key = kvp.Key; - List values = kvp.Value; - - if (values.Count == 0) - { - table.Rows[rowNum].Cells[0].AddParagraph(key); - table.Rows[rowNum].Cells[0].MergeRight = 1; - rowNum++; - } - - else - { - table.Rows[rowNum].Cells[0].AddParagraph(key); - table.Rows[rowNum].Cells[0].MergeDown = values.Count - 1; - - foreach (var value in values) - { - table.Rows[rowNum].Cells[1].AddParagraph(value); - rowNum++; - } - } - } - - - for (int colIndex = 0; colIndex < config.Data.Count; colIndex++) - { - for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++) - { - Type type = typeof(T); - PropertyInfo property = type.GetProperty(config.PropertiesPerRow[rowIndex]); - - if (property == null) - { - throw new ArgumentException($"Property with name {config.PropertiesPerRow[rowIndex]} doesn't exist in class {type.Name}"); - } - - table.Rows[rowIndex].Cells[colIndex + 2].AddParagraph(property.GetValue(config.Data[colIndex]).ToString()); - } - } - - - // Рендеринг документа в PDF - var pdfRenderer = new PdfDocumentRenderer(true) - { - Document = document - }; - pdfRenderer.RenderDocument(); - pdfRenderer.PdfDocument.Save(config.FileName); - } - } -} \ No newline at end of file diff --git a/WinFormsLibrary1/WinFormsLibrary1.csproj b/WinFormsLibrary1/WinFormsLibrary1.csproj deleted file mode 100644 index abefb8b..0000000 --- a/WinFormsLibrary1/WinFormsLibrary1.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - net6.0-windows - enable - true - enable - True - - - - - - -