ИСЭбд-22. Мухамадиева С.С. Лабораторная работа №2 #2

Closed
safia wants to merge 7 commits from LabWork_2 into LabWork_1
46 changed files with 1134 additions and 622 deletions

View File

@ -0,0 +1,11 @@
namespace StudentProgress.Entities.Enums;
[Flags]
public enum Course
{
None,
First = 1, // 1 курс
Second = 2, // 2 курс
Third = 4, // 3 курс
Fourth = 8 // 4 курс
}

View File

@ -1,9 +0,0 @@
namespace StudentProgress.Entities.Enums;
public enum DisLectE
{
None = 0,
Praktika = 1,
Lecturer = 2,
Labaratory = 3
}

View File

@ -8,10 +8,10 @@ namespace StudentProgress.Entities.Enums;
public enum Grade
{
None = 0, //пересдача
Two = 1,
Three = 2,
Four = 3,
Five = 4,
Zachet = 5
None,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
}

View File

@ -1,10 +0,0 @@
namespace StudentProgress.Entities.Enums;
[Flags]
public enum TypeOfWork
{
None = 0, //неизвестная работа
Exam = 1,
Zachet = 2,
Referat = 4,
Laba = 8,
}

View File

@ -6,15 +6,16 @@ public class Grades
public int SubjectsId { get; private set; }
public int ProfessorsId { get; private set; }
public DateTime Date { get; private set; }
public static Grades CreateEntity(int id, int subjectsId, int professorsId, DateTime date)
public IEnumerable<StudentGrades> StudentGrade { get; private set; } = [];
public static Grades CreateEntity(int id, int subjectsId, int professorsId, DateTime date, IEnumerable<StudentGrades> studentGrades)
{
return new Grades
{
Id = id,
SubjectsId = subjectsId,
ProfessorsId = professorsId,
Date = date
Date = date,
StudentGrade = studentGrades
};
}
}

View File

@ -1,17 +1,16 @@
namespace StudentProgress.Entities
{
public class Group
{
public int Id { get; private set; }
public string NameGroup { get; set; } = string.Empty;
namespace StudentProgress.Entities;
public static Group CreateEntity(int id, string nameGroup)
public class Group
{
public int Id { get; private set; }
public string NameGroup { get; set; } = string.Empty;
public static Group CreateEntity(int id, string nameGroup)
{
return new Group
{
return new Group
{
Id = id,
NameGroup = nameGroup ?? string.Empty
};
}
Id = id,
NameGroup = nameGroup ?? string.Empty
};
}
}

View File

@ -1,35 +1,19 @@
namespace StudentProgress.Entities
namespace StudentProgress.Entities;
public class Lectures
{
public class Lectures
public int Id { get; private set; }
public int ProfessorsId { get; private set; }
public DateTime Date { get; private set; }
public string Auditorium { get; private set; } = string.Empty;
public static Lectures CreateElement(int id, int professorsId, DateTime date, string auditorium)
{
public int LectureId { get; private set; }
public int ProfessorsId { get; private set; }
public DateTime Date { get; private set; }
public string Auditorium { get; private set; }
public Lectures()
return new Lectures
{
Auditorium = string.Empty; // Инициализация свойства Auditorium
}
public void SetProfessorsId(int professorsId)
{
ProfessorsId = professorsId;
}
public void SetDate(DateTime date)
{
Date = date;
}
public void SetLectureId(int lectureId)
{
LectureId = lectureId;
}
public void SetAuditorium(string auditorium)
{
Auditorium = auditorium;
}
Id = id,
Date = date,
Auditorium = auditorium,
ProfessorsId = professorsId,
};
}
}

View File

@ -3,15 +3,15 @@
public class Professors
{
public int Id { get; set; }
public string FirstNameProfessor { get; set; } = string.Empty;
public string SurnameProfessor { get; set; } = string.Empty;
public static Professors CreateEntity(int id, string firstName, string SurnameProfessor)
public string FirstName { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public static Professors CreateEntity(int id, string firstName, string surname)
{
return new Professors
{
Id = id,
FirstNameProfessor = firstName ?? string.Empty,
SurnameProfessor = SurnameProfessor ?? string.Empty
FirstName = firstName ?? string.Empty,
Surname = surname ?? string.Empty
};
}
}

View File

@ -1,21 +1,20 @@
namespace StudentProgress.Entities
{
public class Student
{
public int Id { get; private set; }
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public int GroupId { get; set; }
namespace StudentProgress.Entities;
public static Student CreateEntity(int id, string name, string surname, int groupId)
public class Student
{
public int Id { get; private set; }
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public int GroupId { get; set; }
public static Student CreateEntity(int id, string name, string surname, int groupId)
{
return new Student
{
return new Student
{
Id = id,
Name = name ?? string.Empty,
Surname = surname ?? string.Empty,
GroupId = groupId
};
}
Id = id,
Name = name ?? string.Empty,
Surname = surname ?? string.Empty,
GroupId = groupId
};
}
}

View File

@ -1,17 +1,20 @@
namespace StudentProgress.Entities;
using Microsoft.VisualBasic.Devices;
using StudentProgress.Entities.Enums;
namespace StudentProgress.Entities;
public class Subjects
{
public int Id { get; private set; }
public string NameSubject { get; private set; } = string.Empty;
public static Subjects CreateEntity_(int id, string nameSubject)
public Course Course { get; private set; }
public static Subjects CreateEntity_(int id, string nameSubject, Course course)
{
return new Subjects
{
Id = id,
NameSubject = nameSubject ?? string.Empty,
Course = course
};
}
}

View File

@ -48,7 +48,7 @@
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(13, 5, 0, 5);
menuStrip1.Size = new Size(915, 48);
menuStrip1.Size = new Size(915, 46);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
@ -56,7 +56,7 @@
//
DirectoriesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { GroupsToolStripMenuItem, StudentsToolStripMenuItem, ProfessorsToolStripMenuItem, SubjectsToolStripMenuItem });
DirectoriesToolStripMenuItem.Name = "DirectoriesToolStripMenuItem";
DirectoriesToolStripMenuItem.Size = new Size(184, 38);
DirectoriesToolStripMenuItem.Size = new Size(184, 36);
DirectoriesToolStripMenuItem.Text = "Справочники";
//
// GroupsToolStripMenuItem
@ -91,27 +91,27 @@
//
OperationsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { GradesToolStripMenuItem, LecturesCountToolStripMenuItem });
OperationsToolStripMenuItem.Name = "OperationsToolStripMenuItem";
OperationsToolStripMenuItem.Size = new Size(147, 38);
OperationsToolStripMenuItem.Size = new Size(147, 36);
OperationsToolStripMenuItem.Text = "Операции";
//
// GradesToolStripMenuItem
//
GradesToolStripMenuItem.Name = "GradesToolStripMenuItem";
GradesToolStripMenuItem.Size = new Size(285, 44);
GradesToolStripMenuItem.Size = new Size(359, 44);
GradesToolStripMenuItem.Text = "Оценки";
GradesToolStripMenuItem.Click += GradeToolStripMenuItem_Click;
//
// LecturesCountToolStripMenuItem
//
LecturesCountToolStripMenuItem.Name = "LecturesCountToolStripMenuItem";
LecturesCountToolStripMenuItem.Size = new Size(285, 44);
LecturesCountToolStripMenuItem.Size = new Size(359, 44);
LecturesCountToolStripMenuItem.Text = "Учет лекций";
LecturesCountToolStripMenuItem.Click += LecturesCountToolStripMenuItem_Click;
//
// ReportsToolStripMenuItem
//
ReportsToolStripMenuItem.Name = "ReportsToolStripMenuItem";
ReportsToolStripMenuItem.Size = new Size(116, 38);
ReportsToolStripMenuItem.Size = new Size(116, 36);
ReportsToolStripMenuItem.Text = "Отчеты";
//
// FormStudentProgress
@ -126,7 +126,7 @@
Margin = new Padding(6, 7, 6, 7);
Name = "FormStudentProgress";
StartPosition = FormStartPosition.CenterScreen;
Text = "Учет успеваемости студентов";
Text = " ";
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);

