From 45714e0b95882e2690200c8d58b5d4d3fe87fbf1 Mon Sep 17 00:00:00 2001 From: danilafilippov7299 Date: Thu, 7 Nov 2024 00:39:46 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BindingModels/OrderBindingModel.cs | 18 ++ .../BindingModels/ProductBindingModel.cs | 15 ++ .../OnlineShopContracts.csproj | 14 ++ .../ViewModels/OrderViewModel.cs | 27 +++ .../ViewModels/ProductViewModel.cs | 18 ++ .../FormMain.Designer.cs} | 15 +- WinFormsApp1/OnlineShopForms/FormMain.cs | 20 ++ WinFormsApp1/OnlineShopForms/FormMain.resx | 120 ++++++++++ .../OnlineShopForms/FormStatuses.Designer.cs | 65 +++++ WinFormsApp1/OnlineShopForms/FormStatuses.cs | 119 ++++++++++ .../OnlineShopForms/FormStatuses.resx | 120 ++++++++++ .../OnlineShopForms.csproj} | 3 +- .../20241105211148_Initial2.Designer.cs | 58 +++++ .../Migrations/20241105211148_Initial2.cs | 38 +++ .../20241105224042_Initial3.Designer.cs | 75 ++++++ .../Migrations/20241105224042_Initial3.cs | 35 +++ .../OnlineShopDatabaseModelSnapshot.cs | 72 ++++++ .../OnlineStoreDatabase/Models/Order.cs | 63 +++++ .../OnlineStoreDatabase/Models/Product.cs | 48 ++++ .../OnlineStoreDatabase/OnlineShopDatabase.cs | 17 ++ .../OnlineStoreDatabase.csproj | 25 ++ .../Storages/OrderStorage.cs | 133 +++++++++++ .../Storages/ProductStorage.cs | 133 +++++++++++ WinFormsApp1/WinFormsApp1.sln | 30 ++- WinFormsApp1/WinFormsApp1/Create.Designer.cs | 192 +++++++++++++++ WinFormsApp1/WinFormsApp1/Create.cs | 139 +++++++++++ WinFormsApp1/WinFormsApp1/Create.resx | 120 ++++++++++ .../WinFormsApp1/Dictinary.Designer.cs | 73 ++++++ WinFormsApp1/WinFormsApp1/Dictinary.cs | 116 +++++++++ WinFormsApp1/WinFormsApp1/Dictinary.resx | 120 ++++++++++ WinFormsApp1/WinFormsApp1/Form1.Designer.cs | 158 +++++++++---- WinFormsApp1/WinFormsApp1/Form1.cs | 223 +++++++++++++++++- WinFormsApp1/WinFormsApp1/Form1.resx | 73 +++++- WinFormsApp1/WinFormsApp1/Order.cs | 49 ++++ WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj | 13 +- .../CheckedListBoxControl.Designer.cs | 60 ----- .../WinFormsLibrary1/CheckedListBoxControl.cs | 82 ------- .../CheckedListBoxControl.resx | 60 ----- .../WinFormsLibrary1/DataControl.Designer.cs | 57 ----- WinFormsApp1/WinFormsLibrary1/DataControl.cs | 66 ------ .../WinFormsLibrary1/DataControl.resx | 60 ----- .../WinFormsLibrary1/ExcelImages.Designer.cs | 36 --- WinFormsApp1/WinFormsLibrary1/ExcelImages.cs | 80 ------- .../WinFormsLibrary1/ExcelTable.Designer.cs | 36 --- WinFormsApp1/WinFormsLibrary1/ExcelTable.cs | 212 ----------------- .../Exceptions/EmptyValueException.cs | 15 -- .../Exceptions/NotInDateRange.cs | 15 -- WinFormsApp1/WinFormsLibrary1/PieChart.cs | 111 --------- WinFormsApp1/WinFormsLibrary1/TestNode.cs | 29 --- .../TreeViewControl.Designer.cs | 57 ----- .../WinFormsLibrary1/TreeViewControl.cs | 153 ------------ .../WinFormsLibrary1/TreeViewControl.resx | 60 ----- 52 files changed, 2479 insertions(+), 1267 deletions(-) create mode 100644 WinFormsApp1/OnlineShopContracts/BindingModels/OrderBindingModel.cs create mode 100644 WinFormsApp1/OnlineShopContracts/BindingModels/ProductBindingModel.cs create mode 100644 WinFormsApp1/OnlineShopContracts/OnlineShopContracts.csproj create mode 100644 WinFormsApp1/OnlineShopContracts/ViewModels/OrderViewModel.cs create mode 100644 WinFormsApp1/OnlineShopContracts/ViewModels/ProductViewModel.cs rename WinFormsApp1/{WinFormsLibrary1/PieChart.Designer.cs => OnlineShopForms/FormMain.Designer.cs} (68%) create mode 100644 WinFormsApp1/OnlineShopForms/FormMain.cs create mode 100644 WinFormsApp1/OnlineShopForms/FormMain.resx create mode 100644 WinFormsApp1/OnlineShopForms/FormStatuses.Designer.cs create mode 100644 WinFormsApp1/OnlineShopForms/FormStatuses.cs create mode 100644 WinFormsApp1/OnlineShopForms/FormStatuses.resx rename WinFormsApp1/{WinFormsLibrary1/WinFormsLibrary1.csproj => OnlineShopForms/OnlineShopForms.csproj} (71%) create mode 100644 WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.Designer.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.Designer.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Migrations/OnlineShopDatabaseModelSnapshot.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Models/Order.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Models/Product.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/OnlineShopDatabase.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/OnlineStoreDatabase.csproj create mode 100644 WinFormsApp1/OnlineStoreDatabase/Storages/OrderStorage.cs create mode 100644 WinFormsApp1/OnlineStoreDatabase/Storages/ProductStorage.cs create mode 100644 WinFormsApp1/WinFormsApp1/Create.Designer.cs create mode 100644 WinFormsApp1/WinFormsApp1/Create.cs create mode 100644 WinFormsApp1/WinFormsApp1/Create.resx create mode 100644 WinFormsApp1/WinFormsApp1/Dictinary.Designer.cs create mode 100644 WinFormsApp1/WinFormsApp1/Dictinary.cs create mode 100644 WinFormsApp1/WinFormsApp1/Dictinary.resx create mode 100644 WinFormsApp1/WinFormsApp1/Order.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.Designer.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.resx delete mode 100644 WinFormsApp1/WinFormsLibrary1/DataControl.Designer.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/DataControl.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/DataControl.resx delete mode 100644 WinFormsApp1/WinFormsLibrary1/ExcelImages.Designer.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/ExcelImages.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/ExcelTable.Designer.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/ExcelTable.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/Exceptions/EmptyValueException.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/Exceptions/NotInDateRange.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/PieChart.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/TestNode.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/TreeViewControl.Designer.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/TreeViewControl.cs delete mode 100644 WinFormsApp1/WinFormsLibrary1/TreeViewControl.resx diff --git a/WinFormsApp1/OnlineShopContracts/BindingModels/OrderBindingModel.cs b/WinFormsApp1/OnlineShopContracts/BindingModels/OrderBindingModel.cs new file mode 100644 index 0000000..2a1d03d --- /dev/null +++ b/WinFormsApp1/OnlineShopContracts/BindingModels/OrderBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OnlineShopContracts.BindingModels +{ + public class OrderBindingModel + { + public int Id { get; set; } + public string CustomerFIO { get; set; } + public byte[] Photo { get; set; } // Для хранения фото заказа + public string ProductId { get; set; } // Внешний ключ на продукт + public string Email { get; set; } + } +} diff --git a/WinFormsApp1/OnlineShopContracts/BindingModels/ProductBindingModel.cs b/WinFormsApp1/OnlineShopContracts/BindingModels/ProductBindingModel.cs new file mode 100644 index 0000000..f349a30 --- /dev/null +++ b/WinFormsApp1/OnlineShopContracts/BindingModels/ProductBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OnlineShopContracts.BindingModels +{ + public class ProductBindingModel + { + public int Id { get; set; } + public string Name { get; set; } + } +} diff --git a/WinFormsApp1/OnlineShopContracts/OnlineShopContracts.csproj b/WinFormsApp1/OnlineShopContracts/OnlineShopContracts.csproj new file mode 100644 index 0000000..0c81b95 --- /dev/null +++ b/WinFormsApp1/OnlineShopContracts/OnlineShopContracts.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/WinFormsApp1/OnlineShopContracts/ViewModels/OrderViewModel.cs b/WinFormsApp1/OnlineShopContracts/ViewModels/OrderViewModel.cs new file mode 100644 index 0000000..d338cf1 --- /dev/null +++ b/WinFormsApp1/OnlineShopContracts/ViewModels/OrderViewModel.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OnlineShopContracts.ViewModels +{ + public class OrderViewModel + { + [DisplayName("Идентификатор")] + public int? Id { get; set; } + [DisplayName("ФИО заказчика")] + public string CustomerFIO { get; set; } + + //!!!МБ изменить на список строк + [DisplayName("Фото заказа")] + public byte[] Photo { get; set; } + + [DisplayName("Продукт")] + public string ProductId { get; set; } + + [DisplayName("Почта заказчика")] + public string Email { get; set; } + } +} diff --git a/WinFormsApp1/OnlineShopContracts/ViewModels/ProductViewModel.cs b/WinFormsApp1/OnlineShopContracts/ViewModels/ProductViewModel.cs new file mode 100644 index 0000000..5642713 --- /dev/null +++ b/WinFormsApp1/OnlineShopContracts/ViewModels/ProductViewModel.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 OnlineShopContracts.ViewModels +{ + public class ProductViewModel + { + [DisplayName("Идентификатор")] + public int? Id { get; set; } + [DisplayName("Название продукта")] + public string Name { get; set; } + + } +} diff --git a/WinFormsApp1/WinFormsLibrary1/PieChart.Designer.cs b/WinFormsApp1/OnlineShopForms/FormMain.Designer.cs similarity index 68% rename from WinFormsApp1/WinFormsLibrary1/PieChart.Designer.cs rename to WinFormsApp1/OnlineShopForms/FormMain.Designer.cs index 8bfa0ed..578a53c 100644 --- a/WinFormsApp1/WinFormsLibrary1/PieChart.Designer.cs +++ b/WinFormsApp1/OnlineShopForms/FormMain.Designer.cs @@ -1,13 +1,13 @@ -namespace WinFormsLibrary1 +namespace OnlineShopForms { - partial class PieChart + partial class FormMain { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; - /// + /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. @@ -20,7 +20,7 @@ base.Dispose(disposing); } - #region Component Designer generated code + #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -28,9 +28,12 @@ /// private void InitializeComponent() { - components = new System.ComponentModel.Container(); + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "FormMain"; } #endregion } -} +} \ No newline at end of file diff --git a/WinFormsApp1/OnlineShopForms/FormMain.cs b/WinFormsApp1/OnlineShopForms/FormMain.cs new file mode 100644 index 0000000..9b85e09 --- /dev/null +++ b/WinFormsApp1/OnlineShopForms/FormMain.cs @@ -0,0 +1,20 @@ +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 OnlineShopForms +{ + public partial class FormMain : Form + { + public FormMain() + { + InitializeComponent(); + } + } +} diff --git a/WinFormsApp1/OnlineShopForms/FormMain.resx b/WinFormsApp1/OnlineShopForms/FormMain.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/WinFormsApp1/OnlineShopForms/FormMain.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WinFormsApp1/OnlineShopForms/FormStatuses.Designer.cs b/WinFormsApp1/OnlineShopForms/FormStatuses.Designer.cs new file mode 100644 index 0000000..dd1833b --- /dev/null +++ b/WinFormsApp1/OnlineShopForms/FormStatuses.Designer.cs @@ -0,0 +1,65 @@ +namespace OnlineShopForms +{ + partial class FormStatuses + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(250, 450); + dataGridView.TabIndex = 0; + dataGridView.CellEndEdit += dataGridView_CellEndEdit; + dataGridView.KeyDown += dataGridView_KeyDown; + // + // FormStatuses + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(250, 450); + Controls.Add(dataGridView); + Name = "FormStatuses"; + Text = "FormStatuses"; + Load += FormStatuses_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/WinFormsApp1/OnlineShopForms/FormStatuses.cs b/WinFormsApp1/OnlineShopForms/FormStatuses.cs new file mode 100644 index 0000000..d034b81 --- /dev/null +++ b/WinFormsApp1/OnlineShopForms/FormStatuses.cs @@ -0,0 +1,119 @@ +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using OnlineStoreDatabase.Storages; +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 OnlineShopForms +{ + public partial class FormStatuses : Form + { + private readonly StatusStorage _storage; + List list; + + public FormStatuses() + { + InitializeComponent(); + _storage = new StatusStorage(); + } + + private void FormStatuses_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + list = _storage.GetFullList(); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void dataGridView_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyData == Keys.Insert) + { + list.Add(new StatusViewModel()); + dataGridView.DataSource = list; + dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1]; + } + else if (e.KeyData == Keys.Delete) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + try + { + if (!_storage.Delete(new StatusBindingModel() { Id = id })) + { + throw new Exception("Ошибка при удалении"); + } + + dataGridView.Rows.RemoveAt(dataGridView.SelectedRows[0].Index); + + LoadData(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } + + //конец редактирования названия статуса (ячейки) + private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) + { + //то, что введено в ячейке + string statusName = (string)dataGridView.CurrentRow.Cells[1].Value; + + //если в ячейке есть текст (строка непустая) + if (!string.IsNullOrEmpty(statusName)) + { + //если есть id, то надо обновить + if (dataGridView.CurrentRow.Cells[0].Value != null) + { + _storage.Update(new StatusBindingModel() + { + Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue + }); + } + //если нет id, значит надо создать запись + else + { + _storage.Insert(new StatusBindingModel() + { + Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue + }); + } + } + //если строка пустая + else + { + MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } + } +} diff --git a/WinFormsApp1/OnlineShopForms/FormStatuses.resx b/WinFormsApp1/OnlineShopForms/FormStatuses.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/WinFormsApp1/OnlineShopForms/FormStatuses.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WinFormsApp1/WinFormsLibrary1/WinFormsLibrary1.csproj b/WinFormsApp1/OnlineShopForms/OnlineShopForms.csproj similarity index 71% rename from WinFormsApp1/WinFormsLibrary1/WinFormsLibrary1.csproj rename to WinFormsApp1/OnlineShopForms/OnlineShopForms.csproj index 9bcfe82..3af0d37 100644 --- a/WinFormsApp1/WinFormsLibrary1/WinFormsLibrary1.csproj +++ b/WinFormsApp1/OnlineShopForms/OnlineShopForms.csproj @@ -5,11 +5,10 @@ enable true enable - True - + diff --git a/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.Designer.cs b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.Designer.cs new file mode 100644 index 0000000..211d1ef --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.Designer.cs @@ -0,0 +1,58 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OnlineStoreDatabase; + +#nullable disable + +namespace OnlineStoreDatabase.Migrations +{ + [DbContext(typeof(OnlineShopDatabase))] + [Migration("20241105211148_Initial2")] + partial class Initial2 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CustomerFIO") + .IsRequired() + .HasColumnType("text"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Photo") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("ProductId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.cs b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.cs new file mode 100644 index 0000000..2d09f84 --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105211148_Initial2.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OnlineStoreDatabase.Migrations +{ + /// + public partial class Initial2 : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + CustomerFIO = table.Column(type: "text", nullable: false), + Photo = table.Column(type: "bytea", nullable: false), + ProductId = table.Column(type: "text", nullable: false), + Email = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Orders"); + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.Designer.cs b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.Designer.cs new file mode 100644 index 0000000..0570944 --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.Designer.cs @@ -0,0 +1,75 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OnlineStoreDatabase; + +#nullable disable + +namespace OnlineStoreDatabase.Migrations +{ + [DbContext(typeof(OnlineShopDatabase))] + [Migration("20241105224042_Initial3")] + partial class Initial3 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CustomerFIO") + .IsRequired() + .HasColumnType("text"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Photo") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("ProductId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("OnlineStoreDatabase.Models.Product", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.cs b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.cs new file mode 100644 index 0000000..a466049 --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Migrations/20241105224042_Initial3.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OnlineStoreDatabase.Migrations +{ + /// + public partial class Initial3 : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Products", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Products", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Products"); + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Migrations/OnlineShopDatabaseModelSnapshot.cs b/WinFormsApp1/OnlineStoreDatabase/Migrations/OnlineShopDatabaseModelSnapshot.cs new file mode 100644 index 0000000..743ae0a --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Migrations/OnlineShopDatabaseModelSnapshot.cs @@ -0,0 +1,72 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OnlineStoreDatabase; + +#nullable disable + +namespace OnlineStoreDatabase.Migrations +{ + [DbContext(typeof(OnlineShopDatabase))] + partial class OnlineShopDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CustomerFIO") + .IsRequired() + .HasColumnType("text"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("Photo") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("ProductId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("OnlineStoreDatabase.Models.Product", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Models/Order.cs b/WinFormsApp1/OnlineStoreDatabase/Models/Order.cs new file mode 100644 index 0000000..6a6106c --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Models/Order.cs @@ -0,0 +1,63 @@ +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OnlineStoreDatabase.Models +{ + public class Order + { + public int Id { get; set; } + + [Required] + public string CustomerFIO { get; set; } + + [Required] + public byte[] Photo { get; set; } + + [Required] + public string ProductId { get; set; } + + public string Email { get; set; } + + public OrderViewModel GetViewModel => new() + { + Id = Id, + CustomerFIO = CustomerFIO, + Photo = Photo, + ProductId = ProductId, + Email = Email, + }; + public static Order? Create(OrderBindingModel model) + { + if (model == null) + { + return null; + } + + return new Order() + { + Id = model.Id, + CustomerFIO = model.CustomerFIO, + Photo = model.Photo, + ProductId = model.ProductId, + Email = model.Email + }; + } + public void Update(OrderBindingModel model) + { + if (model == null) + { + return; + } + CustomerFIO = model.CustomerFIO; + Photo = model.Photo; + ProductId = model.ProductId; + Email = model.Email; + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Models/Product.cs b/WinFormsApp1/OnlineStoreDatabase/Models/Product.cs new file mode 100644 index 0000000..f2a21fa --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Models/Product.cs @@ -0,0 +1,48 @@ +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OnlineStoreDatabase.Models +{ + public class Product + { + public int Id { get; set; } + + [Required] + public string Name { get; set; } + + + + public ProductViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + }; + public static Product? Create(ProductBindingModel model) + { + if (model == null) + { + return null; + } + + return new Product() + { + Id = model.Id, + Name = model.Name + }; + } + public void Update(ProductBindingModel model) + { + if (model == null) + { + return; + } + Name = model.Name; + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/OnlineShopDatabase.cs b/WinFormsApp1/OnlineStoreDatabase/OnlineShopDatabase.cs new file mode 100644 index 0000000..1dec7eb --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/OnlineShopDatabase.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using OnlineStoreDatabase.Models; + +namespace OnlineStoreDatabase +{ + public class OnlineShopDatabase : DbContext + { + public virtual DbSet Orders { get; set; } + public virtual DbSet Products { get; set; } + protected override void OnConfiguring(DbContextOptionsBuilder OptionsBuilder) + { + + OptionsBuilder.UseNpgsql(@"Host=localhost;Database=postgres;Username=postgres;Password=postgres"); + + } + } +} \ No newline at end of file diff --git a/WinFormsApp1/OnlineStoreDatabase/OnlineStoreDatabase.csproj b/WinFormsApp1/OnlineStoreDatabase/OnlineStoreDatabase.csproj new file mode 100644 index 0000000..14c5e5b --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/OnlineStoreDatabase.csproj @@ -0,0 +1,25 @@ + + + + net6.0 + enable + enable + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/WinFormsApp1/OnlineStoreDatabase/Storages/OrderStorage.cs b/WinFormsApp1/OnlineStoreDatabase/Storages/OrderStorage.cs new file mode 100644 index 0000000..25f44ba --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Storages/OrderStorage.cs @@ -0,0 +1,133 @@ +using Microsoft.EntityFrameworkCore; +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using OnlineStoreDatabase.Models; +using OnlineStoreDatabase; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace OnlineStoreDatabase.Storages +{ + public class OrderStorage + { + public List GetFullList() + { + using var context = new OnlineShopDatabase(); + return context.Orders.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(OrderBindingModel model) + { + using var context = new OnlineShopDatabase(); + //либо поиск по ФИО заказчика + if (!string.IsNullOrEmpty(model.CustomerFIO)) + { + return context.Orders + .Where(x => x.CustomerFIO == model.CustomerFIO) + .Select(x => x.GetViewModel) + .ToList(); + } + /*//либо по статусу заказа + else if (!string.IsNullOrEmpty(model.Status)) + { + return context.Orders + .Where(x => x.Status == model.Status) + .Select(x => x.GetViewModel) + .ToList(); + } + //либо по стоимости + else if (model.Sum.HasValue) + { + return context.Orders + .Where(x => x.Sum == model.Sum) + .Select(x => x.GetViewModel) + .ToList(); + }*/ + return new(); + } + + //получение по id заказа + public OrderViewModel? GetElement(OrderBindingModel model) + { + //if (!model.Id.HasValue) return null; + + using var context = new OnlineShopDatabase(); + return context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } + + public bool Insert(OrderBindingModel model) + { + var newOrder = Order.Create(model); + + if (newOrder == null) + { + return false; + } + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + context.Orders.Add(newOrder); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch (Exception ex) + { + transaction.Rollback(); + return false; + throw; + } + } + + public bool Update(OrderBindingModel model) + { + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + throw new Exception("Заказ не найден"); + } + order.Update(model); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch + { + transaction.Rollback(); + return false; + } + } + + public bool Delete(OrderBindingModel model) + { + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (order == null) + { + throw new Exception("Заказ не найден"); + } + context.Orders.Remove(order); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch (Exception e) + { + transaction.Rollback(); + return false; + } + } + } +} diff --git a/WinFormsApp1/OnlineStoreDatabase/Storages/ProductStorage.cs b/WinFormsApp1/OnlineStoreDatabase/Storages/ProductStorage.cs new file mode 100644 index 0000000..89cd4fa --- /dev/null +++ b/WinFormsApp1/OnlineStoreDatabase/Storages/ProductStorage.cs @@ -0,0 +1,133 @@ +using Microsoft.EntityFrameworkCore; +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using OnlineStoreDatabase.Models; +using OnlineStoreDatabase; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace OnlineStoreDatabase.Storages +{ + public class ProductStorage + { + public List GetFullList() + { + using var context = new OnlineShopDatabase(); + return context.Products.Select(x => x.GetViewModel).ToList().OrderBy(x => x.Id).ToList(); + } + + public List GetFilteredList(ProductBindingModel model) + { + using var context = new OnlineShopDatabase(); + //либо поиск по ФИО заказчика + /*if (!string.IsNullOrEmpty(model.Name)) + { + return context.Products + .Where(x => x.Name == model.Name) + .Select(x => x.GetViewModel) + .ToList(); + }*/ + /*//либо по статусу заказа + else if (!string.IsNullOrEmpty(model.Status)) + { + return context.Products + .Where(x => x.Status == model.Status) + .Select(x => x.GetViewModel) + .ToList(); + }*/ + //либо по стоимости + if (model.Id != null) + { + return context.Products + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + //получение по id заказа + public ProductViewModel? GetElement(ProductBindingModel model) + { + //if (!model.Id.HasValue) return null; + + using var context = new OnlineShopDatabase(); + return context.Products.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } + + public bool Insert(ProductBindingModel model) + { + var newProduct = Product.Create(model); + + if (newProduct == null) + { + return false; + } + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + context.Products.Add(newProduct); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch (Exception ex) + { + transaction.Rollback(); + return false; + throw; + } + } + + public bool Update(ProductBindingModel model) + { + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var Product = context.Products.FirstOrDefault(x => x.Id == model.Id); + if (Product == null) + { + throw new Exception("Заказ не найден"); + } + Product.Update(model); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch + { + transaction.Rollback(); + return false; + } + } + + public bool Delete(ProductBindingModel model) + { + using var context = new OnlineShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id); + if (Product == null) + { + throw new Exception("Заказ не найден"); + } + context.Products.Remove(Product); + context.SaveChanges(); + transaction.Commit(); + return true; + } + catch (Exception e) + { + transaction.Rollback(); + return false; + } + } + } +} diff --git a/WinFormsApp1/WinFormsApp1.sln b/WinFormsApp1/WinFormsApp1.sln index 985dd9d..41d4829 100644 --- a/WinFormsApp1/WinFormsApp1.sln +++ b/WinFormsApp1/WinFormsApp1.sln @@ -1,11 +1,13 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 -VisualStudioVersion = 17.1.32210.238 +VisualStudioVersion = 17.11.35312.102 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{511958B8-3EDB-4F7E-9172-173515683273}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{A8183C87-10C0-41E3-B444-A79BF2B14F1D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsLibrary1", "WinFormsLibrary1\WinFormsLibrary1.csproj", "{951999A1-5DDE-47DD-A205-BAD106A268AB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlineStoreDatabase", "OnlineStoreDatabase\OnlineStoreDatabase.csproj", "{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlineShopContracts", "OnlineShopContracts\OnlineShopContracts.csproj", "{79C13F67-853B-441F-9284-5F683172B252}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -13,19 +15,23 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {511958B8-3EDB-4F7E-9172-173515683273}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {511958B8-3EDB-4F7E-9172-173515683273}.Debug|Any CPU.Build.0 = Debug|Any CPU - {511958B8-3EDB-4F7E-9172-173515683273}.Release|Any CPU.ActiveCfg = Release|Any CPU - {511958B8-3EDB-4F7E-9172-173515683273}.Release|Any CPU.Build.0 = Release|Any CPU - {951999A1-5DDE-47DD-A205-BAD106A268AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {951999A1-5DDE-47DD-A205-BAD106A268AB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {951999A1-5DDE-47DD-A205-BAD106A268AB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {951999A1-5DDE-47DD-A205-BAD106A268AB}.Release|Any CPU.Build.0 = Release|Any CPU + {A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Release|Any CPU.Build.0 = Release|Any CPU + {020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Release|Any CPU.Build.0 = Release|Any CPU + {79C13F67-853B-441F-9284-5F683172B252}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {79C13F67-853B-441F-9284-5F683172B252}.Debug|Any CPU.Build.0 = Debug|Any CPU + {79C13F67-853B-441F-9284-5F683172B252}.Release|Any CPU.ActiveCfg = Release|Any CPU + {79C13F67-853B-441F-9284-5F683172B252}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B32788A5-2A20-48CA-95B2-C703D4313D50} + SolutionGuid = {D0F4C3C4-038E-467D-8374-89DB6185E5B7} EndGlobalSection EndGlobal diff --git a/WinFormsApp1/WinFormsApp1/Create.Designer.cs b/WinFormsApp1/WinFormsApp1/Create.Designer.cs new file mode 100644 index 0000000..352c84a --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Create.Designer.cs @@ -0,0 +1,192 @@ +namespace WinFormsApp1 +{ + partial class Create + { + /// + /// 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() + { + textBox1 = new TextBox(); + mailTextBox1 = new Labs.MailTextBox(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + tableLayoutPanel1 = new TableLayoutPanel(); + dropDownList2 = new Labs.DropDownList(); + button1 = new Button(); + pictureBox1 = new PictureBox(); + label4 = new Label(); + tableLayoutPanel1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); + SuspendLayout(); + // + // textBox1 + // + textBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; + textBox1.Location = new Point(3, 53); + textBox1.Multiline = true; + textBox1.Name = "textBox1"; + textBox1.Size = new Size(334, 77); + textBox1.TabIndex = 0; + // + // mailTextBox1 + // + mailTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; + mailTextBox1.AutoSize = true; + mailTextBox1.Location = new Point(679, 76); + mailTextBox1.Name = "mailTextBox1"; + mailTextBox1.Size = new Size(248, 30); + mailTextBox1.TabIndex = 1; + mailTextBox1.Template = "^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$"; + // + // label1 + // + label1.Anchor = AnchorStyles.None; + label1.AutoSize = true; + label1.Location = new Point(149, 15); + label1.Name = "label1"; + label1.Size = new Size(42, 20); + label1.TabIndex = 3; + label1.Text = "ФИО"; + // + // label2 + // + label2.Anchor = AnchorStyles.None; + label2.AutoSize = true; + label2.Location = new Point(475, 15); + label2.Name = "label2"; + label2.Size = new Size(66, 20); + label2.TabIndex = 4; + label2.Text = "Продукт"; + // + // label3 + // + label3.Anchor = AnchorStyles.None; + label3.AutoSize = true; + label3.Location = new Point(777, 15); + label3.Name = "label3"; + label3.Size = new Size(51, 20); + label3.TabIndex = 5; + label3.Text = "Почта"; + // + // tableLayoutPanel1 + // + tableLayoutPanel1.ColumnCount = 4; + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30.4413929F)); + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30.1369915F)); + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 22.7549458F)); + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 16.666666F)); + tableLayoutPanel1.Controls.Add(label2, 1, 0); + tableLayoutPanel1.Controls.Add(dropDownList2, 1, 1); + tableLayoutPanel1.Controls.Add(textBox1, 0, 1); + tableLayoutPanel1.Controls.Add(button1, 1, 2); + tableLayoutPanel1.Controls.Add(label1, 0, 0); + tableLayoutPanel1.Controls.Add(pictureBox1, 3, 1); + tableLayoutPanel1.Controls.Add(label4, 3, 0); + tableLayoutPanel1.Controls.Add(mailTextBox1, 2, 1); + tableLayoutPanel1.Controls.Add(label3, 2, 0); + tableLayoutPanel1.Dock = DockStyle.Fill; + tableLayoutPanel1.Location = new Point(0, 0); + tableLayoutPanel1.Name = "tableLayoutPanel1"; + tableLayoutPanel1.RowCount = 3; + tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F)); + tableLayoutPanel1.RowStyles.Add(new RowStyle()); + tableLayoutPanel1.RowStyles.Add(new RowStyle()); + tableLayoutPanel1.Size = new Size(1117, 413); + tableLayoutPanel1.TabIndex = 6; + tableLayoutPanel1.Paint += tableLayoutPanel1_Paint; + // + // dropDownList2 + // + dropDownList2.Anchor = AnchorStyles.Left | AnchorStyles.Right; + dropDownList2.AutoSize = true; + dropDownList2.Location = new Point(343, 76); + dropDownList2.MinimumSize = new Size(0, 30); + dropDownList2.Name = "dropDownList2"; + dropDownList2.SelectedLine = ""; + dropDownList2.Size = new Size(330, 30); + dropDownList2.TabIndex = 7; + // + // button1 + // + button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + button1.Location = new Point(343, 381); + button1.Name = "button1"; + button1.Size = new Size(330, 29); + button1.TabIndex = 8; + button1.Text = "Сохранить"; + button1.UseVisualStyleBackColor = true; + button1.Click += saveButton_Click; + // + // pictureBox1 + // + pictureBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right; + pictureBox1.Location = new Point(933, 60); + pictureBox1.Name = "pictureBox1"; + pictureBox1.Size = new Size(181, 62); + pictureBox1.TabIndex = 10; + pictureBox1.TabStop = false; + pictureBox1.Click += pictureBox1_Click; + // + // label4 + // + label4.Anchor = AnchorStyles.None; + label4.AutoSize = true; + label4.Location = new Point(975, 15); + label4.Name = "label4"; + label4.Size = new Size(97, 20); + label4.TabIndex = 9; + label4.Text = "Фото заказа"; + // + // Create + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1117, 413); + Controls.Add(tableLayoutPanel1); + Name = "Create"; + Text = "Create"; + FormClosing += Create_FormClosing; + Load += Create_Load; + tableLayoutPanel1.ResumeLayout(false); + tableLayoutPanel1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private TextBox textBox1; + private Labs.MailTextBox mailTextBox1; + private Label label1; + private Label label2; + private Label label3; + private TableLayoutPanel tableLayoutPanel1; + private Button button1; + private Label label4; + private PictureBox pictureBox1; + private Labs.DropDownList dropDownList2; + } +} \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Create.cs b/WinFormsApp1/WinFormsApp1/Create.cs new file mode 100644 index 0000000..75f6f1c --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Create.cs @@ -0,0 +1,139 @@ +using DocumentFormat.OpenXml.Drawing.Charts; +using Microsoft.VisualBasic.ApplicationServices; +using OnlineStoreDatabase.Storages; +using OnlineShopContracts.BindingModels; +using OnlineShopContracts.ViewModels; +using System; +using System.Linq; +using System.Windows.Forms; +using ShabComponentsLibrary; +using Labs; + + +namespace WinFormsApp1 +{ + public partial class Create : Form + { + public Create(int row = -1) + { + InitializeComponent(); + _storage = new OrderStorage(); + _productStorage = new ProductStorage(); + + orderIndex = row; + //MessageBox.Show(row.ToString(), "Some title", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + public int orderIndex { get; set; } = -1; + private readonly OrderStorage _storage; + private readonly ProductStorage _productStorage; + OrderViewModel initial { get; set; } + public bool saved = false; + + private void saveButton_Click(object sender, EventArgs e) + { + try + { + if (pictureBox1.Image == null) throw new Exception("No Image"); + if (orderIndex != -1) + { + _storage.Update(new OrderBindingModel + { + Id = orderIndex, + CustomerFIO = textBox1.Text, + Photo = Order.converterToBytes(pictureBox1.Image), //"photo", + Email = mailTextBox1.TextValue, + ProductId = dropDownList2.SelectedLine, + }); + } + else + { + _storage.Insert(new OrderBindingModel + { + CustomerFIO = textBox1.Text, + Photo = Order.converterToBytes(pictureBox1.Image), //"photo", + Email = mailTextBox1.TextValue, + ProductId = dropDownList2.SelectedLine, + }); + } + saved = true; + this.Close(); + + } + catch (Exception er) + { + MessageBox.Show(er.Message, "Some title", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void Create_Load(object sender, EventArgs e) + { + if (orderIndex != -1) + { + OrderViewModel order1 = _storage.GetElement(new OrderBindingModel + { + Id = orderIndex, + }); + textBox1.Text = order1.CustomerFIO; + dropDownList2.Fill(_productStorage.GetFullList().Select(x => x.Name).ToList()); + dropDownList2.SelectedLine = order1.ProductId; + pictureBox1.Image = Order.ConvertBytesToImage(order1.Photo); + mailTextBox1.TextValue = order1.Email; + + initial = order1; + } + else + { + initial = new OrderViewModel + { + CustomerFIO = "", + Photo = new byte[0], //"photo", + Email = "", + ProductId = "", + }; + } + } + + private void pictureBox1_Click(object sender, EventArgs e) + { + + using (OpenFileDialog dlg = new OpenFileDialog()) + { + dlg.Title = "Open Image"; + dlg.Filter = "Image|*.jpg;*.jpeg;*.png"; + + if (dlg.ShowDialog() == DialogResult.OK) + { + pictureBox1.Image = new Bitmap(dlg.FileName); + } + } + } + + + private void Create_FormClosing(object sender, FormClosingEventArgs e) + { + string email = ""; + try { email = mailTextBox1.TextValue; } catch { } + if (saved == false && + (initial.CustomerFIO != textBox1.Text || + !initial.Photo.SequenceEqual(Order.converterToBytes(pictureBox1.Image)) || + initial.Email != email || + initial.ProductId != dropDownList2.SelectedLine) + ) + { + DialogResult dialogResult = MessageBox.Show("У вас есть не сохранённые изменения! \n Уверены, что хотите закрыть?", "Закрыть?", MessageBoxButtons.YesNo); + if (dialogResult == DialogResult.No) + { + e.Cancel = true; + } + } + } + + + + private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e) + { + + } + + } +} diff --git a/WinFormsApp1/WinFormsApp1/Create.resx b/WinFormsApp1/WinFormsApp1/Create.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Create.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Dictinary.Designer.cs b/WinFormsApp1/WinFormsApp1/Dictinary.Designer.cs new file mode 100644 index 0000000..a229d9b --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Dictinary.Designer.cs @@ -0,0 +1,73 @@ +namespace WinFormsApp1 +{ + partial class Dictinary + { + /// + /// 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.AllowUserToAddRows = false; + dataGridView1.AllowUserToDeleteRows = false; + dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; + dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.Location = new Point(0, 0); + dataGridView1.MultiSelect = false; + dataGridView1.Name = "dataGridView1"; + dataGridView1.RowHeadersWidth = 51; + dataGridView1.RowTemplate.Height = 29; + dataGridView1.Size = new Size(443, 652); + dataGridView1.TabIndex = 0; + dataGridView1.KeyDown += dataGridView1_KeyDown; + dataGridView1.KeyUp += dataGridView1_KeyUp; + dataGridView1.PreviewKeyDown += dataGridView1_PreviewKeyDown; + // + // Dictinary + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(443, 652); + Controls.Add(dataGridView1); + KeyPreview = true; + Name = "Dictinary"; + Text = "Dictinary"; + Load += Dictinary_Load; + KeyDown += Dictinary_KeyDown; + ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView1; + } +} \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Dictinary.cs b/WinFormsApp1/WinFormsApp1/Dictinary.cs new file mode 100644 index 0000000..35d319c --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Dictinary.cs @@ -0,0 +1,116 @@ +using Labs; +using OnlineShopContracts.BindingModels; +using OnlineStoreDatabase.Storages; +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 WinFormsApp1 +{ + public partial class Dictinary : Form + { + public Dictinary() + { + InitializeComponent(); + + _storage = new ProductStorage(); + } + private readonly ProductStorage _storage; + public bool deleting = false; + private void Dictinary_Load(object sender, EventArgs e) + { + dataGridView1.Columns.Add("Id", "Id"); + dataGridView1.Columns[0].Visible = false; + + dataGridView1.Columns.Add("Name", "Name"); + //dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; + updateTable(); + + } + + public void updateTable() + { + dataGridView1.Rows.Clear(); + _storage.GetFullList().ForEach(item => + { + dataGridView1.Rows.Add(item.Id, item.Name); + }); + } + + private void Dictinary_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Insert) + { + dataGridView1.Rows.Add("", ""); + dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Selected = true; + } + else if (e.KeyCode == Keys.Delete) + { + deleting = true; + DialogResult dialogResult = MessageBox.Show("Уверены, что хотите удалить?", "Удалить?", MessageBoxButtons.YesNo); + if (dialogResult == DialogResult.Yes) + { + + _storage.Delete(new ProductBindingModel + { + Id = (int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value, + }); + updateTable(); + + } + } + } + + + + private void dataGridView1_KeyUp(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter && deleting == false) + { + if ((string)dataGridView1.SelectedCells[0].Value == "") + { + MessageBox.Show("Пустая строка!", "Empty", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + if (dataGridView1.SelectedCells[0].RowIndex != dataGridView1.Rows.Count - 1) + { + _storage.Update(new ProductBindingModel + { + Id = (int)dataGridView1.Rows[Math.Max(0, dataGridView1.SelectedCells[0].RowIndex - 1)].Cells[0].Value, + Name = (string)dataGridView1.Rows[Math.Max(0, dataGridView1.SelectedCells[0].RowIndex - 1)].Cells[1].Value, + }); + } + else + { + _storage.Insert(new ProductBindingModel + { + Name = (string)dataGridView1.SelectedCells[0].Value, + }); + } + updateTable(); + + e.SuppressKeyPress = true; + e.Handled = true; + return; + } + else deleting = false; + } + + + + private void dataGridView1_KeyDown(object sender, KeyEventArgs e) + { + } + + private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) + { + } + } +} diff --git a/WinFormsApp1/WinFormsApp1/Dictinary.resx b/WinFormsApp1/WinFormsApp1/Dictinary.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Dictinary.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Form1.Designer.cs b/WinFormsApp1/WinFormsApp1/Form1.Designer.cs index 6a32e9b..24f5ede 100644 --- a/WinFormsApp1/WinFormsApp1/Form1.Designer.cs +++ b/WinFormsApp1/WinFormsApp1/Form1.Designer.cs @@ -28,61 +28,129 @@ /// private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); - this.userControl11 = new WinFormsLibrary1.CheckedListBoxControl(); - this.dataControl1 = new WinFormsLibrary1.DataControl(); - this.treeViewControl1 = new WinFormsLibrary1.TreeViewControl(); - this.excel21 = new WinFormsLibrary1.ExcelTable(this.components); - this.SuspendLayout(); + components = new System.ComponentModel.Container(); + objectsListBox1 = new Labs.ObjectsListBox(); + shabListOutputComponent1 = new ShabComponentsLibrary.ShabListOutputComponent(); + 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(); + excelImages1 = new WinFormsLibrary1.ExcelImages(components); + wordTable1 = new Labs.WordTable(components); + shabDiagramComponent1 = new ShabComponentsLibrary.ShabDiagramComponent(components); + contextMenuStrip1.SuspendLayout(); + SuspendLayout(); // - // userControl11 + // objectsListBox1 // - this.userControl11.Location = new System.Drawing.Point(12, 37); - this.userControl11.Name = "userControl11"; - this.userControl11.SelectedItem = ""; - this.userControl11.Size = new System.Drawing.Size(276, 217); - this.userControl11.TabIndex = 0; - this.userControl11.Load += new System.EventHandler(this.userControl11_Load); + objectsListBox1.AutoSize = true; + objectsListBox1.Location = new Point(44, 35); + objectsListBox1.Name = "objectsListBox1"; + objectsListBox1.SelectedIndex = -1; + objectsListBox1.Size = new Size(520, 321); + objectsListBox1.TabIndex = 1; // - // dataControl1 + // shabListOutputComponent1 // - this.dataControl1.Location = new System.Drawing.Point(306, 29); - this.dataControl1.Name = "dataControl1"; - this.dataControl1.Size = new System.Drawing.Size(332, 115); - this.dataControl1.TabIndex = 1; - this.dataControl1.ValueChanged += new System.EventHandler(this.dataControl1_ValueChanged); + shabListOutputComponent1.ContextMenuStrip = contextMenuStrip1; + shabListOutputComponent1.Dock = DockStyle.Fill; + shabListOutputComponent1.Location = new Point(0, 0); + shabListOutputComponent1.Margin = new Padding(3, 4, 3, 4); + shabListOutputComponent1.Name = "shabListOutputComponent1"; + shabListOutputComponent1.SelectedRow = -1; + shabListOutputComponent1.Size = new Size(1054, 491); + shabListOutputComponent1.TabIndex = 2; + shabListOutputComponent1.Enter += shabListOutputComponent1_Enter; // - // treeViewControl1 + // contextMenuStrip1 // - this.treeViewControl1.Location = new System.Drawing.Point(665, 12); - this.treeViewControl1.Name = "treeViewControl1"; - this.treeViewControl1.SelectedNod = -1; - this.treeViewControl1.SelectedNode = null; - this.treeViewControl1.Size = new System.Drawing.Size(361, 360); - this.treeViewControl1.TabIndex = 2; + 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(397, 172); + // + // создатьЗаписьToolStripMenuItem + // + создатьЗаписьToolStripMenuItem.Name = "создатьЗаписьToolStripMenuItem"; + создатьЗаписьToolStripMenuItem.Size = new Size(396, 24); + создатьЗаписьToolStripMenuItem.Text = "Создать запись"; + создатьЗаписьToolStripMenuItem.Click += создатьЗаписьToolStripMenuItem_Click; + // + // открытьЗаписьToolStripMenuItem + // + открытьЗаписьToolStripMenuItem.Name = "открытьЗаписьToolStripMenuItem"; + открытьЗаписьToolStripMenuItem.Size = new Size(396, 24); + открытьЗаписьToolStripMenuItem.Text = "Открыть запись"; + открытьЗаписьToolStripMenuItem.Click += открытьЗаписьToolStripMenuItem_Click; + // + // удалитьЗаписьToolStripMenuItem + // + удалитьЗаписьToolStripMenuItem.Name = "удалитьЗаписьToolStripMenuItem"; + удалитьЗаписьToolStripMenuItem.Size = new Size(396, 24); + удалитьЗаписьToolStripMenuItem.Text = "Удалить запись"; + удалитьЗаписьToolStripMenuItem.Click += удалитьЗаписьToolStripMenuItem_Click; + // + // создатьПростойДокументToolStripMenuItem + // + создатьПростойДокументToolStripMenuItem.Name = "создатьПростойДокументToolStripMenuItem"; + создатьПростойДокументToolStripMenuItem.Size = new Size(396, 24); + создатьПростойДокументToolStripMenuItem.Text = "Создать простой документ"; + создатьПростойДокументToolStripMenuItem.Click += создатьПростойДокументToolStripMenuItem_Click; + // + // создатьДокументСНастраиваемойТаблицейToolStripMenuItem + // + создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Name = "создатьДокументСНастраиваемойТаблицейToolStripMenuItem"; + создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Size = new Size(396, 24); + создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Text = "Создать документ с настраиваемой таблицей"; + создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Click += создатьДокументСНастраиваемойТаблицейToolStripMenuItem_Click; + // + // создатьДокументСДиаграммойToolStripMenuItem + // + создатьДокументСДиаграммойToolStripMenuItem.Name = "создатьДокументСДиаграммойToolStripMenuItem"; + создатьДокументСДиаграммойToolStripMenuItem.Size = new Size(396, 24); + создатьДокументСДиаграммойToolStripMenuItem.Text = "Создать документ с диаграммой"; + создатьДокументСДиаграммойToolStripMenuItem.Click += создатьДокументСДиаграммойToolStripMenuItem_Click; + // + // справочникToolStripMenuItem + // + справочникToolStripMenuItem.Name = "справочникToolStripMenuItem"; + справочникToolStripMenuItem.Size = new Size(396, 24); + справочникToolStripMenuItem.Text = "Справочник"; + справочникToolStripMenuItem.Click += справочникToolStripMenuItem_Click; // // Form1 // - this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1052, 404); - this.Controls.Add(this.treeViewControl1); - this.Controls.Add(this.dataControl1); - this.Controls.Add(this.userControl11); - this.Name = "Form1"; - this.Text = "Form1"; - this.Load += new System.EventHandler(this.Form1_Load); - this.ResumeLayout(false); - + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1054, 491); + Controls.Add(shabListOutputComponent1); + Controls.Add(objectsListBox1); + Name = "Form1"; + Text = "Form1"; + Enter += Form1_Enter; + contextMenuStrip1.ResumeLayout(false); + ResumeLayout(false); + PerformLayout(); } #endregion - - private WinFormsLibrary1.CheckedListBoxControl userControl11; - private WinFormsLibrary1.DataControl dataControl1; - private WinFormsLibrary1.TreeViewControl treeViewControl1; - private WinFormsLibrary1.ExcelImages excelComponent1; - private WinFormsLibrary1.ExcelTable excel22; - private WinFormsLibrary1.ExcelTable excel21; + //private WinFormsLibrary1.TreeViewControl treeViewControl2; + private Labs.ObjectsListBox objectsListBox1; + private ShabComponentsLibrary.ShabListOutputComponent shabListOutputComponent1; + 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.ExcelImages excelImages1; + private Labs.WordTable wordTable1; + private ShabComponentsLibrary.ShabDiagramComponent shabDiagramComponent1; } -} \ No newline at end of file +} diff --git a/WinFormsApp1/WinFormsApp1/Form1.cs b/WinFormsApp1/WinFormsApp1/Form1.cs index 1ab786d..0734a91 100644 --- a/WinFormsApp1/WinFormsApp1/Form1.cs +++ b/WinFormsApp1/WinFormsApp1/Form1.cs @@ -1,4 +1,14 @@ -using WinFormsLibrary1; +using Labs; +using Labs.HelperClasses.WordTable; +using ShabComponentsLibrary; +using WinFormsLibrary1; +using ShabComponentsLibrary; +using OnlineShopContracts.BindingModels; +using OnlineStoreDatabase.Storages; +using System.Windows.Forms; +using System.Text; +using OfficeOpenXml; +using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace WinFormsApp1 { @@ -8,32 +18,227 @@ namespace WinFormsApp1 { InitializeComponent(); - /*treeViewControl1.AddTree(new List + _storage = new OrderStorage(); + + /*objectsListBox1.SetTemplateInfo("ФИО: ; , ", '<', '>'); + + objectsListBox1.Fill(new List + { + new Order(1, "FIO1", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 0, "EMAIL1"), + new Order(1, "FIO2", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL2"), + new Order(1, "FIO3", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL3"), + new Order(1, "FIO4", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL4"), + }); + + + treeViewControl2.SetHierarchy(new string[] { "Otdel", "Dol", "FirstName", }); + treeViewControl2.SetAlwaysNewBranchFields(new string[] { "FirstName" }); + treeViewControl2.AddTree(new List { new TestNode("Name1", "otdel1", "dolj"), new TestNode("Name1", "otdel1", "dolj"), new TestNode("Name2", "otdel3", "dolj4"), new TestNode("Name3", "otdel3", "dolj2"), + }); + */ + + + // Configure the columns for the list output component + shabListOutputComponent1.ConfigureColumns(new List + { + //new ColumnInfo { Header = "Name", Width = 150, IsVisible = true, Name = "Name" }, + new ColumnInfo("Id", 400, false, "Id"), + new ColumnInfo("FIO", 400, true, "CustomerFIO"), + new ColumnInfo("Produc", 400, true, "ProductId"), + new ColumnInfo("Photo", 400, false, "Photo"), + new ColumnInfo("Email", 400, true, "Email"), + }); + /* + // Insert values into the grid + shabListOutputComponent1.InsertValues(new List + { + new Order(1, "FIO1", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 0, "EMAIL1"), + new Order(1, "FIO2", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL2"), + new Order(1, "FIO3", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL3"), + new Order(1, "FIO4", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL4"), });*/ - } - private void userControl11_Load(object sender, EventArgs e) + shabListOutputComponent1.InsertValues(_storage.GetFullList()); + } + private readonly OrderStorage _storage; + + + + + private void создатьЗаписьToolStripMenuItem_Click(object sender, EventArgs e) { + Create g = new Create(); + g.ShowDialog(); + shabListOutputComponent1.InsertValues(_storage.GetFullList()); } - - private void Form1_Load(object sender, EventArgs e) + private void открытьЗаписьToolStripMenuItem_Click(object sender, EventArgs e) { + var myObject = shabListOutputComponent1.GetSelectedObject(); + Create g = new Create(myObject.Id); + g.ShowDialog(); + + shabListOutputComponent1.InsertValues(_storage.GetFullList()); } - private void dataControl1_ValueChanged(object sender, EventArgs e) + private void удалитьЗаписьToolStripMenuItem_Click(object sender, EventArgs e) { - + if (shabListOutputComponent1.SelectedRow != -1) + { + DialogResult dialogResult = MessageBox.Show("Удалить запись под номером " + (shabListOutputComponent1.SelectedRow + 1).ToString() + "?", "Удалить?", MessageBoxButtons.YesNo); + if (dialogResult == DialogResult.Yes) + { + _storage.Delete(new OrderBindingModel + { + Id = shabListOutputComponent1.SelectedRow + 1 + }); + } + + } + } + + private void справочникToolStripMenuItem_Click(object sender, EventArgs e) + { + Dictinary g = new Dictinary(); + g.ShowDialog(); + + shabListOutputComponent1.InsertValues(_storage.GetFullList()); } + private void создатьПростойДокументToolStripMenuItem_Click(object sender, EventArgs e) + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + saveFileDialog.Filter = "Image Files (*.xlsx)|*.xlsx"; + saveFileDialog.Title = "Сохранить документ"; + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + List objects = new List { }; + try + { + for (int i = 0; i < 100000; i++) + { + shabListOutputComponent1.SelectedRow = i; + objects.Add(shabListOutputComponent1.GetSelectedObject()); + } + } + catch { } + + ExcelPackage.LicenseContext = LicenseContext.NonCommercial; + excelImages1.CreateDocument(saveFileDialog.FileName, "My Document", objects.Select(x => Order.ConvertBytesToImage(x.Photo)).ToList()); + + } + } + } + + + private void Form1_Enter(object sender, EventArgs e) + { + shabListOutputComponent1.InsertValues(_storage.GetFullList()); + } + private void treeViewControl2_Load(object sender, EventArgs e) + { + // Insert values into the grid + + } + + private void shabListOutputComponent1_Enter(object sender, EventArgs e) + { + } + + private void создатьДокументСНастраиваемойТаблицейToolStripMenuItem_Click(object sender, EventArgs e) + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + saveFileDialog.Filter = "Image Files (*.docx)|*.docx"; + saveFileDialog.Title = "Сохранить документ"; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + List objects = new List { }; + try + { + for (int i = 0; i < 100000; i++) + { + shabListOutputComponent1.SelectedRow = i; + objects.Add(shabListOutputComponent1.GetSelectedObject()); + } + } + catch { } + + wordTable1.CreateWordTable(new Labs.HelperClasses.WordTable.WordTableConfig( + saveFileDialog.FileName, + "ExcelMine", + new List { + new ColumnProperties("Id", 100, "Идентификатор", "Идентификатор"), + new ColumnProperties("CustomerFIO", 100, "Личные данные", "ФИО заказчика"), + new ColumnProperties("Email", 100, "Личные данные", "Эл. почта"), + new ColumnProperties("ProductId", 100, "Выбранный товар", "Выбранный товар"), + }, + new List + { + new CellMergeInfo(1, 2) + }, + objects + )); + + } + } + + } + + private void создатьДокументСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e) + { + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + saveFileDialog.Filter = "Image Files (*.pdf)|*.pdf"; + saveFileDialog.Title = "Сохранить документ"; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + List objects = new List { }; + try + { + for (int i = 0; i < 100000; i++) + { + shabListOutputComponent1.SelectedRow = i; + objects.Add(shabListOutputComponent1.GetSelectedObject()); + } + } + catch { } + Dictionary l = new Dictionary {}; + objects.ForEach(item => + { + if (!l.ContainsKey(item.ProductId)) + l[item.ProductId] = new int[] { 1 }; + else + l[item.ProductId][0] += 1; + }); + + + + shabDiagramComponent1.CreateDocument( + saveFileDialog.FileName, + "Гистограмма интернет магазина", + "Количество заказов товаров", + ShabComponentsLibrary.Enums.LegendPosition.Top, + l + ); + + } + } + } } -} \ No newline at end of file +} diff --git a/WinFormsApp1/WinFormsApp1/Form1.resx b/WinFormsApp1/WinFormsApp1/Form1.resx index 947e8e6..ca8d7a3 100644 --- a/WinFormsApp1/WinFormsApp1/Form1.resx +++ b/WinFormsApp1/WinFormsApp1/Form1.resx @@ -1,4 +1,64 @@ - + + + @@ -57,7 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 + + 202, 17 + + + 348, 17 + + + 481, 17 + \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Order.cs b/WinFormsApp1/WinFormsApp1/Order.cs new file mode 100644 index 0000000..62b3a5a --- /dev/null +++ b/WinFormsApp1/WinFormsApp1/Order.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WinFormsApp1 +{ + public class Order + { + public int Id { get; set; } + public string CustomerFIO { get; set; } + public byte[] Photo { get; set; } // Для хранения фото заказа + public int ProductId { get; set; } // Внешний ключ на продукт + public string Email { get; set; } + + public Order(int id, string customerFIO, byte[] photo, int productId, string email) + { + Id = id; + CustomerFIO = customerFIO; + Photo = photo; + ProductId = productId; + Email = email; + } + + + public static byte[] converterToBytes(Image x) + { + ImageConverter _imageConverter = new ImageConverter(); + byte[] xByte = (byte[])_imageConverter.ConvertTo(new Bitmap(x), typeof(byte[])); + return xByte; + } + public static Image ConvertBytesToImage(byte[] imageBytes) + { + using (var ms = new MemoryStream(imageBytes)) + { + return Image.FromStream(ms); + } + } + } + + public class Product + { + public int Id { get; set; } + public string Name { get; set; } + public decimal Price { get; set; } + } +} diff --git a/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj b/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj index 4fd8f91..29296fd 100644 --- a/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj +++ b/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj @@ -6,14 +6,23 @@ enable true enable + True - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + - + \ No newline at end of file diff --git a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.Designer.cs b/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.Designer.cs deleted file mode 100644 index f41b8f8..0000000 --- a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class CheckedListBoxControl - { - /// - /// 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 Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.checkedListBox1 = new System.Windows.Forms.CheckedListBox(); - this.SuspendLayout(); - // - // checkedListBox1 - // - this.checkedListBox1.FormattingEnabled = true; - this.checkedListBox1.Location = new System.Drawing.Point(13, 16); - this.checkedListBox1.Name = "checkedListBox1"; - this.checkedListBox1.Size = new System.Drawing.Size(180, 144); - this.checkedListBox1.TabIndex = 1; - this.checkedListBox1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.checkedListBox1_ItemCheck); - this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.checkedListBox1_SelectedIndexChanged); - // - // CheckedListBoxControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.checkedListBox1); - this.Name = "CheckedListBoxControl"; - this.Size = new System.Drawing.Size(209, 180); - this.Load += new System.EventHandler(this.UserControl1_Load); - this.ResumeLayout(false); - - } - - #endregion - - private CheckedListBox checkedListBox1; - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.cs b/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.cs deleted file mode 100644 index 7f5d32b..0000000 --- a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.cs +++ /dev/null @@ -1,82 +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 CheckedListBoxControl : UserControl - { - public CheckedListBoxControl() - { - InitializeComponent(); - } - - //Метод, у которого в передаваемых параметрах идет список строк - public void AddToComboBox(List list) - { - foreach (var Item in list) - { - checkedListBox1.Items.Add(Item); - } - } - - //Очистка списка - public void ClearList() - { - checkedListBox1.Items.Clear(); - } - - //Установка и получение выбранного значения - public string SelectedItem - { - get { return (string?)checkedListBox1.SelectedItem ?? string.Empty; } - set { checkedListBox1.SelectedItem = value; } - } - - private event EventHandler? _itemSelected; - - //Событие, вызываемое при смене значения - public event EventHandler? ItemSelected - { - add { _itemSelected += value; } - remove { _itemSelected -= value; } - } - - private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e) - { - int selectedId = checkedListBox1.SelectedIndex; - //checkedListBox1.SetItemChecked(selectedId, true); - - for (int i = 0; i < checkedListBox1.Items.Count; i++) - { - if (i != selectedId) checkedListBox1.SetItemChecked(i, false); - } - - _itemSelected?.Invoke(this, e); - } - - - - - - - - private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) - { - - } - - - - private void UserControl1_Load(object sender, EventArgs e) - { - - } - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.resx b/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.resx deleted file mode 100644 index f298a7b..0000000 --- a/WinFormsApp1/WinFormsLibrary1/CheckedListBoxControl.resx +++ /dev/null @@ -1,60 +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/WinFormsApp1/WinFormsLibrary1/DataControl.Designer.cs b/WinFormsApp1/WinFormsLibrary1/DataControl.Designer.cs deleted file mode 100644 index c51fe3e..0000000 --- a/WinFormsApp1/WinFormsLibrary1/DataControl.Designer.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class DataControl - { - /// - /// 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 Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); - this.SuspendLayout(); - // - // dateTimePicker1 - // - this.dateTimePicker1.Location = new System.Drawing.Point(14, 50); - this.dateTimePicker1.Name = "dateTimePicker1"; - this.dateTimePicker1.Size = new System.Drawing.Size(300, 31); - this.dateTimePicker1.TabIndex = 2; - this.dateTimePicker1.ValueChanged += new System.EventHandler(this.MainTextBox_TextChanged); - // - // DataControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.dateTimePicker1); - this.Name = "DataControl"; - this.Size = new System.Drawing.Size(329, 131); - this.ResumeLayout(false); - - } - - #endregion - - private DateTimePicker dateTimePicker1; - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/DataControl.cs b/WinFormsApp1/WinFormsLibrary1/DataControl.cs deleted file mode 100644 index 7fcdd49..0000000 --- a/WinFormsApp1/WinFormsLibrary1/DataControl.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.Exceptions; - -namespace WinFormsLibrary1 -{ - public partial class DataControl : UserControl - { - public DataControl() - { - InitializeComponent(); - } - - - //Установка диапазона - public void SetDateRange(DateTime time1, DateTime time2) - { - first = time1; - end = time2; - } - private DateTime? first = null; - private DateTime? end = null; - - - /// Установка и получение введенного значения - public DateTime DateValue - { - get - { - if (first == null) throw new EmptyValueException(); - - if (dateTimePicker1.Value < first || dateTimePicker1.Value > end) - throw new NotInDateRange(); - - return dateTimePicker1.Value; - } - set - { - if (first != null && value >= first && value <= end) - dateTimePicker1.Value = (DateTime)value; - } - } - - private event EventHandler? _valueChanged; - - /// Событие, вызываемое при смене значения - public event EventHandler? ValueChanged - { - add { _valueChanged += value; } - remove { _valueChanged -= value; } - } - - private void MainTextBox_TextChanged(object sender, EventArgs e) - { - _valueChanged?.Invoke(this, e); - } - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/DataControl.resx b/WinFormsApp1/WinFormsLibrary1/DataControl.resx deleted file mode 100644 index f298a7b..0000000 --- a/WinFormsApp1/WinFormsLibrary1/DataControl.resx +++ /dev/null @@ -1,60 +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/WinFormsApp1/WinFormsLibrary1/ExcelImages.Designer.cs b/WinFormsApp1/WinFormsLibrary1/ExcelImages.Designer.cs deleted file mode 100644 index d7a41b4..0000000 --- a/WinFormsApp1/WinFormsLibrary1/ExcelImages.Designer.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class ExcelImages - { - /// - /// 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 Component 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(); - } - - #endregion - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/ExcelImages.cs b/WinFormsApp1/WinFormsLibrary1/ExcelImages.cs deleted file mode 100644 index e2520b7..0000000 --- a/WinFormsApp1/WinFormsLibrary1/ExcelImages.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.ComponentModel; -using OfficeOpenXml; -namespace WinFormsLibrary1 -{ - public partial class ExcelImages : Component - { - public ExcelImages() - { - InitializeComponent(); - } - - public ExcelImages(IContainer container) - { - container.Add(this); - - InitializeComponent(); - } - - public void CreateDocument( - string filePath, - string documentTitle, - List images) - { - if (string.IsNullOrWhiteSpace(filePath)) - { - throw new ArgumentException("Путь к файлу не может быть пустым.", nameof(filePath)); - } - - if (string.IsNullOrWhiteSpace(documentTitle)) - { - throw new ArgumentException("Название документа не может быть пустым.", nameof(documentTitle)); - } - - if (images == null || images.Count == 0) - { - throw new ArgumentException("Массив изображений не может быть пустым.", nameof(images)); - } - - using (var package = new ExcelPackage()) - { - var worksheet = package.Workbook.Worksheets.Add(documentTitle); - - worksheet.Cells[1, 1].Value = documentTitle; - worksheet.Cells[1, 1].Style.Font.Bold = true; - worksheet.Cells[1, 1].Style.Font.Size = 16; - - double row = 2; - foreach (var image in images) - { - var excelImage = worksheet.Drawings.AddPicture($"Image{(int)(row - 1)}", new MemoryStream(ImageToByteArray(image))); - excelImage.SetPosition((int)(row - 1), 0, 0, 0); - excelImage.SetSize(image.Width, image.Height); - - row += (int)(image.Height/ PointsToPixels(worksheet.Row(1).Height)); - } - - FileInfo file = new FileInfo(filePath); - package.SaveAs(file); - } - } - - private byte[] ImageToByteArray(Image image) - { - using (var ms = new MemoryStream()) - { - image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); - return ms.ToArray(); - } - } - // Метод для перевода пунктов в пиксели - static double PointsToPixels(double points) - { - return points * (96.0 / 72.0); // Стандартный DPI для экранов 96 пикселей на дюйм, а 1 пункт = 1/72 дюйма - } - - } -} - - - \ No newline at end of file diff --git a/WinFormsApp1/WinFormsLibrary1/ExcelTable.Designer.cs b/WinFormsApp1/WinFormsLibrary1/ExcelTable.Designer.cs deleted file mode 100644 index 2042acd..0000000 --- a/WinFormsApp1/WinFormsLibrary1/ExcelTable.Designer.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class ExcelTable - { - /// - /// 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 Component 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(); - } - - #endregion - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/ExcelTable.cs b/WinFormsApp1/WinFormsLibrary1/ExcelTable.cs deleted file mode 100644 index 8fb6662..0000000 --- a/WinFormsApp1/WinFormsLibrary1/ExcelTable.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System.ComponentModel; -using OfficeOpenXml; -using OfficeOpenXml.Style; - -namespace WinFormsLibrary1 -{ - public partial class ExcelTable : Component - { - public ExcelTable() - { - InitializeComponent(); - } - public ExcelTable(IContainer container) - { - container.Add(this); - - InitializeComponent(); - } - - // Публичный метод для создания Excel документа - public void GenerateExcel(string filePath, string documentTitle, - List mergeInfo, - List<(string, string, string propertyName)> headerTitles, List data) - { - if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(documentTitle) || - mergeInfo == null || headerTitles == null || data == null) - { - throw new ArgumentException("Не все входные данные заполнены."); - } - // Проверка на заполненность шапки - ValidateHeaders(headerTitles); - - // Проверки на корректность объединения ячеек и заполнения - ValidateMergedCells(mergeInfo, headerTitles.Count); - - using (var package = new ExcelPackage()) - { - var worksheet = package.Workbook.Worksheets.Add("Sheet1"); - - worksheet.Cells[1, 1].Value = documentTitle; - worksheet.Cells[1, 1, 1, headerTitles.Count].Merge = true; - worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; - - //Мержим заголовки по столбцам - for (int i = 1; i < headerTitles.Count; i++) - { - if (headerTitles[i].Item2 == headerTitles[i + 1].Item2) - { - int j; - for (j = i; j < headerTitles.Count; j++) - { - if (headerTitles[j].Item2 != headerTitles[j + 1].Item2) break; - } - - mergeInfo.Add(new MergeInfo(2, i + 1, 2, j + 1)); - i = j + 1; - - } - } - - // Заполняем шапку таблицы - for (int i = 0; i < headerTitles.Count; i++) - { - worksheet.Cells[2, i + 1].Value = headerTitles[i].Item2; - worksheet.Cells[3, i + 1].Value = headerTitles[i].Item1; - - //Мержим заголовки по строкам - if (headerTitles[i].Item1 == headerTitles[i].Item2) mergeInfo.Add(new MergeInfo(2, i + 1, 3, i + 1)); - } - - // Применение объединений ячеек - foreach (var merge in mergeInfo) - { - worksheet.Cells[merge.StartRow, merge.StartColumn, merge.EndRow, merge.EndColumn].Merge = true; - } - - // Установка высоты строк - for (int i = 0; i < data.Count; i++) - { - - } - - // Заполнение данных таблицы - for (int rowIndex = 0; rowIndex < data.Count; rowIndex++) - { - var rowData = data[rowIndex]; - for (int colIndex = 0; colIndex < headerTitles.Count; colIndex++) - { - // Используем сопоставление полей/свойств объекта - string propertyName = headerTitles[colIndex].propertyName; - var property = rowData.GetType().GetProperty(propertyName); - - if (property == null) - throw new ArgumentException($"Свойство {property} не найдено в классе {propertyName}."); - - worksheet.Cells[rowIndex + 4, colIndex + 1].Value = property.GetValue(rowData); - - } - - string propertyName2 = "height"; - var propertyHeight = rowData.GetType().GetProperty(propertyName2); - - if (propertyHeight == null) - throw new ArgumentException($"Свойство {propertyHeight} не найдено в классе {propertyName2}."); - worksheet.Row(rowIndex + 4).Height = (double)propertyHeight.GetValue(rowData); - } - - - - // Сохранение файла - var file = new FileInfo(filePath); - package.SaveAs(file); - } - } - - public class Person - { - public int ID { get; set; } // Идентификатор - public string status { get; set; } - public string name { get; set; } - public string fio { get; set; } - public int Age { get; set; } - public string vos { get; set; } - public string kids { get; set; } - public string dol { get; set; } - public string pod { get; set; } - public int prem { get; set; } - public int height { get; set; } - - public Person(int height, int id, string status, string name, string fio, int Age, string vos, string kids, string dol, string pod, int prem) - { - this.height = height; - this.ID = id; - this.status = status; - this.name = name; - this.fio = fio; - this.Age = Age; - this.vos = vos; - this.kids = kids; - this.dol = dol; - this.pod = pod; - this.prem = prem; - } - } - - // Метод для проверки на заполненность шапки - private void ValidateHeaders(List<(string, string, string)> headerInfo) - { - foreach (var header in headerInfo) - { - if (string.IsNullOrWhiteSpace(header.Item1) || string.IsNullOrWhiteSpace(header.Item2)) - { - throw new ArgumentException("Все ячейки шапки должны быть заполнены."); - } - } - } - - // Метод для проверки наложения объединенных ячеек - private void ValidateMergedCells(List mergeInfo, int headerColumnsCount) - { - foreach (var merge in mergeInfo) - { - if (merge.StartColumn > headerColumnsCount || merge.EndColumn > headerColumnsCount) - { - throw new ArgumentException("Объединенные ячейки выходят за пределы шапки."); - } - - // Дополнительные проверки можно добавить здесь - } - - // Проверка на наложение объединенных ячеек - for (int i = 0; i < mergeInfo.Count; i++) - { - var currentMerge = mergeInfo[i]; - - for (int j = i + 1; j < mergeInfo.Count; j++) - { - var otherMerge = mergeInfo[j]; - - // Проверка пересечения по строкам и столбцам - bool isOverlapping = - currentMerge.StartRow <= otherMerge.EndRow && currentMerge.EndRow >= otherMerge.StartRow && - currentMerge.StartColumn <= otherMerge.EndColumn && currentMerge.EndColumn >= otherMerge.StartColumn; - - if (isOverlapping) - { - throw new ArgumentException($"Объединенные ячейки пересекаются: [{currentMerge.StartRow},{currentMerge.StartColumn}] - [{currentMerge.EndRow},{currentMerge.EndColumn}] и [{otherMerge.StartRow},{otherMerge.StartColumn}] - [{otherMerge.EndRow},{otherMerge.EndColumn}]."); - } - } - } - } - } -} -// Класс для информации об объединении ячеек -public class MergeInfo -{ - public int StartRow { get; set; } - public int StartColumn { get; set; } - public int EndRow { get; set; } - public int EndColumn { get; set; } - - public MergeInfo(int startRow, int startColumn, int endRow, int endColumn) - { - StartRow = startRow; - StartColumn = startColumn; - EndRow = endRow; - EndColumn = endColumn; - } -} - - - diff --git a/WinFormsApp1/WinFormsLibrary1/Exceptions/EmptyValueException.cs b/WinFormsApp1/WinFormsLibrary1/Exceptions/EmptyValueException.cs deleted file mode 100644 index 8d5a30f..0000000 --- a/WinFormsApp1/WinFormsLibrary1/Exceptions/EmptyValueException.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Exceptions -{ - public class EmptyValueException : ApplicationException - { - public EmptyValueException() - : base("Значение Пустое") - { } - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/Exceptions/NotInDateRange.cs b/WinFormsApp1/WinFormsLibrary1/Exceptions/NotInDateRange.cs deleted file mode 100644 index d35e854..0000000 --- a/WinFormsApp1/WinFormsLibrary1/Exceptions/NotInDateRange.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1.Exceptions -{ - public class NotInDateRange : ApplicationException - { - public NotInDateRange() - : base("Дата находится не в диапазоне.") - { } - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/PieChart.cs b/WinFormsApp1/WinFormsLibrary1/PieChart.cs deleted file mode 100644 index b4f36e5..0000000 --- a/WinFormsApp1/WinFormsLibrary1/PieChart.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System.ComponentModel; -using OfficeOpenXml; -using OfficeOpenXml.Drawing.Chart; - - -namespace WinFormsLibrary1 -{ - public partial class PieChart : Component - { - public PieChart() - { - InitializeComponent(); - } - - public PieChart(IContainer container) - { - container.Add(this); - - InitializeComponent(); - } - - - // Публичный метод для создания Excel-документа с круговой диаграммой - public void CreateExcelWithPieChart(string filePath, string documentTitle, - string chartTitle, LegendPosition legendPosition, List chartData) - { - if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(documentTitle) || string.IsNullOrEmpty(chartTitle) || chartData == null || chartData.Count == 0) - { - throw new ArgumentException("Все входные данные должны быть заполнены."); - } - - using (var package = new ExcelPackage()) - { - var worksheet = package.Workbook.Worksheets.Add("ChartSheet"); - - // Устанавливаем заголовок документа - worksheet.Cells[1, 1].Value = documentTitle; - worksheet.Cells[1, 1, 1, 2].Merge = true; - worksheet.Cells[1, 1].Style.Font.Size = 16; - worksheet.Cells[1, 1].Style.Font.Bold = true; - - // Записываем данные для диаграммы в ячейки - int row = 3; - worksheet.Cells[row, 1].Value = "Series"; - worksheet.Cells[row, 2].Value = "Value"; - - foreach (var data in chartData) - { - row++; - worksheet.Cells[row, 1].Value = data.SeriesName; - worksheet.Cells[row, 2].Value = data.Value; - } - - // Создаем круговую диаграмму - var pieChart = worksheet.Drawings.AddChart(chartTitle, eChartType.Pie) as ExcelPieChart; - - // Устанавливаем диапазоны данных для диаграммы - pieChart.Series.Add(worksheet.Cells[4, 2, row, 2], worksheet.Cells[4, 1, row, 1]); - - // Заголовок диаграммы - pieChart.Title.Text = chartTitle; - - // Установка положения легенды - switch (legendPosition) - { - case LegendPosition.Top: - pieChart.Legend.Position = eLegendPosition.Top; - break; - case LegendPosition.Bottom: - pieChart.Legend.Position = eLegendPosition.Bottom; - break; - case LegendPosition.Left: - pieChart.Legend.Position = eLegendPosition.Left; - break; - case LegendPosition.Right: - pieChart.Legend.Position = eLegendPosition.Right; - break; - case LegendPosition.None: - pieChart.Legend.Remove(); - break; - } - - // Сохранение файла - var file = new FileInfo(filePath); - package.SaveAs(file); - } - } - } - - public class PieChartData - { - public string SeriesName { get; set; } // Название серии - public double Value { get; set; } // Значение - - public PieChartData(string seriesName, double value) - { - SeriesName = seriesName ?? throw new ArgumentNullException(nameof(seriesName)); - Value = value; - } - } - - // Перечисление для позиции легенды - public enum LegendPosition - { - Top, - Bottom, - Left, - Right, - None - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/TestNode.cs b/WinFormsApp1/WinFormsLibrary1/TestNode.cs deleted file mode 100644 index 5c1050d..0000000 --- a/WinFormsApp1/WinFormsLibrary1/TestNode.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinFormsLibrary1 -{ - public class TestNode - { - - public string FirstName { get; set; } = string.Empty; - - public string Otdel { get; set; } = string.Empty; - - public string Dol { get; set; } = string.Empty; - - public TestNode() - { } - - public TestNode(string FirstName, string Otdel, string Dol) - { - this.FirstName = FirstName; - this.Otdel = Otdel; - this.Dol = Dol; - } - - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.Designer.cs b/WinFormsApp1/WinFormsLibrary1/TreeViewControl.Designer.cs deleted file mode 100644 index f2f998e..0000000 --- a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.Designer.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace WinFormsLibrary1 -{ - partial class TreeViewControl - { - /// - /// 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 Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.treeView1 = new System.Windows.Forms.TreeView(); - this.SuspendLayout(); - // - // treeView1 - // - this.treeView1.Location = new System.Drawing.Point(29, 30); - this.treeView1.Name = "treeView1"; - this.treeView1.Size = new System.Drawing.Size(444, 283); - this.treeView1.TabIndex = 0; - this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect); - // - // TreeViewControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.treeView1); - this.Name = "TreeViewControl"; - this.Size = new System.Drawing.Size(512, 350); - this.ResumeLayout(false); - - } - - #endregion - - private TreeView treeView1; - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.cs b/WinFormsApp1/WinFormsLibrary1/TreeViewControl.cs deleted file mode 100644 index 83d33a0..0000000 --- a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.cs +++ /dev/null @@ -1,153 +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 TreeViewControl : UserControl - { - public TreeViewControl() - { - InitializeComponent(); - } - - private List hierarchy = new List(); - private HashSet alwaysNewBranches = new HashSet(); - - // Метод для задания иерархии полей - public void SetHierarchy(params string[] fields) - { - hierarchy.Clear(); - hierarchy.AddRange(fields); - } - - //всегда новая ветка - public void SetAlwaysNewBranchFields(params string[] fields) - { - alwaysNewBranches.Clear(); - alwaysNewBranches.UnionWith(fields); - } - - public void AddTree(List items) - { - treeView1.Nodes.Clear(); - - foreach (var item in items) - { - TreeNodeCollection currentNodes = treeView1.Nodes; - - foreach (var fieldName in hierarchy) - { - var property = typeof(T).GetProperties().First(x => x.Name == fieldName); - if (property == null) - throw new ArgumentException($"Field {fieldName} not found in type {typeof(T).Name}"); - - var fieldValue = property.GetValue(item)?.ToString() ?? "Unknown"; - TreeNode existingNode = null; - - if (!alwaysNewBranches.Contains(fieldName)) - { - foreach (TreeNode node in currentNodes) - { - if (node.Text == fieldValue) - { - existingNode = node; - break; - } - } - } - - if (existingNode == null) - { - existingNode = new TreeNode(fieldValue); - currentNodes.Add(existingNode); - } - - currentNodes = existingNode.Nodes; - } - } - } - - - public T GetObject() where T : new() - { - if (hierarchy == null) - { - throw new InvalidOperationException("Иерархия не задана"); - } - if (SelectedNode == null) - { - throw new InvalidOperationException("Узел не выбран"); - } - if (SelectedNode.Nodes.Count != 0) - { - throw new InvalidOperationException("Узел не конечный"); - } - - var obj = new T(); - for (int i = hierarchy.Count - 1; i >= 0; i--) - { - var value = SelectedNode.Text; - var propInfo = typeof(T).GetProperty(hierarchy[i]); - if (propInfo == null) - { - throw new InvalidOperationException($"Свойство {hierarchy[i]} не найдено в классе {typeof(T).Name}"); - } - propInfo.SetValue(obj, Convert.ChangeType(value, propInfo.PropertyType)); - - SelectedNode = SelectedNode.Parent; - if (SelectedNode == null) - { - break; - } - } - return obj; - } - - - - - // Свойство для получения/установки индекса выбранной ветки (конечного элемента одной из ветки) (set, get) - public int SelectedNod - { - get { - if (SelectedNode != null && SelectedNode.Nodes.Count == 0) - return SelectedNode.Index; - else return -1; - } - set { - if (value > 0 && value < treeView1.Nodes.Count && treeView1.Nodes[value]?.Nodes?.Count == 0) - SelectedNode = treeView1.Nodes[value]; - } - } - - // Свойство для получения/установки выбранной ветки - public TreeNode SelectedNode - { - get { return treeView1.SelectedNode; } - set { treeView1.SelectedNode = value; } - } - - //Публичный метод для получения выбранной записи (дляконечного элемента дерева). - public string SelectedName() - { - if (SelectedNode != null && SelectedNode.Nodes.Count == 0) - return SelectedNode.Text; - else return "Unknown"; - } - - - - private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) - { - //GetSelectedObject(); - } - } -} diff --git a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.resx b/WinFormsApp1/WinFormsLibrary1/TreeViewControl.resx deleted file mode 100644 index f298a7b..0000000 --- a/WinFormsApp1/WinFormsLibrary1/TreeViewControl.resx +++ /dev/null @@ -1,60 +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