From de8ff2cfafce209d70d83f4374915f9b2e8271ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=20=D0=90=D0=BB=D0=B5=D0=BA=D1=81?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= Date: Wed, 13 Nov 2024 15:21:19 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BA=D0=BE=D0=BF=D0=B5=D1=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FormLibrary/FormLibrary.csproj | 2 +- Forms/Forms.csproj | 2 +- KopLab1.sln | 38 +- Lab3Form/Form1.Designer.cs | 10 +- Lab3Form/Form1.cs | 20 ++ Lab3Form/FormFormats.Designer.cs | 84 +++++ Lab3Form/FormFormats.cs | 106 ++++++ Lab3Form/FormFormats.resx | 126 +++++++ Lab3Form/FormMain.Designer.cs | 175 +++++++++ Lab3Form/FormMain.cs | 338 ++++++++++++++++++ Lab3Form/FormMain.resx | 135 +++++++ Lab3Form/FormStudent.Designer.cs | 177 +++++++++ Lab3Form/FormStudent.cs | 120 +++++++ Lab3Form/FormStudent.resx | 126 +++++++ Lab3Form/Lab3Form.csproj | 18 +- Lab3Form/Program.cs | 23 +- .../BusinessLogics/FormatLogic.cs | 87 +++++ .../BusinessLogics/StudentLogic.cs | 88 +++++ .../StudentPerformanceBusinessLogic.csproj | 15 + .../BindingModels/FormatBindingModel.cs | 15 + .../BindingModels/StudentBindingModel.cs | 15 + .../BusinessLogicContracts/IFormatLogic.cs | 20 ++ .../BusinessLogicContracts/IStudentLogic.cs | 20 ++ .../SearchModels/FormatSearchModel.cs | 13 + .../SearchModels/StudentSearchModel.cs | 13 + .../StorageContracts/IFormatStorage.cs | 21 ++ .../StorageContracts/IStudentStorage.cs | 21 ++ .../StudentPerformanceContracts.csproj | 13 + .../ViewModels/FormatViewModel.cs | 17 + .../ViewModels/StudentExcelViewModel.cs | 29 ++ .../ViewModels/StudentViewModel.cs | 28 ++ StudentPerformanceDataModels/IId.cs | 7 + .../Models/IFormatModel.cs | 13 + .../Models/IStudentModel.cs | 23 ++ .../StudentPerformanceDataModels.csproj | 9 + .../Implements/FormatStorage.cs | 79 ++++ .../Implements/StudentStorage.cs | 87 +++++ .../20241112171255_InitialCreate.Designer.cs | 88 +++++ .../20241112171255_InitialCreate.cs | 67 ++++ .../StudentsDatabaseModelSnapshot.cs | 85 +++++ .../Models/Formats.cs | 54 +++ .../Models/Students.cs | 67 ++++ ...StudentPerformanceDatabaseImplement.csproj | 23 ++ .../StudentsDatabase.cs | 20 ++ 44 files changed, 2518 insertions(+), 19 deletions(-) create mode 100644 Lab3Form/FormFormats.Designer.cs create mode 100644 Lab3Form/FormFormats.cs create mode 100644 Lab3Form/FormFormats.resx create mode 100644 Lab3Form/FormMain.Designer.cs create mode 100644 Lab3Form/FormMain.cs create mode 100644 Lab3Form/FormMain.resx create mode 100644 Lab3Form/FormStudent.Designer.cs create mode 100644 Lab3Form/FormStudent.cs create mode 100644 Lab3Form/FormStudent.resx create mode 100644 StudentPerformanceBusinessLogic/BusinessLogics/FormatLogic.cs create mode 100644 StudentPerformanceBusinessLogic/BusinessLogics/StudentLogic.cs create mode 100644 StudentPerformanceBusinessLogic/StudentPerformanceBusinessLogic.csproj create mode 100644 StudentPerformanceContracts/BindingModels/FormatBindingModel.cs create mode 100644 StudentPerformanceContracts/BindingModels/StudentBindingModel.cs create mode 100644 StudentPerformanceContracts/BusinessLogicContracts/IFormatLogic.cs create mode 100644 StudentPerformanceContracts/BusinessLogicContracts/IStudentLogic.cs create mode 100644 StudentPerformanceContracts/SearchModels/FormatSearchModel.cs create mode 100644 StudentPerformanceContracts/SearchModels/StudentSearchModel.cs create mode 100644 StudentPerformanceContracts/StorageContracts/IFormatStorage.cs create mode 100644 StudentPerformanceContracts/StorageContracts/IStudentStorage.cs create mode 100644 StudentPerformanceContracts/StudentPerformanceContracts.csproj create mode 100644 StudentPerformanceContracts/ViewModels/FormatViewModel.cs create mode 100644 StudentPerformanceContracts/ViewModels/StudentExcelViewModel.cs create mode 100644 StudentPerformanceContracts/ViewModels/StudentViewModel.cs create mode 100644 StudentPerformanceDataModels/IId.cs create mode 100644 StudentPerformanceDataModels/Models/IFormatModel.cs create mode 100644 StudentPerformanceDataModels/Models/IStudentModel.cs create mode 100644 StudentPerformanceDataModels/StudentPerformanceDataModels.csproj create mode 100644 StudentPerformanceDatabaseImplement/Implements/FormatStorage.cs create mode 100644 StudentPerformanceDatabaseImplement/Implements/StudentStorage.cs create mode 100644 StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.Designer.cs create mode 100644 StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.cs create mode 100644 StudentPerformanceDatabaseImplement/Migrations/StudentsDatabaseModelSnapshot.cs create mode 100644 StudentPerformanceDatabaseImplement/Models/Formats.cs create mode 100644 StudentPerformanceDatabaseImplement/Models/Students.cs create mode 100644 StudentPerformanceDatabaseImplement/StudentPerformanceDatabaseImplement.csproj create mode 100644 StudentPerformanceDatabaseImplement/StudentsDatabase.cs diff --git a/FormLibrary/FormLibrary.csproj b/FormLibrary/FormLibrary.csproj index 5b8f88d..83fba9c 100644 --- a/FormLibrary/FormLibrary.csproj +++ b/FormLibrary/FormLibrary.csproj @@ -1,7 +1,7 @@  - net8.0-windows + net6.0-windows enable true enable diff --git a/Forms/Forms.csproj b/Forms/Forms.csproj index 07a9ca3..31cdb8c 100644 --- a/Forms/Forms.csproj +++ b/Forms/Forms.csproj @@ -9,7 +9,7 @@ - + \ No newline at end of file diff --git a/KopLab1.sln b/KopLab1.sln index 5506f5f..48f76b1 100644 --- a/KopLab1.sln +++ b/KopLab1.sln @@ -3,9 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.11.35222.181 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormLibrary", "FormLibrary\FormLibrary.csproj", "{E840E4D9-B195-449A-AB24-ECAAE2655D58}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StudentPerformanceBusinessLogic", "StudentPerformanceBusinessLogic\StudentPerformanceBusinessLogic.csproj", "{0A1F54AD-49A1-420C-B8D1-049D8DA1E0D7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Forms", "Forms\Forms.csproj", "{83F3C50D-D872-48B6-8932-1D5B7E0A40F0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StudentPerformanceDataModels", "StudentPerformanceDataModels\StudentPerformanceDataModels.csproj", "{632322C2-D69C-40AD-A503-E85326249916}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StudentPerformanceContracts", "StudentPerformanceContracts\StudentPerformanceContracts.csproj", "{3BD4CC4F-A1BB-42BE-87AE-1D1E17AE165D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StudentPerformanceDatabaseImplement", "StudentPerformanceDatabaseImplement\StudentPerformanceDatabaseImplement.csproj", "{D894595F-CBC4-4D43-8E81-0A2B5B43FCF5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lab3Form", "..\..\..\Downloads\KOP_PIbd-33_Volkov_N.A._Tikhonenkov_A.E.-Lab3_Tikhonenkov\kop_pibd-33_volkov_n.a._tikhonenkov_a.e\KopLab1\Lab3Form\Lab3Form.csproj", "{015AA962-A1EB-4EC0-9585-3AE294E62953}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -13,14 +19,26 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E840E4D9-B195-449A-AB24-ECAAE2655D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E840E4D9-B195-449A-AB24-ECAAE2655D58}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E840E4D9-B195-449A-AB24-ECAAE2655D58}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E840E4D9-B195-449A-AB24-ECAAE2655D58}.Release|Any CPU.Build.0 = Release|Any CPU - {83F3C50D-D872-48B6-8932-1D5B7E0A40F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {83F3C50D-D872-48B6-8932-1D5B7E0A40F0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {83F3C50D-D872-48B6-8932-1D5B7E0A40F0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83F3C50D-D872-48B6-8932-1D5B7E0A40F0}.Release|Any CPU.Build.0 = Release|Any CPU + {0A1F54AD-49A1-420C-B8D1-049D8DA1E0D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A1F54AD-49A1-420C-B8D1-049D8DA1E0D7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A1F54AD-49A1-420C-B8D1-049D8DA1E0D7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A1F54AD-49A1-420C-B8D1-049D8DA1E0D7}.Release|Any CPU.Build.0 = Release|Any CPU + {632322C2-D69C-40AD-A503-E85326249916}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {632322C2-D69C-40AD-A503-E85326249916}.Debug|Any CPU.Build.0 = Debug|Any CPU + {632322C2-D69C-40AD-A503-E85326249916}.Release|Any CPU.ActiveCfg = Release|Any CPU + {632322C2-D69C-40AD-A503-E85326249916}.Release|Any CPU.Build.0 = Release|Any CPU + {3BD4CC4F-A1BB-42BE-87AE-1D1E17AE165D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3BD4CC4F-A1BB-42BE-87AE-1D1E17AE165D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3BD4CC4F-A1BB-42BE-87AE-1D1E17AE165D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3BD4CC4F-A1BB-42BE-87AE-1D1E17AE165D}.Release|Any CPU.Build.0 = Release|Any CPU + {D894595F-CBC4-4D43-8E81-0A2B5B43FCF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D894595F-CBC4-4D43-8E81-0A2B5B43FCF5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D894595F-CBC4-4D43-8E81-0A2B5B43FCF5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D894595F-CBC4-4D43-8E81-0A2B5B43FCF5}.Release|Any CPU.Build.0 = Release|Any CPU + {015AA962-A1EB-4EC0-9585-3AE294E62953}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {015AA962-A1EB-4EC0-9585-3AE294E62953}.Debug|Any CPU.Build.0 = Debug|Any CPU + {015AA962-A1EB-4EC0-9585-3AE294E62953}.Release|Any CPU.ActiveCfg = Release|Any CPU + {015AA962-A1EB-4EC0-9585-3AE294E62953}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Lab3Form/Form1.Designer.cs b/Lab3Form/Form1.Designer.cs index f31dfe0..5ac1a97 100644 --- a/Lab3Form/Form1.Designer.cs +++ b/Lab3Form/Form1.Designer.cs @@ -3,12 +3,12 @@ partial class Form1 { /// - /// Required designer variable. + /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// - /// Clean up any resources being used. + /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) @@ -23,8 +23,8 @@ #region Windows Form Designer generated code /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. /// private void InitializeComponent() { @@ -36,4 +36,4 @@ #endregion } -} +} \ No newline at end of file diff --git a/Lab3Form/Form1.cs b/Lab3Form/Form1.cs index a501de7..392e399 100644 --- a/Lab3Form/Form1.cs +++ b/Lab3Form/Form1.cs @@ -1,3 +1,23 @@ +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 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 Lab3Form { public partial class Form1 : Form diff --git a/Lab3Form/FormFormats.Designer.cs b/Lab3Form/FormFormats.Designer.cs new file mode 100644 index 0000000..772bbf5 --- /dev/null +++ b/Lab3Form/FormFormats.Designer.cs @@ -0,0 +1,84 @@ +namespace Lab3Form +{ + partial class FormFormats + { + /// + /// 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(); + NameCol = new DataGridViewTextBoxColumn(); + Id = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { NameCol, Id }); + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 47; + dataGridView.Size = new Size(800, 356); + dataGridView.TabIndex = 0; + dataGridView.CellValueChanged += dataGridView_CellValueChanged; + dataGridView.UserDeletingRow += dataGridView_UserDeletingRow; + dataGridView.KeyUp += dataGridView_KeyUp; + // + // NameCol + // + NameCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + NameCol.HeaderText = "Название товара"; + NameCol.MinimumWidth = 6; + NameCol.Name = "NameCol"; + // + // Id + // + Id.HeaderText = "Id"; + Id.MinimumWidth = 6; + Id.Name = "Id"; + Id.Visible = false; + Id.Width = 125; + // + // Formcitys + // + AutoScaleDimensions = new SizeF(8F, 19F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 356); + Controls.Add(dataGridView); + Name = "Formcitys"; + Text = "Выбранные товары"; + Load += Formcitys_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private DataGridViewTextBoxColumn NameCol; + private DataGridViewTextBoxColumn Id; + } +} \ No newline at end of file diff --git a/Lab3Form/FormFormats.cs b/Lab3Form/FormFormats.cs new file mode 100644 index 0000000..3f3777b --- /dev/null +++ b/Lab3Form/FormFormats.cs @@ -0,0 +1,106 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.BusinessLogicContracts; +using Microsoft.EntityFrameworkCore.Diagnostics; +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 Lab3Form +{ + public partial class FormFormats : Form + { + private readonly IFormatLogic _logic; + private bool loading = false; + + public FormFormats(IFormatLogic logic) + { + InitializeComponent(); + _logic = logic; + } + + private void LoadData() + { + loading = true; + try + { + var list = _logic.ReadList(null); + if (list != null) + { + foreach (var city in list) + { + int rowIndex = dataGridView.Rows.Add(); + dataGridView.Rows[rowIndex].Cells[0].Value = city.Name; + dataGridView.Rows[rowIndex].Cells[1].Value = city.Id; + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + finally + { + loading = false; + } + } + + private void Formcitys_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) + { + if (loading || e.RowIndex < 0 || e.ColumnIndex != 0) return; + if (dataGridView.Rows[e.RowIndex].Cells[1].Value != null && !string.IsNullOrEmpty(dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString())) + { + var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + if (name is null) return; + _logic.Update(new FormatBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), Name = name.ToString() }); + } + else + { + var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + if (name is null) return; + _logic.Create(new FormatBindingModel { Id = 0, Name = name.ToString() }); + int newInterestId = _logic.ReadList(null).ToList().Last().Id; + dataGridView.Rows[e.RowIndex].Cells[1].Value = newInterestId; + } + } + + private void dataGridView_KeyUp(object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Insert: + dataGridView.Rows.Add(); + break; + } + } + + private void deleteRows(DataGridViewSelectedRowCollection rows) + { + for (int i = 0; i < rows.Count; i++) + { + DataGridViewRow row = rows[i]; + if (!_logic.Delete(new FormatBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) })) continue; + } + dataGridView.Rows.Clear(); + LoadData(); + } + + private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) + { + e.Cancel = true; + if (dataGridView.SelectedRows == null) return; + if (MessageBox.Show("Удалить записи?", "Подтвердите действие", MessageBoxButtons.YesNo) == DialogResult.No) return; + deleteRows(dataGridView.SelectedRows); + } + } +} diff --git a/Lab3Form/FormFormats.resx b/Lab3Form/FormFormats.resx new file mode 100644 index 0000000..d012256 --- /dev/null +++ b/Lab3Form/FormFormats.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + \ No newline at end of file diff --git a/Lab3Form/FormMain.Designer.cs b/Lab3Form/FormMain.Designer.cs new file mode 100644 index 0000000..d8f75ae --- /dev/null +++ b/Lab3Form/FormMain.Designer.cs @@ -0,0 +1,175 @@ +namespace Lab3Form +{ + 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. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + menuStrip = new MenuStrip(); + заказыToolStripMenuItem = new ToolStripMenuItem(); + создатьToolStripMenuItem = new ToolStripMenuItem(); + редактироватьToolStripMenuItem = new ToolStripMenuItem(); + удалитьToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + документToolStripMenuItem = new ToolStripMenuItem(); + документСТаблицейToolStripMenuItem = new ToolStripMenuItem(); + документСДиаграммойToolStripMenuItem = new ToolStripMenuItem(); + выбранныеТоварыToolStripMenuItem = new ToolStripMenuItem(); + /* controlDataTable = new ControlsLibraryNet60.Data.ControlDataTableTable();*/ + pdfTable1 = new FormLibrary.PDFTable(components); + excelTableComponent1 = new WinFormsLibraryVolkov.NonVisualComponents.ExcelTableComponent(components); + /*componentDocumentWithChartLineWord1 = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartLineWord(components);*/ + menuStrip.SuspendLayout(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(18, 18); + menuStrip.Items.AddRange(new ToolStripItem[] { заказыToolStripMenuItem, отчётыToolStripMenuItem, выбранныеТоварыToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Padding = new Padding(5, 2, 0, 2); + menuStrip.Size = new Size(853, 24); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip"; + // + // заказыToolStripMenuItem + // + заказыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { создатьToolStripMenuItem, редактироватьToolStripMenuItem, удалитьToolStripMenuItem }); + заказыToolStripMenuItem.Name = "заказыToolStripMenuItem"; + заказыToolStripMenuItem.Size = new Size(58, 20); + заказыToolStripMenuItem.Text = "Заказы"; + // + // создатьToolStripMenuItem + // + создатьToolStripMenuItem.Name = "создатьToolStripMenuItem"; + создатьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.A; + создатьToolStripMenuItem.Size = new Size(196, 22); + создатьToolStripMenuItem.Text = "Создать"; + создатьToolStripMenuItem.Click += создатьToolStripMenuItem_Click; + // + // редактироватьToolStripMenuItem + // + редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem"; + редактироватьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U; + редактироватьToolStripMenuItem.Size = new Size(196, 22); + редактироватьToolStripMenuItem.Text = "Редактировать"; + редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click; + // + // удалитьToolStripMenuItem + // + удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem"; + удалитьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.D; + удалитьToolStripMenuItem.Size = new Size(196, 22); + удалитьToolStripMenuItem.Text = "Удалить"; + удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { документToolStripMenuItem, документСТаблицейToolStripMenuItem, документСДиаграммойToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(60, 20); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // документToolStripMenuItem + // + документToolStripMenuItem.Name = "документToolStripMenuItem"; + документToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + документToolStripMenuItem.Size = new Size(309, 22); + документToolStripMenuItem.Text = "Документ с простой таблицей"; + документToolStripMenuItem.Click += GeneratePdfButton_Click; + // + // документСТаблицейToolStripMenuItem + // + документСТаблицейToolStripMenuItem.Name = "документСТаблицейToolStripMenuItem"; + документСТаблицейToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; + документСТаблицейToolStripMenuItem.Size = new Size(309, 22); + документСТаблицейToolStripMenuItem.Text = "Отчет по всем заказам Excel"; + документСТаблицейToolStripMenuItem.Click += buttonCreateOrderReport_Click; + // + // документСДиаграммойToolStripMenuItem + // + документСДиаграммойToolStripMenuItem.Name = "документСДиаграммойToolStripMenuItem"; + документСДиаграммойToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; + документСДиаграммойToolStripMenuItem.Size = new Size(309, 22); + документСДиаграммойToolStripMenuItem.Text = "Документ с линейной диаграммой"; + документСДиаграммойToolStripMenuItem.Click += CreateDocumentButton_Click; + // + // выбранныеТоварыToolStripMenuItem + // + выбранныеТоварыToolStripMenuItem.Name = "выбранныеТоварыToolStripMenuItem"; + выбранныеТоварыToolStripMenuItem.Size = new Size(125, 20); + выбранныеТоварыToolStripMenuItem.Text = "Города назначения"; + выбранныеТоварыToolStripMenuItem.Click += выбранныеТоварыToolStripMenuItem_Click; + // + // controlDataTable + // + controlDataTable.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + controlDataTable.AutoSize = true; + controlDataTable.Location = new Point(0, 24); + controlDataTable.Margin = new Padding(4, 3, 4, 3); + controlDataTable.Name = "controlDataTable"; + controlDataTable.SelectedRowIndex = -1; + controlDataTable.Size = new Size(853, 419); + controlDataTable.TabIndex = 1; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(853, 442); + Controls.Add(controlDataTable); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Margin = new Padding(3, 2, 3, 2); + Name = "FormMain"; + Text = "Заказы"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private MenuStrip menuStrip; + private ToolStripMenuItem заказыToolStripMenuItem; + private ToolStripMenuItem создатьToolStripMenuItem; + private ToolStripMenuItem редактироватьToolStripMenuItem; + private ToolStripMenuItem удалитьToolStripMenuItem; + private ToolStripMenuItem отчётыToolStripMenuItem; + private ToolStripMenuItem документToolStripMenuItem; + private ToolStripMenuItem документСТаблицейToolStripMenuItem; + private ToolStripMenuItem выбранныеТоварыToolStripMenuItem; + private ToolStripMenuItem документСДиаграммойToolStripMenuItem; + private ControlsLibraryNet60.Data.ControlDataTableTable controlDataTable; + private FormLibrary.PDFTable pdfTable1; + private WinFormsLibraryVolkov.NonVisualComponents.ExcelTableComponent excelTableComponent1; + private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartLineWord componentDocumentWithChartLineWord1; + } +} \ No newline at end of file diff --git a/Lab3Form/FormMain.cs b/Lab3Form/FormMain.cs new file mode 100644 index 0000000..c5a4379 --- /dev/null +++ b/Lab3Form/FormMain.cs @@ -0,0 +1,338 @@ +using StudentPerformanceBusinessLogic.BusinessLogics; +using StudentPerformanceContracts.BusinessLogicContracts; +using StudentPerformanceContracts.ViewModels; +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using ControlsLibraryNet60.Models; +using Microsoft.EntityFrameworkCore.Diagnostics; +using WinFormsLibraryZhirnova.NonVisualComponents; +using ComponentsLibraryNet60.Core; +using ComponentsLibraryNet60.DocumentWithTable; +using ComponentsLibraryNet60.Models; +using FormLibrary.HelperClasses; +using FormLibrary; +using ComponentsLibraryNet60.DocumentWithChart; +using System.Text; + +namespace Lab3Form +{ + public partial class FormMain : Form + { + private IStudentLogic _logic; + + public FormMain(IStudentLogic logic) + { + controlDataTable.LoadColumns(new List + { + new DataTableColumnConfig { ColumnHeader = "Идентификатор", PropertyName = "Id", Visible = true, Width = 100 }, + new DataTableColumnConfig { ColumnHeader = "ФИО заказчика", PropertyName = "Fullname", Visible = true, Width = 200 }, + new DataTableColumnConfig { ColumnHeader = "Город назначения", PropertyName = "DestinationCityName", Visible = true, Width = 150 }, + new DataTableColumnConfig { ColumnHeader = "История передвижения", PropertyName = "OrderStatusHistory", Visible = true, Width = 250 }, + new DataTableColumnConfig { ColumnHeader = "Дата выдачи", PropertyName = "ExpectedDeliveryDate", Visible = true, Width = 125 }, + }); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + InitializeComponent(); + _logic = logic; + } + + private void LoadData() + { + controlDataTable.Clear(); + var orders = _logic.ReadList(null); + if (orders != null) + { + var displayOrders = orders.Select(order => new + { + order.Id, + order.Fullname, + order.Format, + AverageScore = string.Join(", ", order.AverageScore), + order.AdmissionDate + }).ToList(); + controlDataTable.AddTable(displayOrders); + } + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void создатьToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormStudent)); + if (service is FormStudent form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormStudent)); + if (service is FormStudent form) + { + form._id = controlDataTable.GetSelectedObject().Id; + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void удалитьToolStripMenuItem_Click(object sender, EventArgs e) + { + var selectedOrder = controlDataTable.GetSelectedObject(); + if (selectedOrder == null) + { + MessageBox.Show("Не выбрана запись для удаления."); + return; + } + if (MessageBox.Show("Удалить запись?", "", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + var isDeleted = _logic.Delete(new StudentBindingModel { Id = selectedOrder.Id ?? 0 }); + if (isDeleted) + { + LoadData(); + MessageBox.Show("Запись успешно удалена."); + } + else + { + MessageBox.Show("Ошибка при удалении записи."); + } + } + } + + private void GeneratePdfButton_Click(object sender, EventArgs e) + { + try + { + + var orders = _logic.ReadList(null); + + + var orderTables = new List(); + + foreach (var order in orders) + { + + int rowCount = order.AverageScore.Count; + + + string[,] orderTable = new string[rowCount+1, 4]; + + + orderTable[0, 0] = "Средний балл по сессии"; + orderTable[0, 1] = "Идентификатор студента"; + orderTable[0, 2] = "Форма обучения"; + orderTable[0, 3] = "Дата поступления"; + + + for (int i = 0; i < rowCount; i++) + { + orderTable[i+1, 0] = order.AverageScore[i]; + orderTable[i+1, 1] = order.Id.ToString(); + orderTable[i+1, 2] = order.Format; + orderTable[i+1, 3] = order.AdmissionDate.ToString("yyyy-MM-dd"); + } + + + orderTables.Add(orderTable); + } + + + using (System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog()) + { + saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"; + saveFileDialog.Title = "Сохранить PDF-документ"; + saveFileDialog.FileName = "Отчет1.pdf"; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + + var pdfData = new PdfDocumentData( + saveFileDialog.FileName, + "Отчет по студентам", + orderTables + ); + + var documentGenerator = new PDFTable(); + documentGenerator.GeneratePdf(pdfData); + + MessageBox.Show("PDF-документ успешно создан!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + catch (Exception ex) + { + MessageBox.Show($"Произошла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCreateOrderReport_Click(object sender, EventArgs e) + { + + var orders = _logic.ReadList(null); + if (orders == null || orders.Count == 0) + { + MessageBox.Show("Нет заказов для отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + + var tableData = new List(); + foreach (var order in orders) + { + if (order != null) + { + tableData.Add(new StudentExcelViewModel( + order.Id, + order.Fullname, + order.Format, + order.AdmissionDate + )); + } + } + string path = AppDomain.CurrentDomain.BaseDirectory + "OrderReport.xlsx"; + + using (System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog()) + { + saveFileDialog.Title = "Сохранить Excel-документ"; + saveFileDialog.FileName = "Отчет2.xlsx"; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + path = saveFileDialog.FileName; + + MessageBox.Show("Excel-документ успешно создан!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + + List<(int, int)> merges = new List<(int, int)> + { + (0,1), + (2, 3) + }; + + List heights = Enumerable.Repeat(20, 4).ToList(); + + + List<(string, string)> headers = new List<(string, string)> + { + + ("","Данные"), + ("Id", "Идентификатор"), + ("Fullname", "ФИО студента"), + ("", "Студент"), + ("Format", "Форма обучения"), + ("AdmissionDate", "Дата поступления") + }; + + if (merges.Count == 0 || heights.Count == 0 || headers.Count == 0 || tableData.Count == 0) + { + MessageBox.Show("Недостаточно данных для создания отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + Console.WriteLine($"Merges Count: {merges.Count}"); + Console.WriteLine($"Heights Count: {heights.Count}"); + Console.WriteLine($"Headers Count: {headers.Count}"); + Console.WriteLine($"TableData Count: {tableData.Count}"); + if (excelTableComponent1.createWithTable(path, "Отчет по студентам", merges, heights, headers, tableData)) + { + MessageBox.Show("Отчет успешно создан!"); + } + else + { + MessageBox.Show("Ошибка при создании отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + + private void CreateDocumentButton_Click(object sender, EventArgs e) + { + + var orders = _logic.ReadList(null).Cast().ToList(); + + + var chartData = new Dictionary>(); + + foreach (var order in orders) + { + if (!chartData.ContainsKey(order.Format)) + { + chartData[order.Format] = new List<(DateTime Date, int Count)>(); + } + + + var existingData = chartData[order.Format] + .FirstOrDefault(d => d.Date.Date == order.AdmissionDate.Date); + + if (existingData.Date == default) + { + chartData[order.Format].Add((order.AdmissionDate.Date, 1)); + } + else + { + + int index = chartData[order.Format].FindIndex(d => d.Date.Date == order.AdmissionDate.Date); + var updatedValue = chartData[order.Format][index]; + chartData[order.Format][index] = (updatedValue.Date, updatedValue.Count + 1); + } + } + + string filePath = "Отчет3.docx"; + + using (System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog()) + { + saveFileDialog.Title = "Сохранить Word-документ"; + saveFileDialog.FileName = "Отчет3.docx"; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + filePath = saveFileDialog.FileName; + + MessageBox.Show("Docx-документ успешно создан!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + var config = new ComponentDocumentWithChartConfig + { + ChartTitle = "Отчет по заказам", + LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom, + Data = chartData.ToDictionary( + entry => entry.Key, + entry => entry.Value.Select(d => (DateTimeToInt(d.Date), (double)d.Count)).ToList()), + FilePath = filePath, + Header = "Заголовок отчета" + + }; + + + var documentComponent = new ComponentDocumentWithChartLineWord(); + + + documentComponent.CreateDoc(config); + + MessageBox.Show("Документ создан успешно!"); + } + private int DateTimeToInt(DateTime date) + { + return date.Day; + } + + + private void выбранныеТоварыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormFormats)); + if (service is FormFormats form) + { + form.ShowDialog(); + } + } + } +} diff --git a/Lab3Form/FormMain.resx b/Lab3Form/FormMain.resx new file mode 100644 index 0000000..6f2a6fb --- /dev/null +++ b/Lab3Form/FormMain.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 126, 17 + + + 231, 17 + + + 409, 17 + + + 177 + + \ No newline at end of file diff --git a/Lab3Form/FormStudent.Designer.cs b/Lab3Form/FormStudent.Designer.cs new file mode 100644 index 0000000..32d6d54 --- /dev/null +++ b/Lab3Form/FormStudent.Designer.cs @@ -0,0 +1,177 @@ +namespace Lab3Form +{ + partial class FormStudent + { + /// + /// 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() + { + labelFIO = new Label(); + textBoxFIO = new TextBox(); + labelcity = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + openFileDialog = new OpenFileDialog(); + label1 = new Label(); + label2 = new Label(); + customListBox1 = new FormLibrary.CustomListBox(); + customInputRangeDate1 = new WinFormsLibraryVolkov.CustomInputRangeDate(); + listBox1 = new ListBox(); + SuspendLayout(); + // + // labelFIO + // + labelFIO.AutoSize = true; + labelFIO.Location = new Point(10, 7); + labelFIO.Name = "labelFIO"; + labelFIO.Size = new Size(91, 15); + labelFIO.TabIndex = 0; + labelFIO.Text = "ФИО заказчика"; + // + // textBoxFIO + // + textBoxFIO.Location = new Point(10, 24); + textBoxFIO.Margin = new Padding(3, 2, 3, 2); + textBoxFIO.Name = "textBoxFIO"; + textBoxFIO.Size = new Size(241, 23); + textBoxFIO.TabIndex = 1; + // + // labelcity + // + labelcity.AutoSize = true; + labelcity.Location = new Point(10, 62); + labelcity.Name = "labelcity"; + labelcity.Size = new Size(107, 15); + labelcity.TabIndex = 4; + labelcity.Text = "Город назначения"; + // + // buttonCancel + // + buttonCancel.Location = new Point(161, 414); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(83, 21); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отменить"; + buttonCancel.UseVisualStyleBackColor = true; + // + // buttonSave + // + buttonSave.Location = new Point(7, 414); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(94, 21); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // openFileDialog + // + openFileDialog.FileName = "openFileDialog"; + openFileDialog.Multiselect = true; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(10, 360); + label1.Name = "label1"; + label1.Size = new Size(132, 15); + label1.TabIndex = 10; + label1.Text = "Дата получения заказа"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(10, 264); + label2.Name = "label2"; + label2.Size = new Size(123, 15); + label2.TabIndex = 12; + label2.Text = "Точки передвижения"; + // + // customListBox1 + // + customListBox1.Location = new Point(10, 80); + customListBox1.Name = "customListBox1"; + customListBox1.SelectedItem = ""; + customListBox1.Size = new Size(237, 179); + customListBox1.TabIndex = 17; + // + // customInputRangeDate1 + // + customInputRangeDate1.Location = new Point(10, 378); + customInputRangeDate1.MaxDate = new DateTime(0L); + customInputRangeDate1.MinDate = new DateTime(0L); + customInputRangeDate1.Name = "customInputRangeDate1"; + customInputRangeDate1.Size = new Size(199, 31); + customInputRangeDate1.TabIndex = 18; + // + // listBox1 + // + listBox1.FormattingEnabled = true; + listBox1.ItemHeight = 15; + listBox1.Location = new Point(13, 282); + listBox1.Name = "listBox1"; + listBox1.SelectionMode = SelectionMode.MultiExtended; + listBox1.Size = new Size(231, 64); + listBox1.TabIndex = 19; + // + // FormOrder + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(256, 459); + Controls.Add(listBox1); + Controls.Add(customInputRangeDate1); + Controls.Add(customListBox1); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(labelcity); + Controls.Add(textBoxFIO); + Controls.Add(labelFIO); + Margin = new Padding(3, 2, 3, 2); + Name = "FormOrder"; + Text = "Заказ"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelFIO; + private TextBox textBoxFIO; + private Label labelcity; + private Button buttonCancel; + private Button buttonSave; + private OpenFileDialog openFileDialog; + private Label label1; + private Label label2; + private FormLibrary.CustomListBox customListBox1; + private WinFormsLibraryZhirnova.CustomInputRangeDate customInputRangeDate1; + private ListBox listBox1; + } +} \ No newline at end of file diff --git a/Lab3Form/FormStudent.cs b/Lab3Form/FormStudent.cs new file mode 100644 index 0000000..0cab516 --- /dev/null +++ b/Lab3Form/FormStudent.cs @@ -0,0 +1,120 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.BusinessLogicContracts; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.ViewModels; +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 Lab3Form +{ + public partial class FormStudent : Form + { + public int? _id; + private readonly IStudentLogic _logic; + private readonly IFormatLogic _formatLogic; + private List _Formats; + public int Id { set { _id = value; } } + + public FormStudent(IStudentLogic logic, IFormatLogic formatLogic) + { + InitializeComponent(); + + _logic = logic; + _formatLogic = formatLogic; + _Formats = new List(); + _Formats = _formatLogic.ReadList(null); + var cityNames = _Formats.Select(city => city.Name).ToList(); + customListBox1.PopulateListBox(cityNames); + var orderStatuses = new List { "Очное", "Заочное", "Очно-заочное", "Дистанционное" }; + listBox1.Items.AddRange(orderStatuses.ToArray()); + DateTime now = DateTime.Now; + customInputRangeDate1.MinDate = now.AddYears(-6); + customInputRangeDate1.MaxDate = now; + this.Load += FormOrder_Load; + } + + private void FormOrder_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + StudentSearchModel searchModel = new StudentSearchModel { Id = _id.Value }; + StudentViewModel orderViewModel = _logic.ReadElement(searchModel); + + if (orderViewModel != null) + { + textBoxFIO.Text = orderViewModel.Fullname; + + FormatViewModel selectedCity = _Formats.FirstOrDefault(city => city.Id == orderViewModel.FormatId); + if (selectedCity != null) + { + customListBox1.SelectedItem = selectedCity.Name; + } + + customInputRangeDate1.Date = orderViewModel.AdmissionDate; + + foreach (string status in orderViewModel.AverageScore) + { + int index = listBox1.Items.IndexOf(status); + if (index != -1) + { + listBox1.SetSelected(index, true); + } + } + } + else + { + MessageBox.Show("Студент с указанным ID не найден.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО студента", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + if (customListBox1.SelectedItem == null) + { + MessageBox.Show("Укажите форму обучения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + try + { + var model = new StudentBindingModel + { + Id = _id ?? 0, + Fullname = textBoxFIO.Text, + FormatId = _Formats.First(x => x.Name == customListBox1.SelectedItem).Id, + AdmissionDate = customInputRangeDate1.Date, + AverageScore = listBox1.SelectedItems.Cast().ToList(), + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Возникла ошибка при сохранении. Дополнительная информация в логах"); + } + MessageBox.Show("Сохранение прошло успешно", "Успешное сохранение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/Lab3Form/FormStudent.resx b/Lab3Form/FormStudent.resx new file mode 100644 index 0000000..68d5403 --- /dev/null +++ b/Lab3Form/FormStudent.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 90 + + \ No newline at end of file diff --git a/Lab3Form/Lab3Form.csproj b/Lab3Form/Lab3Form.csproj index 663fdb8..7c40c75 100644 --- a/Lab3Form/Lab3Form.csproj +++ b/Lab3Form/Lab3Form.csproj @@ -2,10 +2,26 @@ WinExe - net8.0-windows + net8.0-windows7.0 enable true enable + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + \ No newline at end of file diff --git a/Lab3Form/Program.cs b/Lab3Form/Program.cs index 96c8e01..bd6fa4f 100644 --- a/Lab3Form/Program.cs +++ b/Lab3Form/Program.cs @@ -1,7 +1,15 @@ +using Microsoft.Extensions.DependencyInjection; +using StudentPerformanceBusinessLogic.BusinessLogics; +using StudentPerformanceContracts.BusinessLogicContracts; +using StudentPerformanceContracts.StorageContracts; +using StudentPerformanceDatabaseImplement.Implements; + namespace Lab3Form { internal static class Program { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -11,7 +19,20 @@ namespace Lab3Form // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + Application.Run(_serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/StudentPerformanceBusinessLogic/BusinessLogics/FormatLogic.cs b/StudentPerformanceBusinessLogic/BusinessLogics/FormatLogic.cs new file mode 100644 index 0000000..4360b3e --- /dev/null +++ b/StudentPerformanceBusinessLogic/BusinessLogics/FormatLogic.cs @@ -0,0 +1,87 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.BusinessLogicContracts; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.StorageContracts; +using StudentPerformanceContracts.ViewModels; + +namespace StudentPerformanceBusinessLogic.BusinessLogics +{ + public class FormatLogic : IFormatLogic + { + private readonly IFormatStorage _formatStorage; + + public FormatLogic(IFormatStorage formatStorage) + { + _formatStorage = formatStorage; + } + + public List? ReadList(FormatSearchModel? model) + { + var list = model == null ? _formatStorage.GetFullList() : _formatStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public FormatViewModel? ReadElement(FormatSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _formatStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public bool Create(FormatBindingModel model) + { + CheckModel(model); + if (_formatStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Update(FormatBindingModel model) + { + CheckModel(model); + if (_formatStorage.Update(model) == null) + { + return false; + } + return true; + } + public bool Delete(FormatBindingModel model) + { + CheckModel(model, false); + if (_formatStorage.Delete(model) == null) + { + return false; + } + return true; + } + + private void CheckModel(FormatBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentNullException("Нет наименования формата обучения", nameof(model.Name)); + } + } + } +} diff --git a/StudentPerformanceBusinessLogic/BusinessLogics/StudentLogic.cs b/StudentPerformanceBusinessLogic/BusinessLogics/StudentLogic.cs new file mode 100644 index 0000000..fe1b6fe --- /dev/null +++ b/StudentPerformanceBusinessLogic/BusinessLogics/StudentLogic.cs @@ -0,0 +1,88 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.BusinessLogicContracts; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.StorageContracts; +using StudentPerformanceContracts.ViewModels; + +namespace StudentPerformanceBusinessLogic.BusinessLogics +{ + public class StudentLogic : IStudentLogic + { + private readonly IStudentStorage _studentStorage; + + public StudentLogic(IStudentStorage studentStorage) + { + _studentStorage = studentStorage; + } + + public List? ReadList(StudentSearchModel? model) + { + var list = model == null ? _studentStorage.GetFullList() : _studentStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public StudentViewModel? ReadElement(StudentSearchModel? model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _studentStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public bool Create(StudentBindingModel model) + { + CheckModel(model); + if (_studentStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Update(StudentBindingModel model) + { + CheckModel(model); + if (_studentStorage.Update(model) == null) + { + return false; + } + return true; + } + + public bool Delete(StudentBindingModel model) + { + CheckModel(model, false); + if (_studentStorage.Delete(model) == null) + { + return false; + } + return true; + } + + private void CheckModel(StudentBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Fullname)) + { + throw new ArgumentNullException("Нет ФИО студента", nameof(model.Fullname)); + } + } + } +} diff --git a/StudentPerformanceBusinessLogic/StudentPerformanceBusinessLogic.csproj b/StudentPerformanceBusinessLogic/StudentPerformanceBusinessLogic.csproj new file mode 100644 index 0000000..6eccf72 --- /dev/null +++ b/StudentPerformanceBusinessLogic/StudentPerformanceBusinessLogic.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/StudentPerformanceContracts/BindingModels/FormatBindingModel.cs b/StudentPerformanceContracts/BindingModels/FormatBindingModel.cs new file mode 100644 index 0000000..4507a74 --- /dev/null +++ b/StudentPerformanceContracts/BindingModels/FormatBindingModel.cs @@ -0,0 +1,15 @@ +using StudentPerformanceDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.BindingModels +{ + public class FormatBindingModel : IFormatModel + { + public int Id { get; set; } + public string Name { get; set; } = String.Empty; + } +} diff --git a/StudentPerformanceContracts/BindingModels/StudentBindingModel.cs b/StudentPerformanceContracts/BindingModels/StudentBindingModel.cs new file mode 100644 index 0000000..28a6888 --- /dev/null +++ b/StudentPerformanceContracts/BindingModels/StudentBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using StudentPerformanceDataModels.Models; + +namespace StudentPerformanceContracts.BindingModels +{ + public class StudentBindingModel : IStudentModel + { + public int Id { get; set; } + public string Fullname { get; set; } = string.Empty; + public List AverageScore { get; set; } = new List(); + public int FormatId { get; set; } + public DateTime AdmissionDate { get; set; } + } +} diff --git a/StudentPerformanceContracts/BusinessLogicContracts/IFormatLogic.cs b/StudentPerformanceContracts/BusinessLogicContracts/IFormatLogic.cs new file mode 100644 index 0000000..bb430c4 --- /dev/null +++ b/StudentPerformanceContracts/BusinessLogicContracts/IFormatLogic.cs @@ -0,0 +1,20 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.BusinessLogicContracts +{ + public interface IFormatLogic + { + List? ReadList(FormatSearchModel? model); + FormatViewModel? ReadElement(FormatSearchModel model); + bool Create(FormatBindingModel model); + bool Update(FormatBindingModel model); + bool Delete(FormatBindingModel model); + } +} diff --git a/StudentPerformanceContracts/BusinessLogicContracts/IStudentLogic.cs b/StudentPerformanceContracts/BusinessLogicContracts/IStudentLogic.cs new file mode 100644 index 0000000..de7f5fe --- /dev/null +++ b/StudentPerformanceContracts/BusinessLogicContracts/IStudentLogic.cs @@ -0,0 +1,20 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.BusinessLogicContracts +{ + public interface IStudentLogic + { + List? ReadList(StudentSearchModel? model); + StudentViewModel? ReadElement(StudentSearchModel model); + bool Create(StudentBindingModel model); + bool Update(StudentBindingModel model); + bool Delete(StudentBindingModel model); + } +} diff --git a/StudentPerformanceContracts/SearchModels/FormatSearchModel.cs b/StudentPerformanceContracts/SearchModels/FormatSearchModel.cs new file mode 100644 index 0000000..ef17546 --- /dev/null +++ b/StudentPerformanceContracts/SearchModels/FormatSearchModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.SearchModels +{ + public class FormatSearchModel + { + public int? Id { get; set; } + } +} diff --git a/StudentPerformanceContracts/SearchModels/StudentSearchModel.cs b/StudentPerformanceContracts/SearchModels/StudentSearchModel.cs new file mode 100644 index 0000000..4f54d00 --- /dev/null +++ b/StudentPerformanceContracts/SearchModels/StudentSearchModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.SearchModels +{ + public class StudentSearchModel + { + public int? Id { get; set; } + } +} diff --git a/StudentPerformanceContracts/StorageContracts/IFormatStorage.cs b/StudentPerformanceContracts/StorageContracts/IFormatStorage.cs new file mode 100644 index 0000000..f2e6392 --- /dev/null +++ b/StudentPerformanceContracts/StorageContracts/IFormatStorage.cs @@ -0,0 +1,21 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.StorageContracts +{ + public interface IFormatStorage + { + List GetFullList(); + List GetFilteredList(FormatSearchModel model); + FormatViewModel? GetElement(FormatSearchModel model); + FormatViewModel? Insert(FormatBindingModel model); + FormatViewModel? Update(FormatBindingModel model); + FormatViewModel? Delete(FormatBindingModel model); + } +} diff --git a/StudentPerformanceContracts/StorageContracts/IStudentStorage.cs b/StudentPerformanceContracts/StorageContracts/IStudentStorage.cs new file mode 100644 index 0000000..038ce10 --- /dev/null +++ b/StudentPerformanceContracts/StorageContracts/IStudentStorage.cs @@ -0,0 +1,21 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.StorageContracts +{ + public interface IStudentStorage + { + List GetFullList(); + List GetFilteredList(StudentSearchModel model); + StudentViewModel? GetElement(StudentSearchModel model); + StudentViewModel? Insert(StudentBindingModel model); + StudentViewModel? Update(StudentBindingModel model); + StudentViewModel? Delete(StudentBindingModel model); + } +} diff --git a/StudentPerformanceContracts/StudentPerformanceContracts.csproj b/StudentPerformanceContracts/StudentPerformanceContracts.csproj new file mode 100644 index 0000000..3f0f13a --- /dev/null +++ b/StudentPerformanceContracts/StudentPerformanceContracts.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/StudentPerformanceContracts/ViewModels/FormatViewModel.cs b/StudentPerformanceContracts/ViewModels/FormatViewModel.cs new file mode 100644 index 0000000..c53cc9a --- /dev/null +++ b/StudentPerformanceContracts/ViewModels/FormatViewModel.cs @@ -0,0 +1,17 @@ +using StudentPerformanceDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.ViewModels +{ + public class FormatViewModel : IFormatModel + { + public int Id { get; set; } + [DisplayName("Наименование")] + public string Name { get; set; } = string.Empty; + } +} diff --git a/StudentPerformanceContracts/ViewModels/StudentExcelViewModel.cs b/StudentPerformanceContracts/ViewModels/StudentExcelViewModel.cs new file mode 100644 index 0000000..03f7566 --- /dev/null +++ b/StudentPerformanceContracts/ViewModels/StudentExcelViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.ViewModels +{ + public class StudentExcelViewModel + { + public StudentExcelViewModel(int id, string fullname, string format, DateTime admissionDate) + { + this.Id = id; + this.Fullname = fullname; + this.Format = format; + this.AdmissionDate = admissionDate; + } + + public int Id; + public string Fullname; + public string Format; + public DateTime AdmissionDate; + + // Новое свойство для отформатированной строки + public string FormattedAdmissionDate => AdmissionDate.ToString("dd.MM.yyyy HH:mm:ss"); + } + + +} diff --git a/StudentPerformanceContracts/ViewModels/StudentViewModel.cs b/StudentPerformanceContracts/ViewModels/StudentViewModel.cs new file mode 100644 index 0000000..236411d --- /dev/null +++ b/StudentPerformanceContracts/ViewModels/StudentViewModel.cs @@ -0,0 +1,28 @@ +using StudentPerformanceDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceContracts.ViewModels +{ + public class StudentViewModel : IStudentModel + { + public int Id { get; set; } + + [DisplayName("ФИО студента")] + public string Fullname { get; set; } = string.Empty; + + [DisplayName("Средний балл по сессии")] + public List AverageScore { get; set; } + + public int FormatId { get; set; } + [DisplayName("Форма обучения")] + public string Format { get; set; } + + [DisplayName("Дата ппоступления")] + public DateTime AdmissionDate { get; set; } + } +} diff --git a/StudentPerformanceDataModels/IId.cs b/StudentPerformanceDataModels/IId.cs new file mode 100644 index 0000000..dfecc6a --- /dev/null +++ b/StudentPerformanceDataModels/IId.cs @@ -0,0 +1,7 @@ +namespace StudentPerformanceDataModels +{ + public interface IId + { + int Id { get; } + } +} diff --git a/StudentPerformanceDataModels/Models/IFormatModel.cs b/StudentPerformanceDataModels/Models/IFormatModel.cs new file mode 100644 index 0000000..82a72fb --- /dev/null +++ b/StudentPerformanceDataModels/Models/IFormatModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceDataModels.Models +{ + public interface IFormatModel : IId + { + string Name { get; } + } +} diff --git a/StudentPerformanceDataModels/Models/IStudentModel.cs b/StudentPerformanceDataModels/Models/IStudentModel.cs new file mode 100644 index 0000000..93ef013 --- /dev/null +++ b/StudentPerformanceDataModels/Models/IStudentModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceDataModels.Models +{ + public interface IStudentModel : IId + { + // Полное имя студента + string Fullname { get; } + + // Средний балл по сессии (не более 6 сессий) + List AverageScore { get; } + + // Формат обучения + int FormatId { get; } + + // Дата поступления + DateTime AdmissionDate { get; } + } +} diff --git a/StudentPerformanceDataModels/StudentPerformanceDataModels.csproj b/StudentPerformanceDataModels/StudentPerformanceDataModels.csproj new file mode 100644 index 0000000..fa71b7a --- /dev/null +++ b/StudentPerformanceDataModels/StudentPerformanceDataModels.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/StudentPerformanceDatabaseImplement/Implements/FormatStorage.cs b/StudentPerformanceDatabaseImplement/Implements/FormatStorage.cs new file mode 100644 index 0000000..092b586 --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Implements/FormatStorage.cs @@ -0,0 +1,79 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.StorageContracts; +using StudentPerformanceContracts.ViewModels; +using StudentPerformanceDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace StudentPerformanceDatabaseImplement.Implements +{ + public class FormatStorage : IFormatStorage + { + public List GetFullList() + { + using var context = new StudentsDatabase(); + return context.Formats + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(FormatSearchModel model) + { + if (!model.Id.HasValue) + { + return new(); + } + using var context = new StudentsDatabase(); + return context.Formats + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + public FormatViewModel? GetElement(FormatSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + using var context = new StudentsDatabase(); + return context.Formats + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + public FormatViewModel? Insert(FormatBindingModel model) + { + var newcity = Formats.Create(model); + if (newcity == null) + { + return null; + } + using var context = new StudentsDatabase(); + context.Formats.Add(newcity); + context.SaveChanges(); + return newcity.GetViewModel; + } + public FormatViewModel? Update(FormatBindingModel model) + { + using var context = new StudentsDatabase(); + var component = context.Formats.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + public FormatViewModel? Delete(FormatBindingModel model) + { + using var context = new StudentsDatabase(); + var element = context.Formats.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Formats.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/StudentPerformanceDatabaseImplement/Implements/StudentStorage.cs b/StudentPerformanceDatabaseImplement/Implements/StudentStorage.cs new file mode 100644 index 0000000..f983c31 --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Implements/StudentStorage.cs @@ -0,0 +1,87 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.SearchModels; +using StudentPerformanceContracts.StorageContracts; +using StudentPerformanceContracts.ViewModels; +using StudentPerformanceDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using System.Security.Principal; + +namespace StudentPerformanceDatabaseImplement.Implements +{ + public class StudentStorage : IStudentStorage + { + public List GetFullList() + { + using var context = new StudentsDatabase(); + return context.Students + .Include(x => x.Format) + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(StudentSearchModel model) + { + if (!model.Id.HasValue) + { + return new(); + } + + using var context = new StudentsDatabase(); + return context.Students + .Include(x => x.Format) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + public StudentViewModel? GetElement(StudentSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + + using var context = new StudentsDatabase(); + return context.Students + .Include(x => x.Format) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public StudentViewModel? Insert(StudentBindingModel model) + { + using var context = new StudentsDatabase(); + var newOrder = Students.Create(context, model); + if (newOrder == null) + { + return null; + } + context.Students.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } + public StudentViewModel? Update(StudentBindingModel model) + { + using var context = new StudentsDatabase(); + var Order = context.Students.FirstOrDefault(x => x.Id == model.Id); + if (Order == null) + { + return null; + } + Order.Update(model, context); + context.SaveChanges(); + return Order.GetViewModel; + } + public StudentViewModel? Delete(StudentBindingModel model) + { + using var context = new StudentsDatabase(); + var element = context.Students + .Include(x => x.Format) + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Students.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.Designer.cs b/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.Designer.cs new file mode 100644 index 0000000..a15e1fa --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.Designer.cs @@ -0,0 +1,88 @@ +// +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using StudentPerformanceDatabaseImplement; + +#nullable disable + +namespace StudentPerformanceDatabaseImplement.Migrations +{ + [DbContext(typeof(StudentsDatabase))] + [Migration("20241112171255_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Formats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Formats"); + }); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Students", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdmissionDate") + .HasColumnType("timestamp with time zone"); + + b.Property>("AverageScore") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("FormatId") + .HasColumnType("integer"); + + b.Property("Fullname") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("FormatId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Students", b => + { + b.HasOne("StudentPerformanceDatabaseImplement.Models.Formats", "Format") + .WithMany() + .HasForeignKey("FormatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Format"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.cs b/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.cs new file mode 100644 index 0000000..c655fd3 --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Migrations/20241112171255_InitialCreate.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace StudentPerformanceDatabaseImplement.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Formats", + 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_Formats", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Students", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Fullname = table.Column(type: "text", nullable: false), + AverageScore = table.Column>(type: "text[]", nullable: false), + FormatId = table.Column(type: "integer", nullable: false), + AdmissionDate = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Students", x => x.Id); + table.ForeignKey( + name: "FK_Students_Formats_FormatId", + column: x => x.FormatId, + principalTable: "Formats", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Students_FormatId", + table: "Students", + column: "FormatId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Students"); + + migrationBuilder.DropTable( + name: "Formats"); + } + } +} diff --git a/StudentPerformanceDatabaseImplement/Migrations/StudentsDatabaseModelSnapshot.cs b/StudentPerformanceDatabaseImplement/Migrations/StudentsDatabaseModelSnapshot.cs new file mode 100644 index 0000000..7a068d8 --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Migrations/StudentsDatabaseModelSnapshot.cs @@ -0,0 +1,85 @@ +// +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using StudentPerformanceDatabaseImplement; + +#nullable disable + +namespace StudentPerformanceDatabaseImplement.Migrations +{ + [DbContext(typeof(StudentsDatabase))] + partial class StudentsDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Formats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Formats"); + }); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Students", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdmissionDate") + .HasColumnType("timestamp with time zone"); + + b.Property>("AverageScore") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("FormatId") + .HasColumnType("integer"); + + b.Property("Fullname") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("FormatId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("StudentPerformanceDatabaseImplement.Models.Students", b => + { + b.HasOne("StudentPerformanceDatabaseImplement.Models.Formats", "Format") + .WithMany() + .HasForeignKey("FormatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Format"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/StudentPerformanceDatabaseImplement/Models/Formats.cs b/StudentPerformanceDatabaseImplement/Models/Formats.cs new file mode 100644 index 0000000..e2474f1 --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Models/Formats.cs @@ -0,0 +1,54 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.ViewModels; +using StudentPerformanceDataModels.Models; + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceDatabaseImplement.Models +{ + public class Formats : IFormatModel + { + public int Id { get; private set; } + [Required] + public string Name { get; private set; } = string.Empty; + + public static Formats? Create(FormatBindingModel? model) + { + if (model == null) + { + return null; + } + return new Formats() + { + Id = model.Id, + Name = model.Name, + }; + } + public static Formats? Create(FormatViewModel? model) + { + return new Formats() + { + Id = model.Id, + Name = model.Name, + }; + } + public void Update(FormatBindingModel? model) + { + if (model == null) + { + return; + } + Name = model.Name; + } + public FormatViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + }; + } +} diff --git a/StudentPerformanceDatabaseImplement/Models/Students.cs b/StudentPerformanceDatabaseImplement/Models/Students.cs new file mode 100644 index 0000000..9bbec3c --- /dev/null +++ b/StudentPerformanceDatabaseImplement/Models/Students.cs @@ -0,0 +1,67 @@ +using StudentPerformanceContracts.BindingModels; +using StudentPerformanceContracts.ViewModels; +using StudentPerformanceDataModels.Models; + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceDatabaseImplement.Models +{ + public class Students : IStudentModel + { + [Required] + public string Fullname { get; set; } = string.Empty; + + // Средний балл по сесии (не более 6 сессий) + public List AverageScore { get; set; } = new List(); + + public int Id { get; private set; } + + public int FormatId { get; set; } + public virtual Formats Format { get; set; } = new(); + + public DateTime AdmissionDate { get; set; } + + public static Students? Create(StudentsDatabase context, StudentBindingModel? model) + { + if (model == null) + { + return null; + } + return new Students() + { + Id = model.Id, + Fullname = model.Fullname, + Format = context.Formats.First(x => x.Id == model.FormatId), + AverageScore = model.AverageScore, + AdmissionDate = model.AdmissionDate.ToUniversalTime() + }; + } + + public void Update(StudentBindingModel? model, StudentsDatabase context) + { + if (model == null) + { + return; + } + Fullname = model.Fullname; + Format = context.Formats.First(x => x.Id == model.Id); + AverageScore = model.AverageScore.ToList(); + AdmissionDate = model.AdmissionDate.ToUniversalTime(); + } + + public StudentViewModel GetViewModel => new() + { + Id = Id, + Fullname = Fullname, + FormatId = Format.Id, + Format = Format.Name, + AverageScore = AverageScore, + AdmissionDate = AdmissionDate, + }; + } +} \ No newline at end of file diff --git a/StudentPerformanceDatabaseImplement/StudentPerformanceDatabaseImplement.csproj b/StudentPerformanceDatabaseImplement/StudentPerformanceDatabaseImplement.csproj new file mode 100644 index 0000000..20bf87b --- /dev/null +++ b/StudentPerformanceDatabaseImplement/StudentPerformanceDatabaseImplement.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/StudentPerformanceDatabaseImplement/StudentsDatabase.cs b/StudentPerformanceDatabaseImplement/StudentsDatabase.cs new file mode 100644 index 0000000..c66a53f --- /dev/null +++ b/StudentPerformanceDatabaseImplement/StudentsDatabase.cs @@ -0,0 +1,20 @@ +using StudentPerformanceDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Principal; +using System.Text; +using System.Threading.Tasks; + +namespace StudentPerformanceDatabaseImplement +{ + public class StudentsDatabase : DbContext + { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseNpgsql("Host=localhost;Database=StudentPerformanceDB;Username=postgres;Password=12345"); + + public virtual DbSet Students { set; get; } + public virtual DbSet Formats { set; get; } + } +}