View File

@ -28,7 +28,6 @@
/// </summary>
private void InitializeComponent()
{
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
@ -37,56 +36,51 @@
dateTimePicker1 = new DateTimePicker();
comboBoxSubject = new ComboBox();
comboBoxProfessor = new ComboBox();
checkedListBoxType = new CheckedListBox();
groupBox1 = new GroupBox();
groupBox2 = new GroupBox();
dataGridView1 = new DataGridView();
ColumnStudent = new DataGridViewComboBoxColumn();
ColumnMark = new DataGridViewTextBoxColumn();
groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(62, 49);
label1.Name = "label1";
label1.Size = new Size(94, 32);
label1.TabIndex = 0;
label1.Text = "Работа:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(62, 272);
label2.Location = new Point(33, 42);
label2.Margin = new Padding(2, 0, 2, 0);
label2.Name = "label2";
label2.Size = new Size(116, 32);
label2.Size = new Size(58, 15);
label2.TabIndex = 1;
label2.Text = "Предмет:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(62, 370);
label3.Location = new Point(33, 90);
label3.Margin = new Padding(2, 0, 2, 0);
label3.Name = "label3";
label3.Size = new Size(191, 32);
label3.Size = new Size(95, 15);
label3.TabIndex = 2;
label3.Text = "Преподователь:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(62, 481);
label4.Location = new Point(33, 140);
label4.Margin = new Padding(2, 0, 2, 0);
label4.Name = "label4";
label4.Size = new Size(70, 32);
label4.Size = new Size(35, 15);
label4.TabIndex = 3;
label4.Text = "Дата:";
//
// buttonSave
//
buttonSave.Location = new Point(62, 625);
buttonSave.Location = new Point(33, 188);
buttonSave.Margin = new Padding(2, 1, 2, 1);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(150, 46);
buttonSave.Size = new Size(81, 22);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -94,9 +88,10 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(357, 625);
buttonCancel.Location = new Point(192, 188);
buttonCancel.Margin = new Padding(2, 1, 2, 1);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(150, 46);
buttonCancel.Size = new Size(81, 22);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -104,40 +99,37 @@
//
// dateTimePicker1
//
dateTimePicker1.Location = new Point(178, 481);
dateTimePicker1.Location = new Point(81, 134);
dateTimePicker1.Margin = new Padding(2, 1, 2, 1);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(400, 39);
dateTimePicker1.Size = new Size(192, 23);
dateTimePicker1.TabIndex = 6;
//
// comboBoxSubject
//
comboBoxSubject.FormattingEnabled = true;
comboBoxSubject.Location = new Point(267, 272);
comboBoxSubject.Location = new Point(141, 42);
comboBoxSubject.Margin = new Padding(2, 1, 2, 1);
comboBoxSubject.Name = "comboBoxSubject";
comboBoxSubject.Size = new Size(242, 40);
comboBoxSubject.Size = new Size(132, 23);
comboBoxSubject.TabIndex = 8;
//
// comboBoxProfessor
//
comboBoxProfessor.FormattingEnabled = true;
comboBoxProfessor.Location = new Point(267, 370);
comboBoxProfessor.Location = new Point(141, 87);
comboBoxProfessor.Margin = new Padding(2, 1, 2, 1);
comboBoxProfessor.Name = "comboBoxProfessor";
comboBoxProfessor.Size = new Size(242, 40);
comboBoxProfessor.Size = new Size(132, 23);
comboBoxProfessor.TabIndex = 9;
//
// checkedListBoxType
//
checkedListBoxType.FormattingEnabled = true;
checkedListBoxType.Location = new Point(267, 49);
checkedListBoxType.Name = "checkedListBoxType";
checkedListBoxType.Size = new Size(240, 184);
checkedListBoxType.TabIndex = 10;
//
// groupBox1
//
groupBox1.Location = new Point(680, 158);
groupBox1.Location = new Point(366, 74);
groupBox1.Margin = new Padding(2, 1, 2, 1);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(400, 200);
groupBox1.Padding = new Padding(2, 1, 2, 1);
groupBox1.Size = new Size(215, 94);
groupBox1.TabIndex = 11;
groupBox1.TabStop = false;
groupBox1.Text = "groupBox1";
@ -145,11 +137,9 @@
// groupBox2
//
groupBox2.Controls.Add(dataGridView1);
groupBox2.Location = new Point(627, 49);
groupBox2.Margin = new Padding(6);
groupBox2.Location = new Point(338, 23);
groupBox2.Name = "groupBox2";
groupBox2.Padding = new Padding(6);
groupBox2.Size = new Size(519, 622);
groupBox2.Size = new Size(279, 221);
groupBox2.TabIndex = 12;
groupBox2.TabStop = false;
groupBox2.Text = "Оценка";
@ -158,13 +148,13 @@
//
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { ColumnStudent });
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { ColumnStudent, ColumnMark });
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(6, 38);
dataGridView1.Margin = new Padding(6);
dataGridView1.Location = new Point(3, 19);
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersVisible = false;
dataGridView1.RowHeadersWidth = 82;
dataGridView1.Size = new Size(507, 578);
dataGridView1.Size = new Size(273, 199);
dataGridView1.TabIndex = 0;
//
// ColumnStudent
@ -173,14 +163,20 @@
ColumnStudent.MinimumWidth = 10;
ColumnStudent.Name = "ColumnStudent";
//
// ColumnMark
//
ColumnMark.HeaderText = "Оценка";
ColumnMark.Name = "ColumnMark";
ColumnMark.Resizable = DataGridViewTriState.True;
ColumnMark.SortMode = DataGridViewColumnSortMode.NotSortable;
//
// FormGrade
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1161, 779);
ClientSize = new Size(625, 273);
Controls.Add(groupBox2);
Controls.Add(groupBox1);
Controls.Add(checkedListBoxType);
Controls.Add(comboBoxProfessor);
Controls.Add(comboBoxSubject);
Controls.Add(dateTimePicker1);
@ -189,10 +185,9 @@
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Margin = new Padding(2, 1, 2, 1);
Name = "FormGrade";
Text = "Оценка";
Load += FormGrade_Load;
groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
@ -200,8 +195,6 @@
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private Label label4;
@ -210,10 +203,10 @@
private DateTimePicker dateTimePicker1;
private ComboBox comboBoxSubject;
private ComboBox comboBoxProfessor;
private CheckedListBox checkedListBoxType;
private GroupBox groupBox1;
private GroupBox groupBox2;
private DataGridView dataGridView1;
private DataGridViewComboBoxColumn ColumnStudent;
private DataGridViewTextBoxColumn ColumnMark;
}
}

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using StudentProgress.Entities;
using StudentProgress.Entities;
using StudentProgress.Entities.Enums;
using StudentProgress.Repositories;
@ -11,30 +8,23 @@ namespace StudentProgress.Forms
{
private readonly IGradesRepository _gradesRepository;
private readonly ISubjectsRepository _subjectsRepository;
private readonly IProfessorsNameRepository _professorsRepository;
private readonly IProfessorsRepository _professorsRepository;
private readonly IStudentRepository _studentRepository;
public FormGrade(IGradesRepository gradesRepository, ISubjectsRepository subjectsRepository,
IProfessorsNameRepository professorsRepository, IStudentRepository studentRepository)
IProfessorsRepository professorsRepository, IStudentRepository studentRepository)
{
InitializeComponent();
_gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository));
_subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository));
_professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository));
_studentRepository = studentRepository ?? throw new ArgumentNullException(nameof(studentRepository));
LoadWorkTypes();
LoadSubjects();
LoadProfessors();
LoadStudents();
}
private void LoadWorkTypes()
{
foreach (var elem in Enum.GetValues(typeof(TypeOfWork)))
{
checkedListBoxType.Items.Add(elem);
}
}
private void LoadSubjects()
@ -47,9 +37,9 @@ namespace StudentProgress.Forms
private void LoadProfessors()
{
var professors = _professorsRepository.ReadProfessorsName();
var professors = _professorsRepository.ReadProfessors();
comboBoxProfessor.DataSource = professors;
comboBoxProfessor.DisplayMember = "FirstNameProfessor";
comboBoxProfessor.DisplayMember = "FirstName";
comboBoxProfessor.ValueMember = "Id";
}
@ -65,11 +55,11 @@ namespace StudentProgress.Forms
{
try
{
if (comboBoxSubject.SelectedIndex < 0 || checkedListBoxType.CheckedItems.Count == 0)
if (comboBoxSubject.SelectedIndex < 0 || dataGridView1.RowCount < 1)
{
throw new Exception("Имеются незаполненные поля");
}
CreateGrade(0);
_gradesRepository.CreateGrade(CreateGrade(0));
Close();
}
catch (Exception ex)
@ -80,43 +70,18 @@ namespace StudentProgress.Forms
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Grades CreateGrade(int id)
{
TypeOfWork typeOfWork = TypeOfWork.None;
foreach (var elem in checkedListBoxType.CheckedItems)
{
typeOfWork |= (TypeOfWork)elem;
}
return Grades.CreateEntity(id, (int)comboBoxSubject.SelectedValue, (int)comboBoxProfessor.SelectedValue, dateTimePicker1.Value);
}
private Grades CreateGrade(int id) => Grades.CreateEntity(id, (int)comboBoxSubject.SelectedValue!, (int)comboBoxProfessor.SelectedValue!, dateTimePicker1.Value, CreateListStudentGradesFromDataGrid());
private void FormGrade_Load(object sender, EventArgs e)
{
var columnGrade = new DataGridViewComboBoxColumn
{
Name = "ColumnGrade",
HeaderText = "Оценка",
DataSource = Enum.GetValues(typeof(Grade))
};
if (dataGridView1.Columns["ColumnGrade"] != null)
{
dataGridView1.Columns.Remove("ColumnGrade");
}
dataGridView1.Columns.Add(columnGrade);
}
private List<StudentGrades> CreateListFeedFeedReplenishmentsFromDataGrid()
public List<StudentGrades> CreateListStudentGradesFromDataGrid()
{
var list = new List<StudentGrades>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["ColumnStudent"].Value == null || row.Cells["ColumnGrade"].Value == null)
if (row.Cells["ColumnStudent"].Value == null || row.Cells["ColumnMark"].Value == null)
{
continue;
}
list.Add(StudentGrades.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnStudent"].Value), (Grade)(row.Cells["ColumnGrade"].Value)));
list.Add(StudentGrades.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnStudent"].Value), (Grade)Convert.ToInt32(row.Cells["ColumnMark"].Value)));
}
return list;
}

View File

@ -120,7 +120,4 @@
<metadata name="ColumnStudent.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnStudent.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -82,6 +82,7 @@
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(548, 271);
dataGridView.TabIndex = 1;
//

View File

@ -78,14 +78,14 @@ namespace StudentProgress.Forms
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormGroup
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(644, 461);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxNameGroup);

View File

@ -41,22 +41,27 @@ namespace StudentProgress.Forms
//
// dataGridView
//
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(26, 30);
dataGridView.Margin = new Padding(6, 7, 6, 7);
dataGridView.Location = new Point(14, 14);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 82;
dataGridView.Size = new Size(635, 569);
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(342, 267);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(28, 37);
buttonAdd.Margin = new Padding(6, 7, 6, 7);
buttonAdd.Location = new Point(15, 17);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(162, 115);
buttonAdd.Size = new Size(87, 54);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
@ -65,10 +70,9 @@ namespace StudentProgress.Forms
//
buttonPencil.BackgroundImage = Properties.Resources.Pencil;
buttonPencil.BackgroundImageLayout = ImageLayout.Stretch;
buttonPencil.Location = new Point(28, 224);
buttonPencil.Margin = new Padding(6, 7, 6, 7);
buttonPencil.Location = new Point(15, 105);
buttonPencil.Name = "buttonPencil";
buttonPencil.Size = new Size(162, 127);
buttonPencil.Size = new Size(87, 60);
buttonPencil.TabIndex = 2;
buttonPencil.UseVisualStyleBackColor = true;
buttonPencil.Click += buttonPencil_Click;
@ -77,10 +81,9 @@ namespace StudentProgress.Forms
//
buttonDel.BackgroundImage = Properties.Resources.Del;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(28, 390);
buttonDel.Margin = new Padding(6, 7, 6, 7);
buttonDel.Location = new Point(15, 183);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(162, 127);
buttonDel.Size = new Size(87, 60);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
@ -90,19 +93,19 @@ namespace StudentProgress.Forms
panel1.Controls.Add(buttonAdd);
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonPencil);
panel1.Location = new Point(693, 30);
panel1.Location = new Point(373, 14);
panel1.Margin = new Padding(2, 1, 2, 1);
panel1.Name = "panel1";
panel1.Size = new Size(214, 569);
panel1.Size = new Size(115, 267);
panel1.TabIndex = 4;
//
// FormGroups
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(919, 628);
ClientSize = new Size(495, 294);
Controls.Add(panel1);
Controls.Add(dataGridView);
Margin = new Padding(6, 7, 6, 7);
Name = "FormGroups";
Text = "Группы";
Load += FormGroups_Load;

View File

@ -38,23 +38,27 @@
//
// LecturesDataGridView
//
LecturesDataGridView.AllowUserToResizeColumns = false;
LecturesDataGridView.AllowUserToResizeRows = false;
LecturesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
LecturesDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
LecturesDataGridView.Location = new Point(15, 16);
LecturesDataGridView.Margin = new Padding(6, 7, 6, 7);
LecturesDataGridView.Location = new Point(8, 8);
LecturesDataGridView.MultiSelect = false;
LecturesDataGridView.Name = "LecturesDataGridView";
LecturesDataGridView.RowHeadersVisible = false;
LecturesDataGridView.RowHeadersWidth = 82;
LecturesDataGridView.Size = new Size(841, 459);
LecturesDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
LecturesDataGridView.Size = new Size(453, 215);
LecturesDataGridView.TabIndex = 0;
LecturesDataGridView.CellContentClick += LecturesDataGridView_CellContentClick;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(28, 36);
buttonAdd.Margin = new Padding(13, 17, 13, 17);
buttonAdd.Location = new Point(15, 17);
buttonAdd.Margin = new Padding(7, 8, 7, 8);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(155, 128);
buttonAdd.Size = new Size(83, 60);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
@ -63,10 +67,10 @@
//
buttonDel.BackgroundImage = Properties.Resources.Del;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(25, 281);
buttonDel.Margin = new Padding(13, 17, 13, 17);
buttonDel.Location = new Point(13, 132);
buttonDel.Margin = new Padding(7, 8, 7, 8);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(158, 138);
buttonDel.Size = new Size(85, 65);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
@ -75,19 +79,19 @@
//
panel1.Controls.Add(buttonAdd);
panel1.Controls.Add(buttonDel);
panel1.Location = new Point(885, 16);
panel1.Location = new Point(477, 8);
panel1.Margin = new Padding(2, 1, 2, 1);
panel1.Name = "panel1";
panel1.Size = new Size(216, 452);
panel1.Size = new Size(116, 212);
panel1.TabIndex = 3;
//
// FormLecturesCount
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1112, 493);
ClientSize = new Size(599, 231);
Controls.Add(panel1);
Controls.Add(LecturesDataGridView);
Margin = new Padding(6, 7, 6, 7);
Name = "FormLecturesCount";
Text = "Учет лекций";
Load += FormLecturesCount_Load;

View File

@ -9,10 +9,10 @@ namespace StudentProgress.Forms
{
public partial class FormLecturesCount : Form
{
private readonly IProfessorsNameRepository _professorsRepository;
private readonly IProfessorsRepository _professorsRepository;
private readonly ILecturesRepository _lecturesRepository;
public FormLecturesCount(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository)
public FormLecturesCount(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository)
{
InitializeComponent();
_professorsRepository = professorsRepository;

View File

@ -40,26 +40,23 @@ namespace StudentProgress.Forms
//
// textBoxFirstName
//
textBoxFirstName.Location = new Point(235, 28);
textBoxFirstName.Margin = new Padding(6, 7, 6, 7);
textBoxFirstName.Location = new Point(127, 13);
textBoxFirstName.Name = "textBoxFirstName";
textBoxFirstName.Size = new Size(252, 39);
textBoxFirstName.Size = new Size(167, 23);
textBoxFirstName.TabIndex = 0;
//
// textBoxSurname
//
textBoxSurname.Location = new Point(235, 105);
textBoxSurname.Margin = new Padding(6, 7, 6, 7);
textBoxSurname.Location = new Point(127, 49);
textBoxSurname.Name = "textBoxSurname";
textBoxSurname.Size = new Size(306, 39);
textBoxSurname.Size = new Size(167, 23);
textBoxSurname.TabIndex = 1;
//
// buttonSave
//
buttonSave.Location = new Point(53, 233);
buttonSave.Margin = new Padding(6, 7, 6, 7);
buttonSave.Location = new Point(29, 109);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(162, 57);
buttonSave.Size = new Size(87, 27);
buttonSave.TabIndex = 2;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -67,10 +64,9 @@ namespace StudentProgress.Forms
//
// buttonCancel
//
buttonCancel.Location = new Point(286, 233);
buttonCancel.Margin = new Padding(6, 7, 6, 7);
buttonCancel.Location = new Point(154, 109);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(162, 57);
buttonCancel.Size = new Size(87, 27);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -79,33 +75,34 @@ namespace StudentProgress.Forms
// label1
//
label1.AutoSize = true;
label1.Location = new Point(53, 31);
label1.Location = new Point(29, 15);
label1.Margin = new Padding(2, 0, 2, 0);
label1.Name = "label1";
label1.Size = new Size(66, 32);
label1.Size = new Size(34, 15);
label1.TabIndex = 4;
label1.Text = "Имя:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(53, 105);
label2.Location = new Point(29, 49);
label2.Margin = new Padding(2, 0, 2, 0);
label2.Name = "label2";
label2.Size = new Size(113, 32);
label2.Size = new Size(58, 15);
label2.TabIndex = 5;
label2.Text = "Фамилия";
//
// FormProfessor
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(695, 354);
ClientSize = new Size(374, 166);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSurname);
Controls.Add(textBoxFirstName);
Margin = new Padding(6, 7, 6, 7);
Name = "FormProfessor";
Text = "Преподаватель";
ResumeLayout(false);

View File

@ -8,7 +8,7 @@ namespace StudentProgress.Forms
{
public partial class FormProfessor : Form
{
private readonly IProfessorsNameRepository _professorsRepository;
private readonly IProfessorsRepository _professorsRepository;
private int? _professorId;
public int Id
@ -34,7 +34,7 @@ namespace StudentProgress.Forms
}
}
public FormProfessor(IProfessorsNameRepository professorsRepository)
public FormProfessor(IProfessorsRepository professorsRepository)
{
InitializeComponent();
_professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository));

View File

@ -39,60 +39,61 @@ namespace StudentProgress.Forms
//
// dataGridView
//
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(26, 30);
dataGridView.Margin = new Padding(6, 7, 6, 7);
dataGridView.Location = new Point(14, 14);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 82;
dataGridView.Size = new Size(867, 492);
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(467, 231);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.BackgroundImage = StudentProgress.Properties.Resources.Add;
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(935, 30);
buttonAdd.Margin = new Padding(6, 7, 6, 7);
buttonAdd.Location = new Point(503, 14);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(162, 118);
buttonAdd.Size = new Size(87, 55);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonPencil
//
buttonPencil.BackgroundImage = StudentProgress.Properties.Resources.Pencil;
buttonPencil.BackgroundImage = Properties.Resources.Pencil;
buttonPencil.BackgroundImageLayout = ImageLayout.Stretch;
buttonPencil.Location = new Point(935, 224);
buttonPencil.Margin = new Padding(6, 7, 6, 7);
buttonPencil.Location = new Point(503, 105);
buttonPencil.Name = "buttonPencil";
buttonPencil.Size = new Size(162, 118);
buttonPencil.Size = new Size(87, 55);
buttonPencil.TabIndex = 2;
buttonPencil.UseVisualStyleBackColor = true;
buttonPencil.Click += buttonPencil_Click;
//
// buttonDel
//
buttonDel.BackgroundImage = StudentProgress.Properties.Resources.Del;
buttonDel.BackgroundImage = Properties.Resources.Del;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(935, 396);
buttonDel.Margin = new Padding(6, 7, 6, 7);
buttonDel.Location = new Point(503, 186);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(162, 126);
buttonDel.Size = new Size(87, 59);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// FormProfessors
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1148, 628);
ClientSize = new Size(618, 294);
Controls.Add(buttonDel);
Controls.Add(buttonPencil);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Margin = new Padding(6, 7, 6, 7);
Name = "FormProfessors";
Text = "Преподаватели";
Load += FormProfessors_Load;

View File

@ -8,9 +8,9 @@ namespace StudentProgress.Forms
public partial class FormProfessors : Form
{
private readonly IUnityContainer _container;
private readonly IProfessorsNameRepository _professorsRepository;
private readonly IProfessorsRepository _professorsRepository;
public FormProfessors(IUnityContainer container, IProfessorsNameRepository professorsRepository)
public FormProfessors(IUnityContainer container, IProfessorsRepository professorsRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));

View File

@ -7,10 +7,10 @@ namespace StudentProgress.Forms
{
public partial class FormRecordLecture : Form
{
private readonly IProfessorsNameRepository _professorsRepository;
private readonly IProfessorsRepository _professorsRepository;
private readonly ILecturesRepository _lecturesRepository;
public FormRecordLecture(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository)
public FormRecordLecture(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository)
{
InitializeComponent();
_professorsRepository = professorsRepository;

View File

@ -95,6 +95,7 @@
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(548, 271);
dataGridView.TabIndex = 1;
//

View File

@ -20,27 +20,23 @@ namespace StudentPerformance.Forms
buttonSave = new Button();
buttonCancel = new Button();
labelName = new Label();
groupBox = new GroupBox();
dataGridView = new DataGridView();
ColumnLast = new DataGridViewComboBoxColumn();
groupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
checkedListBoxCourses = new CheckedListBox();
groupBox1 = new GroupBox();
groupBox1.SuspendLayout();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(183, 47);
textBoxName.Margin = new Padding(6, 7, 6, 7);
textBoxName.Location = new Point(99, 22);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(343, 39);
textBoxName.Size = new Size(187, 23);
textBoxName.TabIndex = 0;
//
// buttonSave
//
buttonSave.Location = new Point(32, 579);
buttonSave.Margin = new Padding(6, 7, 6, 7);
buttonSave.Location = new Point(17, 271);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(162, 57);
buttonSave.Size = new Size(87, 27);
buttonSave.TabIndex = 1;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -48,10 +44,9 @@ namespace StudentPerformance.Forms
//
// buttonCancel
//
buttonCancel.Location = new Point(370, 597);
buttonCancel.Margin = new Padding(6, 7, 6, 7);
buttonCancel.Location = new Point(199, 280);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(162, 57);
buttonCancel.Size = new Size(87, 27);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -60,67 +55,44 @@ namespace StudentPerformance.Forms
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(32, 47);
labelName.Margin = new Padding(6, 0, 6, 0);
labelName.Location = new Point(17, 22);
labelName.Name = "labelName";
labelName.Size = new Size(111, 32);
labelName.Size = new Size(55, 15);
labelName.TabIndex = 3;
labelName.Text = "Предмет";
//
// groupBox
// checkedListBoxCourses
//
groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupBox.Controls.Add(dataGridView);
groupBox.Location = new Point(32, 111);
groupBox.Margin = new Padding(6);
groupBox.Name = "groupBox";
groupBox.Padding = new Padding(6);
groupBox.Size = new Size(494, 435);
groupBox.TabIndex = 3;
groupBox.TabStop = false;
groupBox.Text = "Преподаватели";
checkedListBoxCourses.Dock = DockStyle.Fill;
checkedListBoxCourses.FormattingEnabled = true;
checkedListBoxCourses.Location = new Point(3, 19);
checkedListBoxCourses.Name = "checkedListBoxCourses";
checkedListBoxCourses.Size = new Size(263, 179);
checkedListBoxCourses.TabIndex = 4;
//
// dataGridView
// groupBox1
//
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnLast });
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(6, 38);
dataGridView.Margin = new Padding(6);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 82;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(482, 391);
dataGridView.TabIndex = 0;
//
// ColumnLast
//
ColumnLast.HeaderText = "Фамилия преподавателя";
ColumnLast.MinimumWidth = 10;
ColumnLast.Name = "ColumnLast";
ColumnLast.Width = 200;
groupBox1.Controls.Add(checkedListBoxCourses);
groupBox1.Location = new Point(17, 64);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(269, 201);
groupBox1.TabIndex = 5;
groupBox1.TabStop = false;
groupBox1.Text = "Курсы";
//
// FormSubject
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(590, 719);
Controls.Add(groupBox);
ClientSize = new Size(318, 337);
Controls.Add(groupBox1);
Controls.Add(labelName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxName);
Margin = new Padding(6, 7, 6, 7);
Name = "FormSubject";
Text = "Предметы";
Load += FormSubject_Load;
groupBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
groupBox1.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
@ -129,8 +101,7 @@ namespace StudentPerformance.Forms
private System.Windows.Forms.Button buttonSave;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelName;
private GroupBox groupBox;
private DataGridView dataGridView;
private DataGridViewComboBoxColumn ColumnLast;
private CheckedListBox checkedListBoxCourses;
private GroupBox groupBox1;
}
}

View File

@ -1,4 +1,5 @@
using StudentProgress.Entities;
using StudentProgress.Entities.Enums;
using StudentProgress.Repositories;
using System;
using System.Windows.Forms;
@ -8,11 +9,46 @@ namespace StudentPerformance.Forms
public partial class FormSubject : Form
{
private readonly ISubjectsRepository _subjectsRepository;
private int? _subjectId;
public int Id
{
set
{
try
{
var subject = _subjectsRepository.ReadSubjectById(value);
if (subject == null)
{
throw new InvalidDataException(nameof(subject));
}
foreach (Course elem in Enum.GetValues(typeof(Course)))
{
if ((elem & subject.Course) != 0)
{
checkedListBoxCourses.SetItemChecked(checkedListBoxCourses.Items.IndexOf(elem), true);
}
}
textBoxName.Text = subject.NameSubject;
_subjectId = subject.Id;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormSubject(ISubjectsRepository subjectsRepository)
{
InitializeComponent();
_subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository));
foreach (var elem in Enum.GetValues(typeof(Course)))
{
checkedListBoxCourses.Items.Add(elem);
}
}
private void buttonSave_Click(object sender, EventArgs e)
@ -23,9 +59,14 @@ namespace StudentPerformance.Forms
{
throw new Exception("Имя предмета не может быть пустым");
}
var subject = Subjects.CreateEntity_(0, textBoxName.Text);
_subjectsRepository.CreateSubjects_(subject);
if (_subjectId.HasValue)
{
_subjectsRepository.UpdateSubject(CreateEntity(_subjectId.Value));
}
else
{
_subjectsRepository.CreateSubjects_(CreateEntity(0));
}
Close();
}
catch (Exception ex)
@ -36,9 +77,15 @@ namespace StudentPerformance.Forms
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private void FormSubject_Load(object sender, EventArgs e)
private Subjects CreateEntity(int id)
{
// Инициализация формы, если необходимо
Course course = Course.None;
foreach (var elem in checkedListBoxCourses.CheckedItems)
{
course |= (Course)elem;
}
return Subjects.CreateEntity_(id, textBoxName.Text, course);
}
}
}

View File

@ -36,29 +36,29 @@ namespace StudentProgress.Forms
buttonDel = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
buttonUpd = new Button();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonUpd);
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(1018, 0);
panel1.Margin = new Padding(6, 6, 6, 6);
panel1.Location = new Point(548, 0);
panel1.Name = "panel1";
panel1.Size = new Size(139, 578);
panel1.Size = new Size(75, 271);
panel1.TabIndex = 0;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Del;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(13, 367);
buttonDel.Margin = new Padding(6, 6, 6, 6);
buttonDel.Location = new Point(7, 172);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(104, 113);
buttonDel.Size = new Size(56, 53);
buttonDel.TabIndex = 1;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
@ -67,10 +67,9 @@ namespace StudentProgress.Forms
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(13, 73);
buttonAdd.Margin = new Padding(6, 6, 6, 6);
buttonAdd.Location = new Point(7, 34);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(104, 113);
buttonAdd.Size = new Size(56, 53);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
@ -85,26 +84,35 @@ namespace StudentProgress.Forms
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Margin = new Padding(6, 6, 6, 6);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 82;
dataGridView.Size = new Size(1018, 578);
dataGridView.Size = new Size(548, 271);
dataGridView.TabIndex = 1;
//
// buttonUpd
//
buttonUpd.BackgroundImage = Properties.Resources.Pencil;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(7, 93);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(56, 53);
buttonUpd.TabIndex = 2;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// FormSubjects
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1157, 578);
ClientSize = new Size(623, 271);
Controls.Add(dataGridView);
Controls.Add(panel1);
Margin = new Padding(6, 6, 6, 6);
Name = "FormSubjects";
Text = "Предметы";
Load += FormSubjects__Load;
Load += FormSubjects_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
@ -116,5 +124,6 @@ namespace StudentProgress.Forms
private DataGridView dataGridView;
private Button buttonDel;
private Button buttonAdd;
private Button buttonUpd;
}
}

View File

@ -2,56 +2,96 @@
using System.Windows.Forms;
using StudentPerformance.Forms;
using StudentProgress.Repositories;
using StudentProgress.Repositories.Implementations;
using Unity;
namespace StudentProgress.Forms
{
public partial class FormSubjects : Form
{
private readonly ISubjectsRepository _subjectsRepository;
private readonly IUnityContainer _container;
public FormSubjects(ISubjectsRepository subjectsRepository)
public FormSubjects(IUnityContainer container, ISubjectsRepository subjectsRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository));
}
private void FormSubjects__Load(object sender, EventArgs e)
{
// Загрузка данных в DataGridView
LoadData();
}
private void FormSubjects_Load(object sender, EventArgs e) => LoadData();
private void LoadData()
{
// Пример загрузки данных из репозитория
var subjects = _subjectsRepository.ReadSubjects();
dataGridView.DataSource = subjects;
dataGridView.DataSource = _subjectsRepository.ReadSubjects();
dataGridView.Columns["Id"].Visible = false;
}
private void buttonAdd_Click(object sender, EventArgs e)
{
// Логика добавления нового предмета
using (var form = new FormSubject(new SubjectsRepository()))
try
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
_container.Resolve<FormSubject>().ShowDialog();
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonDel_Click(object sender, EventArgs e)
{
// Логика удаления выбранного предмета
if (dataGridView.SelectedRows.Count > 0)
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
var selectedSubject = dataGridView.SelectedRows[0].DataBoundItem as Entities.Subjects;
if (selectedSubject != null)
{
_subjectsRepository.DeleteSubjects(selectedSubject.Id);
LoadData();
}
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_subjectsRepository.DeleteSubjects(findId);
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormSubject>();
form.Id = findId;
form.ShowDialog();
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -1,9 +1,12 @@
using StudentProgress.Forms;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity;
using Unity.Lifetime;
using StudentProgress.Repositories;
using StudentProgress.Repositories.Implementations;
using Unity;
using System;
using System.Windows.Forms;
using Unity.Microsoft.Logging;
using StudentPerformance.Repositories.Implementations;
namespace StudentProgress
{
@ -15,26 +18,39 @@ namespace StudentProgress
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var container = new UnityContainer();
// Ðåãèñòðàöèÿ ðåïîçèòîðèåâ
container.RegisterType<IGradesRepository, GradesRepository>();
container.RegisterType<IGroupRepository, GroupRepository>();
container.RegisterType<IProfessorsNameRepository, ProfessorsNameRepository>();
container.RegisterType<IStudentRepository, StudentRepository>();
container.RegisterType<ISubjectsRepository, SubjectsRepository>();
container.RegisterType<ILecturesRepository, LecturesRepository>();
// Ðåãèñòðàöèÿ ôîðì
container.RegisterType<FormGroups>();
container.RegisterType<FormStudents>();
container.RegisterType<FormSubjects>();
container.RegisterType<FormGrades>();
container.RegisterType<FormProfessors>();
container.RegisterType<FormRecordLecture>();
container.RegisterType<FormLecturesCount>();
var container = CreateContainer();
Application.Run(container.Resolve<FormStudentProgress>());
}
public static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IGradesRepository, GradesRepository>(new TransientLifetimeManager());
container.RegisterType<IGroupRepository, GroupRepository>(new TransientLifetimeManager());
container.RegisterType<ILecturesRepository, LecturesRepository>(new TransientLifetimeManager());
container.RegisterType<IProfessorsRepository, ProfessorsRepository>(new TransientLifetimeManager());
container.RegisterType<IStudentRepository, StudentRepository>(new TransientLifetimeManager());
container.RegisterType<ISubjectsRepository, SubjectsRepository>(new TransientLifetimeManager());
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@ -1,10 +1,10 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
@ -13,12 +13,12 @@ namespace StudentProgress.Properties {
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
@ -33,7 +33,7 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
@ -47,8 +47,8 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
@ -61,7 +61,7 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Add {
get {
@ -71,7 +71,7 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap BackGround {
get {
@ -81,7 +81,7 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Del {
get {
@ -91,7 +91,7 @@ namespace StudentProgress.Properties {
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Pencil {
get {

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentProgress.Repositories
{
public interface IConnectionString
{
string ConnectionString { get; }
}
}

View File

@ -1,13 +0,0 @@
using StudentProgress.Entities;
using System.Collections.Generic;
namespace StudentProgress.Repositories;
public interface IProfessorsNameRepository
{
IEnumerable<Professors> ReadProfessorsName();
Professors ReadProfessorsNameById(int id);
void CreateProfessorsName(Professors professorsName);
void UpdateProfessorsName(Professors professorsName);
void DeleteProfessorsName(int id);
}

View File

@ -0,0 +1,13 @@
using StudentProgress.Entities;
using System.Collections.Generic;
namespace StudentProgress.Repositories;
public interface IProfessorsRepository
{
IEnumerable<Professors> ReadProfessors();
Professors ReadProfessorsById(int id);
void CreateProfessors(Professors professors);
void UpdateProfessors(Professors professors);
void DeleteProfessors(int id);
}

View File

@ -4,7 +4,10 @@ namespace StudentProgress.Repositories;
public interface ISubjectsRepository
{
IEnumerable<Subjects> ReadSubjects(int? professorsNameId = null);
void CreateSubjects_(Subjects subject);
void DeleteSubjects(int id);
}
IEnumerable<Subjects> ReadSubjects(int? id = null);
Subjects ReadSubjectById(int id);
void UpdateSubject(Subjects subject);
}

View File

@ -0,0 +1,9 @@
using StudentProgress.Repositories;
namespace StudentProgress.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString =>
"Host=localhost;Port=5432;Database=OTP_sophiya;Username=postgres;Password=030405;";
}

View File

@ -1,29 +1,92 @@
using StudentProgress.Entities;
using System;
using System.Collections.Generic;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
namespace StudentProgress.Repositories.Implementations;
public class GradesRepository : IGradesRepository
namespace StudentProgress.Repositories.Implementations
{
public void CreateGrade(Grades grade)
public class GradesRepository : IGradesRepository
{
// Логика создания оценки
}
private readonly IConnectionString _connectionString;
private readonly ILogger<GradesRepository> _logger;
public void DeleteGrade(int id)
{
// Логика удаления оценки по идентификатору
}
public GradesRepository(IConnectionString connectionString, ILogger<GradesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Grades> ReadGrades(DateTime? dateFrom = null, DateTime? dateTo = null, int? subjectsId = null, int? professorsId = null)
{
// Логика чтения оценок с возможностью фильтрации по дате, идентификатору предмета и идентификатору преподавателя
return new List<Grades>();
}
public void CreateGrade(Grades grade)
{
_logger.LogInformation("Добавление оценки");
_logger.LogDebug("Оценка: {json}", JsonConvert.SerializeObject(grade));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Grades (SubjectsId, ProfessorsId, Date)
VALUES (@SubjectsId, @ProfessorsId, @Date);
SELECT MAX(Id) FROM Grades";
var gradesId =
connection.QueryFirst<int>(queryInsert, grade, transaction);
var querySubInsert = @"
INSERT INTO StudentGrades (StudentID, Grade, GradesId)
VALUES (@StudentID, @Grade, @GradesId)";
foreach (var elem in grade.StudentGrade)
{
connection.Execute(querySubInsert, new
{
elem.StudentID,
elem.Grade,
gradesId,
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении оценки");
throw;
}
}
public void UpdateGrade(Grades grade)
{
// Логика обновления оценки
public void DeleteGrade(int id)
{
_logger.LogInformation("Удаление оценки");
_logger.LogDebug("Оценка: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "DELETE FROM Grades WHERE Id = @Id";
connection.Execute(query, new { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении оценки");
throw;
}
}
public IEnumerable<Grades> ReadGrades(DateTime? dateFrom = null, DateTime? dateTo = null, int? subjectsId = null, int? professorsId = null)
{
_logger.LogInformation("Получение оценок");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT * FROM Grades";
var grades = connection.Query<Grades>(query);
_logger.LogDebug("Полученные оценки: {json}", JsonConvert.SerializeObject(grades));
return grades;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении оценок");
throw;
}
}
}
}

View File

@ -1,50 +1,125 @@
using StudentProgress.Entities;
using System.Collections.Generic;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
using StudentProgress.Repositories;
namespace StudentProgress.Repositories.Implementations
namespace StudentPerformance.Repositories.Implementations;
public class GroupRepository : IGroupRepository
{
public class GroupRepository : IGroupRepository
private readonly IConnectionString _connectionString;
private readonly ILogger<GroupRepository> _logger;
public GroupRepository(IConnectionString connectionString, ILogger<GroupRepository> logger)
{
private readonly List<Group> _groups;
_connectionString = connectionString;
_logger = logger;
}
public GroupRepository()
public void CreateGroup(Group group)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(group));
try
{
// Инициализация тестовых данных
_groups = new List<Group>();
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO ""Group"" (NameGroup)
VALUES (@NameGroup)";
connection.Execute(queryInsert, group);
}
public void CreateGroup(Group group)
catch (Exception ex)
{
// Логика создания группы
_groups.Add(group);
}
public void DeleteGroup(int id)
{
// Логика удаления группы по идентификатору
_groups.RemoveAll(g => g.Id == id);
}
public IEnumerable<Group> ReadGroup()
{
// Логика чтения всех групп
return _groups;
}
public Group ReadGroupById(int id)
{
// Логика чтения группы по идентификатору
return _groups.Find(g => g.Id == id);
}
public void UpdateGroup(Group group)
{
// Логика обновления группы
var existingGroup = _groups.Find(g => g.Id == group.Id);
if (existingGroup != null)
{
existingGroup.NameGroup = group.NameGroup;
}
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
}
public void DeleteGroup(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM ""Group""
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Group> ReadGroup()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM \"Group\"";
var groups = connection.Query<Group>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(groups));
return groups;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Group ReadGroupById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM ""Group""
WHERE Id=@id";
var group = connection.QueryFirst<Group>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(group));
return group;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateGroup(Group group)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(group));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE ""Group""
SET
NameGroup=@NameGroup
WHERE Id=@Id";
connection.Execute(queryUpdate, group);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,31 +1,73 @@
using StudentProgress.Entities;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
namespace StudentProgress.Repositories.Implementations
{
public class LecturesRepository : ILecturesRepository
{
private readonly List<Lectures> _lectures = new List<Lectures>();
private readonly IConnectionString _connectionString;
private readonly ILogger<LecturesRepository> _logger;
public LecturesRepository(IConnectionString connectionString, ILogger<LecturesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Lectures> ReadLectures()
{
return _lectures;
_logger.LogInformation("Получение лекций");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT * FROM Lectures";
var lectures = connection.Query<Lectures>(query);
_logger.LogDebug("Полученные лекции: {json}", JsonConvert.SerializeObject(lectures));
return lectures;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении лекций");
throw;
}
}
public void CreateLecture(Lectures lecture)
{
int newLectureId = _lectures.Count > 0 ? _lectures.Max(l => l.LectureId) + 1 : 1;
lecture.SetLectureId(newLectureId);
_lectures.Add(lecture);
_logger.LogInformation("Добавление лекции");
_logger.LogDebug("Лекция: {json}", JsonConvert.SerializeObject(lecture));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = @"
INSERT INTO Lectures (ProfessorsId, Date, Auditorium)
VALUES (@ProfessorsId, @Date, @Auditorium)";
connection.Execute(query, lecture);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении лекции");
throw;
}
}
public void DeleteLecture(int lectureId)
{
var lectureToRemove = _lectures.FirstOrDefault(l => l.LectureId == lectureId);
if (lectureToRemove != null)
_logger.LogInformation("Удаление лекции");
_logger.LogDebug("Лекция: {id}", lectureId);
try
{
_lectures.Remove(lectureToRemove);
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "DELETE FROM Lectures WHERE Id = @LectureId";
connection.Execute(query, new { LectureId = lectureId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении лекции");
throw;
}
}
}

View File

@ -1,34 +0,0 @@
using StudentProgress.Entities;
using System.Collections.Generic;
namespace StudentProgress.Repositories.Implementations;
public class ProfessorsNameRepository : IProfessorsNameRepository
{
public void CreateProfessorsName(Professors professorsName)
{
// Логика создания преподавателя
}
public void DeleteProfessorsName(int id)
{
// Логика удаления преподавателя по идентификатору
}
public IEnumerable<Professors> ReadProfessorsName()
{
// Логика чтения всех преподавателей
return new List<Professors>();
}
public Professors ReadProfessorsNameById(int id)
{
// Логика чтения преподавателя по идентификатору
return Professors.CreateEntity(id, "Unknown", "Unknown");
}
public void UpdateProfessorsName(Professors professorsName)
{
// Логика обновления преподавателя
}
}

View File

@ -0,0 +1,121 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
namespace StudentProgress.Repositories.Implementations;
public class ProfessorsRepository : IProfessorsRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProfessorsRepository> _logger;
public ProfessorsRepository(IConnectionString connectionString, ILogger<ProfessorsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProfessors(Professors professors)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(professors));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO Professors (FirstName, Surname)
VALUES (@FirstName, @Surname)";
connection.Execute(queryInsert, professors);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteProfessors(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Professors
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Professors> ReadProfessors()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Professors";
var professors = connection.Query<Professors>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(professors));
return professors;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Professors ReadProfessorsById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Professors
WHERE Id=@id";
var professors = connection.QueryFirst<Professors>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(professors));
return professors;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateProfessors(Professors professorsName)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(professorsName));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Professors
SET
FirstName=@FirstName,
Surname=@Surname
WHERE Id=@Id";
connection.Execute(queryUpdate, professorsName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,56 +1,128 @@
using StudentProgress.Entities;
using System.Collections.Generic;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
using StudentProgress.Repositories;
using System.Data.SqlClient;
namespace StudentProgress.Repositories.Implementations
namespace StudentPerformance.Repositories.Implementations;
public class StudentRepository : IStudentRepository
{
public class StudentRepository : IStudentRepository
private readonly IConnectionString _connectionString;
private readonly ILogger<StudentRepository> _logger;
public StudentRepository(IConnectionString connectionString, ILogger<StudentRepository> logger)
{
private readonly List<Student> _students;
_connectionString = connectionString;
_logger = logger;
}
public StudentRepository()
public void CreateStudent(Student student)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(student));
try
{
// Инициализация пустого списка студентов
_students = new List<Student>();
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Student (Name, Surname, GroupId)
VALUES (@Name, @Surname, @GroupId)";
connection.Execute(queryInsert, student);
}
public void CreateStudent(Student student)
catch (Exception ex)
{
// Логика создания студента
_students.Add(student);
}
public void DeleteStudent(int id)
{
// Логика удаления студента по идентификатору
_students.RemoveAll(s => s.Id == id);
}
public Student ReadStudentById(int id)
{
// Логика чтения студента по идентификатору
return _students.Find(s => s.Id == id);
}
public IEnumerable<Student> ReadStudents(int? groupID = null)
{
// Логика чтения всех студентов с возможностью фильтрации по идентификатору группы
if (groupID.HasValue)
{
return _students.FindAll(s => s.GroupId == groupID.Value);
}
return _students;
}
public void UpdateStudent(Student student)
{
// Логика обновления студента
var existingStudent = _students.Find(s => s.Id == student.Id);
if (existingStudent != null)
{
existingStudent.Name = student.Name;
existingStudent.Surname = student.Surname;
existingStudent.GroupId = student.GroupId;
}
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
}
public void DeleteStudent(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Student
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Student ReadStudentById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Student
WHERE Id=@id";
var student = connection.QueryFirst<Student>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(student));
return student;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Student> ReadStudents(int? groupID = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Student";
var student = connection.Query<Student>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(student));
return student;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateStudent(Student student)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(student));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Student
SET
Name=@Name,
Surname=@Surname,
GroupId=@GroupId
WHERE Id=@Id";
connection.Execute(queryUpdate, student);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,28 +1,124 @@
using StudentProgress.Entities;
using System.Collections.Generic;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities;
namespace StudentProgress.Repositories.Implementations;
public class SubjectsRepository : ISubjectsRepository
namespace StudentProgress.Repositories.Implementations
{
public void CreateSubjects(Subjects subject)
public class SubjectsRepository : ISubjectsRepository
{
// Логика создания предмета
}
private readonly IConnectionString _connectionString;
private readonly ILogger<SubjectsRepository> _logger;
public void CreateSubjects_(Subjects subject)
{
throw new NotImplementedException();
}
public SubjectsRepository(IConnectionString connectionString, ILogger<SubjectsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void DeleteSubjects(int id)
{
// Логика удаления предмета по идентификатору
}
public void CreateSubjects_(Subjects subject)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(subject));
public IEnumerable<Subjects> ReadSubjects(int? lecturerNameId = null)
{
// Логика чтения предметов с возможностью фильтрации по идентификатору преподавателя
return new List<Subjects>();
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO Subjects (NameSubject, Course)
VALUES (@NameSubject, @Course)";
connection.Execute(queryInsert, subject);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSubjects(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Subjects
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Subjects> ReadSubjects(int? id = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Subjects";
var subjects = connection.Query<Subjects>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(subjects));
return subjects;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Subjects ReadSubjectById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Subjects
WHERE Id=@id";
var subject = connection.QueryFirst<Subjects>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(subject));
return subject;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateSubject(Subjects subject)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(subject));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryUpdate = @"UPDATE Subjects
SET
NameSubject = @NameSubject,
Course = @Course
WHERE Id = @Id";
connection.Execute(queryUpdate, subject, transaction);
transaction.Commit();
_logger.LogInformation("Объект с Id: {id} успешно обновлен", subject.Id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}
}

View File

@ -9,7 +9,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Container" Version="5.11.11" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log.txt",
"rollingInterval": "Day"
}
}
]
}
}