ПИбд-22. Халиуллов Р.М. Лабораторная работа №3 #3

Closed
rakhaliullov wants to merge 3 commits from LabWork3 into LabWork2
36 changed files with 1919 additions and 116 deletions

View File

@ -1,10 +1,4 @@
using ProjectShedule.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;
namespace ProjectShedule.Entities;
public class Curriculum
{

View File

@ -1,28 +1,35 @@
using ProjectShedule.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;
public class CurriculumSubject
{
public int Id { get; set; }
public DateTime Date { get; private set; }
public int CurriculumId { get; private set; }
public IEnumerable<SubjectSubject> SubjectSubject { get; private set; } = [];
public Course Course { get; private set; }
public static CurriculumSubject CreateCurriculumSubject(int id, int curriculumId, Course course, IEnumerable<SubjectSubject> subjectSubjects)
public static CurriculumSubject CreateCurriculumSubject(int id, DateTime date, int curriculumId, Course course, IEnumerable<SubjectSubject> subjectSubjects)
{
return new CurriculumSubject()
{
Id = id,
Date = date,
CurriculumId = curriculumId,
Course = course,
SubjectSubject = subjectSubjects
};
}
public static CurriculumSubject CreateCurriculumSubject(TempCurriculumSubject tempCurriculumSubject, IEnumerable<SubjectSubject> subjectSubject)
{
return new CurriculumSubject
{
Id = tempCurriculumSubject.Id,
Date = tempCurriculumSubject.Date,
CurriculumId = tempCurriculumSubject.CurriculumId,
Course = tempCurriculumSubject.Course,
SubjectSubject = subjectSubject
};
}
}

View File

@ -1,9 +1,4 @@
using ProjectShedule.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;
@ -12,13 +7,14 @@ public class Shedule
public int Id { get; private set; }
public DateTime Date { get; private set; }
public PairNumber PairNumber { get; private set; }
public int PairCount { get; private set; }
public int StudentsGroupId { get; private set; }
public int TeacherId { get; private set; }
public int SubjectId { get; private set; }
public int ClassroomId { get; private set; }
public static Shedule CreateOperation(int id, DateTime date, PairNumber pairNumber
public static Shedule CreateOperation(int id, DateTime date, PairNumber pairNumber, int pairCount
, int studentsGroupId, int teacherId, int subjectId, int classroomId)
{
return new Shedule
@ -26,6 +22,7 @@ public class Shedule
Id = id,
Date = date,
PairNumber = pairNumber,
PairCount = pairCount,
StudentsGroupId = studentsGroupId,
TeacherId = teacherId,
SubjectId = subjectId,

View File

@ -1,9 +1,4 @@
using ProjectShedule.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;
namespace ProjectShedule.Entities;
public class Subject
{

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectShedule.Entities;
public class SubjectSubject

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectShedule.Entities;
namespace ProjectShedule.Entities;
public class Teacher
{

View File

@ -0,0 +1,13 @@
using ProjectShedule.Entities.Enums;
namespace ProjectShedule.Entities;
public class TempCurriculumSubject
{
public int Id { get; private set; }
public DateTime Date { get; private set; }
public int CurriculumId { get; private set; }
public int SubjectId { get; private set; }
public int LessonsCount { get; private set; }
public Course Course { get; private set; }
}

View File

@ -39,6 +39,9 @@
createSheduleToolStripMenuItem = new ToolStripMenuItem();
createCurriculumToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
directoryReportToolStripMenuItem = new ToolStripMenuItem();
sheduleReportToolStripMenuItem = new ToolStripMenuItem();
lessonsCountToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
SuspendLayout();
//
@ -62,35 +65,35 @@
// classroomToolStripMenuItem
//
classroomToolStripMenuItem.Name = "classroomToolStripMenuItem";
classroomToolStripMenuItem.Size = new Size(224, 26);
classroomToolStripMenuItem.Size = new Size(216, 26);
classroomToolStripMenuItem.Text = "Аудитории";
classroomToolStripMenuItem.Click += classroomToolStripMenuItem_Click;
//
// teacherToolStripMenuItem
//
teacherToolStripMenuItem.Name = "teacherToolStripMenuItem";
teacherToolStripMenuItem.Size = new Size(224, 26);
teacherToolStripMenuItem.Size = new Size(216, 26);
teacherToolStripMenuItem.Text = "Преподаватели";
teacherToolStripMenuItem.Click += teacherToolStripMenuItem_Click;
//
// subjectsToolStripMenuItem
//
subjectsToolStripMenuItem.Name = "subjectsToolStripMenuItem";
subjectsToolStripMenuItem.Size = new Size(224, 26);
subjectsToolStripMenuItem.Size = new Size(216, 26);
subjectsToolStripMenuItem.Text = "Дисциплины";
subjectsToolStripMenuItem.Click += subjectsToolStripMenuItem_Click;
//
// curriculumsToolStripMenuItem
//
curriculumsToolStripMenuItem.Name = "curriculumsToolStripMenuItem";
curriculumsToolStripMenuItem.Size = new Size(224, 26);
curriculumsToolStripMenuItem.Size = new Size(216, 26);
curriculumsToolStripMenuItem.Text = "Направлении";
curriculumsToolStripMenuItem.Click += curriculumsToolStripMenuItem_Click;
//
// studentGroupsToolStripMenuItem
//
studentGroupsToolStripMenuItem.Name = "studentGroupsToolStripMenuItem";
studentGroupsToolStripMenuItem.Size = new Size(224, 26);
studentGroupsToolStripMenuItem.Size = new Size(216, 26);
studentGroupsToolStripMenuItem.Text = "Группы студентов";
studentGroupsToolStripMenuItem.Click += studentGroupsToolStripMenuItem_Click;
//
@ -117,10 +120,35 @@
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, sheduleReportToolStripMenuItem, lessonsCountToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(73, 24);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// directoryReportToolStripMenuItem
//
directoryReportToolStripMenuItem.Name = "directoryReportToolStripMenuItem";
directoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
directoryReportToolStripMenuItem.Size = new Size(432, 26);
directoryReportToolStripMenuItem.Text = "Документ со справочниками ";
directoryReportToolStripMenuItem.Click += directoryReportToolStripMenuItem_Click;
//
// sheduleReportToolStripMenuItem
//
sheduleReportToolStripMenuItem.Name = "sheduleReportToolStripMenuItem";
sheduleReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
sheduleReportToolStripMenuItem.Size = new Size(432, 26);
sheduleReportToolStripMenuItem.Text = "Cводка по прохождению учебного плана";
sheduleReportToolStripMenuItem.Click += sheduleReportToolStripMenuItem_Click;
//
// lessonsCountToolStripMenuItem
//
lessonsCountToolStripMenuItem.Name = "lessonsCountToolStripMenuItem";
lessonsCountToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
lessonsCountToolStripMenuItem.Size = new Size(432, 26);
lessonsCountToolStripMenuItem.Text = "Количество занятий для дисциплин";
lessonsCountToolStripMenuItem.Click += lessonsCountToolStripMenuItem_Click;
//
// FormSchedulingBureau
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -152,5 +180,8 @@
private ToolStripMenuItem createSheduleToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem createCurriculumToolStripMenuItem;
private ToolStripMenuItem directoryReportToolStripMenuItem;
private ToolStripMenuItem sheduleReportToolStripMenuItem;
private ToolStripMenuItem lessonsCountToolStripMenuItem;
}
}

View File

@ -1,5 +1,4 @@
using ProjectShedule.Forms;
using System.ComponentModel;
using Unity;
namespace ProjectShedule
@ -104,5 +103,44 @@ namespace ProjectShedule
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void directoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void sheduleReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormSheduleReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void lessonsCountToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormCurriculumSubjectDistributionReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -70,12 +70,11 @@
textBoxClassroomNumber.Name = "textBoxClassroomNumber";
textBoxClassroomNumber.Size = new Size(150, 27);
textBoxClassroomNumber.TabIndex = 3;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(47, 149);
label3.Location = new Point(47, 154);
label3.Name = "label3";
label3.Size = new Size(116, 20);
label3.TabIndex = 4;
@ -85,7 +84,7 @@
//
comboBoxTypeClassroom.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxTypeClassroom.FormattingEnabled = true;
comboBoxTypeClassroom.Location = new Point(219, 141);
comboBoxTypeClassroom.Location = new Point(218, 146);
comboBoxTypeClassroom.Name = "comboBoxTypeClassroom";
comboBoxTypeClassroom.Size = new Size(151, 28);
comboBoxTypeClassroom.TabIndex = 5;

View File

@ -35,15 +35,17 @@
comboBoxDirection = new ComboBox();
comboBoxCourse = new ComboBox();
groupBoxCurriculum = new GroupBox();
dataGridViewCur = new DataGridView();
Column1 = new DataGridViewComboBoxColumn();
Column2 = new DataGridViewTextBoxColumn();
dataGridView = new DataGridView();
ColumnSubject = new DataGridViewComboBoxColumn();
ColumnLessons = new DataGridViewTextBoxColumn();
dataGridViewCur = new DataGridView();
Column1 = new DataGridViewComboBoxColumn();
Column2 = new DataGridViewTextBoxColumn();
dateTimePicker1 = new DateTimePicker();
label2 = new Label();
groupBoxCurriculum.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewCur).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridViewCur).BeginInit();
SuspendLayout();
//
// buttonCancel
@ -69,7 +71,7 @@
// label4
//
label4.AutoSize = true;
label4.Location = new Point(115, 96);
label4.Location = new Point(115, 113);
label4.Name = "label4";
label4.Size = new Size(44, 20);
label4.TabIndex = 16;
@ -78,7 +80,7 @@
// label1
//
label1.AutoSize = true;
label1.Location = new Point(52, 44);
label1.Location = new Point(52, 73);
label1.Name = "label1";
label1.Size = new Size(107, 20);
label1.TabIndex = 11;
@ -88,7 +90,7 @@
//
comboBoxDirection.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxDirection.FormattingEnabled = true;
comboBoxDirection.Location = new Point(165, 36);
comboBoxDirection.Location = new Point(165, 65);
comboBoxDirection.Name = "comboBoxDirection";
comboBoxDirection.Size = new Size(150, 28);
comboBoxDirection.TabIndex = 10;
@ -97,7 +99,7 @@
//
comboBoxCourse.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxCourse.FormattingEnabled = true;
comboBoxCourse.Location = new Point(165, 93);
comboBoxCourse.Location = new Point(165, 110);
comboBoxCourse.Name = "comboBoxCourse";
comboBoxCourse.Size = new Size(150, 28);
comboBoxCourse.TabIndex = 20;
@ -114,33 +116,6 @@
groupBoxCurriculum.TabStop = false;
groupBoxCurriculum.Text = "Учбеный план";
//
// dataGridViewCur
//
dataGridViewCur.AllowUserToResizeColumns = false;
dataGridViewCur.AllowUserToResizeRows = false;
dataGridViewCur.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCur.Columns.AddRange(new DataGridViewColumn[] { Column1, Column2 });
dataGridViewCur.Dock = DockStyle.Fill;
dataGridViewCur.Location = new Point(3, 23);
dataGridViewCur.Name = "dataGridViewCur";
dataGridViewCur.RowHeadersWidth = 51;
dataGridViewCur.Size = new Size(354, 289);
dataGridViewCur.TabIndex = 0;
//
// Column1
//
Column1.HeaderText = "Column1";
Column1.MinimumWidth = 6;
Column1.Name = "Column1";
Column1.Width = 125;
//
// Column2
//
Column2.HeaderText = "Column2";
Column2.MinimumWidth = 6;
Column2.Name = "Column2";
Column2.Width = 125;
//
// dataGridView
//
dataGridView.AllowUserToResizeColumns = false;
@ -171,11 +146,56 @@
ColumnLessons.MinimumWidth = 6;
ColumnLessons.Name = "ColumnLessons";
//
// dataGridViewCur
//
dataGridViewCur.AllowUserToResizeColumns = false;
dataGridViewCur.AllowUserToResizeRows = false;
dataGridViewCur.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCur.Columns.AddRange(new DataGridViewColumn[] { Column1, Column2 });
dataGridViewCur.Dock = DockStyle.Fill;
dataGridViewCur.Location = new Point(3, 23);
dataGridViewCur.Name = "dataGridViewCur";
dataGridViewCur.RowHeadersWidth = 51;
dataGridViewCur.Size = new Size(354, 289);
dataGridViewCur.TabIndex = 0;
//
// Column1
//
Column1.HeaderText = "Column1";
Column1.MinimumWidth = 6;
Column1.Name = "Column1";
Column1.Width = 125;
//
// Column2
//
Column2.HeaderText = "Column2";
Column2.MinimumWidth = 6;
Column2.Name = "Column2";
Column2.Width = 125;
//
// dateTimePicker1
//
dateTimePicker1.Location = new Point(165, 23);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(150, 27);
dateTimePicker1.TabIndex = 22;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(24, 30);
label2.Name = "label2";
label2.Size = new Size(135, 20);
label2.TabIndex = 23;
label2.Text = "Дата составления:";
//
// FormCurriculumSubject
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(384, 522);
Controls.Add(label2);
Controls.Add(dateTimePicker1);
Controls.Add(groupBoxCurriculum);
Controls.Add(comboBoxCourse);
Controls.Add(buttonCancel);
@ -186,8 +206,8 @@
Name = "FormCurriculumSubject";
Text = "Составление учебного плана";
groupBoxCurriculum.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewCur).EndInit();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)dataGridViewCur).EndInit();
ResumeLayout(false);
PerformLayout();
}
@ -207,5 +227,7 @@
private DataGridView dataGridView;
private DataGridViewComboBoxColumn ColumnSubject;
private DataGridViewTextBoxColumn ColumnLessons;
private DateTimePicker dateTimePicker1;
private Label label2;
}
}

View File

@ -1,6 +1,7 @@
using ProjectShedule.Entities;
using ProjectShedule.Entities.Enums;
using ProjectShedule.Repositories;
using System.Linq;
namespace ProjectShedule.Forms
@ -25,8 +26,6 @@ namespace ProjectShedule.Forms
ColumnSubject.DataSource = subjectRepository.ReadSubject();
ColumnSubject.DisplayMember = "Name";
ColumnSubject.ValueMember = "Id";
}
private void buttonSave_Click(object sender, EventArgs e)
@ -39,6 +38,7 @@ namespace ProjectShedule.Forms
throw new Exception("Есть незаполненные поля");
}
_curriculumSubjectRepository.CreateCurriculumSubject(CurriculumSubject.CreateCurriculumSubject(0,
dateTimePicker1.Value,
(int)comboBoxDirection.SelectedValue!,
(Course)comboBoxCourse.SelectedItem!,
CreateListSubjectSubjectFromDataGrid()));
@ -67,7 +67,8 @@ namespace ProjectShedule.Forms
Convert.ToInt32(row.Cells["ColumnSubject"].Value),
Convert.ToInt32(row.Cells["ColumnLessons"].Value)));
}
return list;
return list.GroupBy(x => x.SubjectId, x => x.LessonsCount, (id, counts) =>
SubjectSubject.CreateOperation(0, id, counts.Sum())).ToList();
}
}
}

View File

@ -123,6 +123,18 @@
<metadata name="ColumnLessons.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSubject.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnLessons.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column1.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column2.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column1.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>

View File

@ -0,0 +1,110 @@
namespace ProjectShedule.Forms
{
partial class FormCurriculumSubjectDistributionReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonBuild = new Button();
buttonFile = new Button();
labelFileName = new Label();
label1 = new Label();
dateTimePicker = new DateTimePicker();
SuspendLayout();
//
// buttonBuild
//
buttonBuild.Location = new Point(21, 111);
buttonBuild.Margin = new Padding(3, 4, 3, 4);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(275, 31);
buttonBuild.TabIndex = 9;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += buttonBuild_Click;
//
// buttonFile
//
buttonFile.Location = new Point(21, 14);
buttonFile.Margin = new Padding(3, 4, 3, 4);
buttonFile.Name = "buttonFile";
buttonFile.Size = new Size(86, 31);
buttonFile.TabIndex = 8;
buttonFile.Text = "Выбрать";
buttonFile.UseVisualStyleBackColor = true;
buttonFile.Click += buttonFile_Click;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(115, 19);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(45, 20);
labelFileName.TabIndex = 7;
labelFileName.Text = "Файл";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(21, 62);
label1.Name = "label1";
label1.Size = new Size(44, 20);
label1.TabIndex = 6;
label1.Text = "Дата:";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(68, 57);
dateTimePicker.Margin = new Padding(3, 4, 3, 4);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(228, 27);
dateTimePicker.TabIndex = 5;
//
// FormCurriculumSubjectDistributionReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(323, 162);
Controls.Add(buttonBuild);
Controls.Add(buttonFile);
Controls.Add(labelFileName);
Controls.Add(label1);
Controls.Add(dateTimePicker);
Name = "FormCurriculumSubjectDistributionReport";
Text = "FormCurriculumSubjectDistributionReport";
Review

Заголовок формы оформлен неверно

Заголовок формы оформлен неверно
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonBuild;
private Button buttonFile;
private Label labelFileName;
private Label label1;
private DateTimePicker dateTimePicker;
}
}

View File

@ -0,0 +1,59 @@
using ProjectShedule.Reports;
using Unity;
namespace ProjectShedule.Forms
{
public partial class FormCurriculumSubjectDistributionReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormCurriculumSubjectDistributionReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void buttonFile_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFileName.Text = Path.GetFileName(_fileName);
}
}
private void buttonBuild_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePicker.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
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
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,131 @@
namespace ProjectShedule.Forms
{
partial class FormDirectoryReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
checkBoxGroups = new CheckBox();
buttonBuild = new Button();
checkBoxCurriculums = new CheckBox();
checkBoxSubjects = new CheckBox();
checkBoxTeachers = new CheckBox();
checkBoxClassrooms = new CheckBox();
SuspendLayout();
//
// checkBoxGroups
//
checkBoxGroups.AutoSize = true;
checkBoxGroups.Location = new Point(12, 203);
checkBoxGroups.Margin = new Padding(3, 4, 3, 4);
checkBoxGroups.Name = "checkBoxGroups";
checkBoxGroups.Size = new Size(83, 24);
checkBoxGroups.TabIndex = 11;
checkBoxGroups.Text = "Группы";
checkBoxGroups.UseVisualStyleBackColor = true;
//
// buttonBuild
//
buttonBuild.Location = new Point(10, 254);
buttonBuild.Margin = new Padding(3, 4, 3, 4);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(159, 31);
buttonBuild.TabIndex = 10;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += buttonBuild_Click;
//
// checkBoxCurriculums
//
checkBoxCurriculums.AutoSize = true;
checkBoxCurriculums.Location = new Point(12, 154);
checkBoxCurriculums.Margin = new Padding(3, 4, 3, 4);
checkBoxCurriculums.Name = "checkBoxCurriculums";
checkBoxCurriculums.Size = new Size(127, 24);
checkBoxCurriculums.TabIndex = 9;
checkBoxCurriculums.Text = "Направлении";
checkBoxCurriculums.UseVisualStyleBackColor = true;
//
// checkBoxSubjects
//
checkBoxSubjects.AutoSize = true;
checkBoxSubjects.Location = new Point(12, 106);
checkBoxSubjects.Margin = new Padding(3, 4, 3, 4);
checkBoxSubjects.Name = "checkBoxSubjects";
checkBoxSubjects.Size = new Size(121, 24);
checkBoxSubjects.TabIndex = 8;
checkBoxSubjects.Text = "Дисциплины";
checkBoxSubjects.UseVisualStyleBackColor = true;
//
// checkBoxTeachers
//
checkBoxTeachers.AutoSize = true;
checkBoxTeachers.Location = new Point(12, 58);
checkBoxTeachers.Margin = new Padding(3, 4, 3, 4);
checkBoxTeachers.Name = "checkBoxTeachers";
checkBoxTeachers.Size = new Size(140, 24);
checkBoxTeachers.TabIndex = 7;
checkBoxTeachers.Text = "Преподаватели";
checkBoxTeachers.UseVisualStyleBackColor = true;
//
// checkBoxClassrooms
//
checkBoxClassrooms.AutoSize = true;
checkBoxClassrooms.Location = new Point(12, 13);
checkBoxClassrooms.Margin = new Padding(3, 4, 3, 4);
checkBoxClassrooms.Name = "checkBoxClassrooms";
checkBoxClassrooms.Size = new Size(107, 24);
checkBoxClassrooms.TabIndex = 6;
checkBoxClassrooms.Text = "Аудитории";
checkBoxClassrooms.UseVisualStyleBackColor = true;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(187, 300);
Controls.Add(checkBoxGroups);
Controls.Add(buttonBuild);
Controls.Add(checkBoxCurriculums);
Controls.Add(checkBoxSubjects);
Controls.Add(checkBoxTeachers);
Controls.Add(checkBoxClassrooms);
Name = "FormDirectoryReport";
Text = "FormDirectoryReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxGroups;
private Button buttonBuild;
private CheckBox checkBoxCurriculums;
private CheckBox checkBoxSubjects;
private CheckBox checkBoxTeachers;
private CheckBox checkBoxClassrooms;
}
}

View File

@ -0,0 +1,52 @@
using ProjectShedule.Reports;
using Unity;
namespace ProjectShedule.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void buttonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxClassrooms.Checked && !checkBoxTeachers.Checked && !checkBoxSubjects.Checked && !checkBoxCurriculums.Checked && !checkBoxGroups.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if
(_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxClassrooms.Checked, checkBoxTeachers.Checked, checkBoxSubjects.Checked, checkBoxCurriculums.Checked, checkBoxGroups.Checked))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
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
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -33,7 +33,7 @@ namespace ProjectShedule.Forms
comboBoxClassroom.DataSource = classroomRepository.ReadClassroom();
comboBoxClassroom.DisplayMember = "Name";
comboBoxClassroom.ValueMember = "Id";
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
@ -43,15 +43,18 @@ namespace ProjectShedule.Forms
comboBoxClassroom.SelectedIndex < 0 || checkedListBox.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
}
PairNumber pairNumber = PairNumber.None;
int pairCount = 0;
foreach (var elem in checkedListBox.CheckedItems)
{
pairNumber |= (PairNumber)elem;
}
pairCount++;
}
_sheduleRepository.CreateShedule(Shedule.CreateOperation(0,
dateTimePicker.Value,
pairNumber,
pairCount,
(int)comboBoxGroup.SelectedValue!,
(int)comboBoxTeacher.SelectedValue!,
(int)comboBoxSubject.SelectedValue!,

View File

@ -0,0 +1,168 @@
namespace ProjectShedule.Forms
{
partial class FormSheduleReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
label4 = new Label();
label3 = new Label();
label2 = new Label();
label1 = new Label();
buttonBuild = new Button();
buttonFile = new Button();
textBoxFilePath = new TextBox();
comboBoxSubject = new ComboBox();
dateTimePickerStart = new DateTimePicker();
dateTimePickerEnd = new DateTimePicker();
SuspendLayout();
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(27, 183);
label4.Name = "label4";
label4.Size = new Size(90, 20);
label4.TabIndex = 19;
label4.Text = "Дата конца:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(27, 132);
label3.Name = "label3";
label3.Size = new Size(97, 20);
label3.TabIndex = 18;
label3.Text = "Дата начала:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(27, 75);
label2.Name = "label2";
label2.Size = new Size(73, 20);
label2.TabIndex = 17;
label2.Text = "Предмет:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(27, 23);
label1.Name = "label1";
label1.Size = new Size(112, 20);
label1.TabIndex = 16;
label1.Text = "Путь до файла:";
//
// buttonBuild
//
buttonBuild.Location = new Point(27, 233);
buttonBuild.Margin = new Padding(3, 4, 3, 4);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(338, 31);
buttonBuild.TabIndex = 15;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += buttonBuild_Click;
//
// buttonFile
//
buttonFile.Location = new Point(333, 19);
buttonFile.Margin = new Padding(3, 4, 3, 4);
buttonFile.Name = "buttonFile";
buttonFile.Size = new Size(30, 31);
buttonFile.TabIndex = 14;
buttonFile.Text = "...";
buttonFile.UseVisualStyleBackColor = true;
buttonFile.Click += buttonFile_Click;
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(137, 19);
textBoxFilePath.Margin = new Padding(3, 4, 3, 4);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.Size = new Size(189, 27);
textBoxFilePath.TabIndex = 13;
//
// comboBoxSubject
//
comboBoxSubject.FormattingEnabled = true;
comboBoxSubject.Location = new Point(137, 71);
comboBoxSubject.Margin = new Padding(3, 4, 3, 4);
comboBoxSubject.Name = "comboBoxSubject";
comboBoxSubject.Size = new Size(226, 28);
comboBoxSubject.TabIndex = 12;
//
// dateTimePickerStart
//
dateTimePickerStart.Location = new Point(137, 124);
dateTimePickerStart.Margin = new Padding(3, 4, 3, 4);
dateTimePickerStart.Name = "dateTimePickerStart";
dateTimePickerStart.Size = new Size(228, 27);
dateTimePickerStart.TabIndex = 11;
//
// dateTimePickerEnd
//
dateTimePickerEnd.Location = new Point(137, 175);
dateTimePickerEnd.Margin = new Padding(3, 4, 3, 4);
dateTimePickerEnd.Name = "dateTimePickerEnd";
dateTimePickerEnd.Size = new Size(228, 27);
dateTimePickerEnd.TabIndex = 10;
//
// FormSheduleReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(402, 278);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonBuild);
Controls.Add(buttonFile);
Controls.Add(textBoxFilePath);
Controls.Add(comboBoxSubject);
Controls.Add(dateTimePickerStart);
Controls.Add(dateTimePickerEnd);
Name = "FormSheduleReport";
Text = "Отчет по прохождению учебного плана";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label4;
private Label label3;
private Label label2;
private Label label1;
private Button buttonBuild;
private Button buttonFile;
private TextBox textBoxFilePath;
private ComboBox comboBoxSubject;
private DateTimePicker dateTimePickerStart;
private DateTimePicker dateTimePickerEnd;
}
}

View File

@ -0,0 +1,70 @@
using ProjectShedule.Reports;
using ProjectShedule.Repositories;
using Unity;
namespace ProjectShedule.Forms
{
public partial class FormSheduleReport : Form
{
private readonly IUnityContainer _container;
public FormSheduleReport(IUnityContainer container, ISubjectRepository subjectRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxSubject.DataSource = subjectRepository.ReadSubject();
comboBoxSubject.DisplayMember = "Name";
comboBoxSubject.ValueMember = "Id";
}
private void buttonFile_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
private void buttonBuild_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxSubject.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
}
if (dateTimePickerEnd.Value <= dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxSubject.SelectedValue!, dateTimePickerStart.Value, dateTimePickerEnd.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
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
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -10,11 +10,13 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="8.0.5" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<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" />

View File

@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
using ProjectShedule.Repositories;
namespace ProjectShedule.Reports;
internal class ChartReport
{
private readonly ICurriculumSubjectRepository _curriculumSubjectRepository;
private readonly ISubjectRepository _subjectRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(ICurriculumSubjectRepository curriculumSubjectRepository, ISubjectRepository subjectRepository, ILogger<ChartReport> logger)
{
_curriculumSubjectRepository = curriculumSubjectRepository ?? throw new ArgumentNullException(nameof(curriculumSubjectRepository));
_subjectRepository = subjectRepository ?? throw new ArgumentNullException(nameof(subjectRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Распределение занятий")
.AddPieChart("Дисциплины", GetData(dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
var subjectNames = _subjectRepository.ReadSubject()
.ToDictionary(f => f.Id, f => f.Name);
return _curriculumSubjectRepository
.ReadCurriculumSubject()
.Where(x => x.Date.Date == dateTime.Date)
.SelectMany(x => x.SubjectSubject)
.GroupBy(x => x.SubjectId)
.Select(g => (Caption: subjectNames[g.Key].ToString(), Value: (double)g.Sum(x => x.LessonsCount)))
.ToList();
}
}

View File

@ -0,0 +1,120 @@
using Microsoft.Extensions.Logging;
using ProjectShedule.Repositories;
namespace ProjectShedule.Reports;
internal class DocReport
{
private readonly IClassroomRepository _classroomRepository;
private readonly ITeacherRepository _teacherRepository;
private readonly ISubjectRepository _subjectRepository;
private readonly ICurriculumRepository _curriculumRepository;
private readonly IGroupRepository _groupRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IClassroomRepository classroomRepository,
ITeacherRepository teacherRepository,
ISubjectRepository subjectRepository,
ICurriculumRepository curriculumRepository,
IGroupRepository groupRepository,
ILogger<DocReport> logger)
{
_classroomRepository = classroomRepository ??
throw new ArgumentNullException(nameof(classroomRepository));
_teacherRepository = teacherRepository ??
throw new ArgumentNullException(nameof(teacherRepository));
_subjectRepository = subjectRepository ??
throw new ArgumentNullException(nameof(subjectRepository));
_curriculumRepository = curriculumRepository ??
throw new ArgumentNullException(nameof(curriculumRepository));
_groupRepository = groupRepository ??
throw new ArgumentNullException(nameof(groupRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeClassrooms,
bool includeTeachers, bool includeSubjects,
bool includeCurriculums, bool includeGroups)
{
try
{
var builder = new WordBuilder(filePath)
.AddHeader("Документ со справочниками");
if (includeClassrooms)
{
builder.AddParagraph("Аудитории")
.AddTable([2400, 1200, 2400],
GetClassrooms());
}
if (includeTeachers)
{
builder.AddParagraph("Преподаватели")
.AddTable([2400, 2400],
GetTeachers());
}
if (includeSubjects)
{
builder.AddParagraph("Дисциплины")
.AddTable([2400],
GetSubjects());
}
if (includeCurriculums)
{
builder.AddParagraph("Направлении")
.AddTable([2400],
GetCurriculums());
}
if (includeGroups)
{
builder.AddParagraph("Группы студентов")
.AddTable([2400, 2400, 1200, 2400],
GetGroups());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetClassrooms()
{
return [
["Размер", "Номер аудитории", "Тип"],
.. _classroomRepository.ReadClassroom().Select(x => new string[]
{ x.Size.ToString(), x.Name, x.ClassType.ToString() }),
];
}
private List<string[]> GetTeachers()
{
return [
["Имя", "Фамилия"],
.. _teacherRepository.ReadTeacher().Select(x => new string[] { x.FirstName, x.LastName }),
];
}
private List<string[]> GetSubjects()
{
return [
["Название предмета"],
.. _subjectRepository.ReadSubject().Select(x => new string[]
{ x.Name }),
];
}
private List<string[]> GetCurriculums()
{
return [
["Направление"],
.. _curriculumRepository.ReadCurriculum().Select(x => new string[]
{ x.Direction }),
];
}
private List<string[]> GetGroups()
{
return [
["Количество студентов", "Номер группы", "Курс", "Направление"],
.. _groupRepository.ReadGroup().Select(x => new string[]
{ x.StudentsCount.ToString(),x.GroupNumber.ToString(), x.Course.ToString(), x.CurriculumId.ToString()}),
];
}
}

View File

@ -0,0 +1,311 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace ProjectShedule.Reports;
internal class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells,
worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold() { Val = true }
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder()
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Right,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3,
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>().FirstOrDefault(c => c.CellReference != null &&
c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null &&
cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@ -0,0 +1,76 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace ProjectShedule.Reports;
public class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 14;
}
}

View File

@ -0,0 +1,71 @@
using Microsoft.Extensions.Logging;
using ProjectShedule.Repositories;
namespace ProjectShedule.Reports;
internal class TableReport
{
private readonly ICurriculumSubjectRepository _curriculumSubjectRepository;
private readonly ISheduleRepository _sheduleRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Дата", "Количество установленных занятий", "Количество поставленных занятий"];
public TableReport(ICurriculumSubjectRepository curriculumSubjectRepository, ISheduleRepository sheduleRepository, ILogger<TableReport> logger)
{
_curriculumSubjectRepository = curriculumSubjectRepository ?? throw new ArgumentNullException(nameof(curriculumSubjectRepository));
_sheduleRepository = sheduleRepository ?? throw new ArgumentNullException(nameof(sheduleRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int subjectId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по прохождению учебного плана", 0, 3)
.AddParagraph("за период", 0)
.AddTable([10, 15, 15], GetData(subjectId, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int subjectId, DateTime startDate, DateTime endDate)
{
var data = _curriculumSubjectRepository
.ReadCurriculumSubject()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.SubjectSubject.Any(y => y.SubjectId == subjectId))
.Select(x => new {Date = x.Date, CountIn = x.SubjectSubject.FirstOrDefault(y => y.SubjectId == subjectId)?.LessonsCount, CountOut = (int?)null})
.Union(
_sheduleRepository
.ReadShedule()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.SubjectId == subjectId)
.Select(x => new { Date = x.Date, CountIn = (int?)null, CountOut = x?.PairCount})
)
.OrderBy(x => x.Date);
var groupedData = data
.GroupBy(x => x.Date)
.Select(g => new
{
Date = g.Key,
TotalIn = g.Sum(x => x.CountIn),
TotalOut = g.Sum(x => x.CountOut)
})
.OrderBy(x => x.Date);
return
new List<string[]>() { item }
.Union( groupedData
.Select(x => new string[] { x.Date.ToString("dd.MM.yyyy"), x.TotalIn.ToString()!, x.TotalOut.ToString()! }))
.Union(
new[] { new string[] { "Всего", groupedData.Sum(x => x.TotalIn).ToString()!, groupedData.Sum(x => x.TotalOut).ToString()! } }
)
.ToList();
}
}

View File

@ -0,0 +1,125 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace ProjectShedule.Reports;
internal class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
var runProperties = run.AppendChild(new RunProperties());
runProperties.AppendChild(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
));
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth()
{
Width =
widths[j].ToString()
}),
new Paragraph(new Run(new RunProperties(new Bold()), new
Text(data.First()[j])))));
}
table.Append(tr);
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath,
WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}

View File

@ -4,7 +4,7 @@ namespace ProjectShedule.Repositories;
public interface ICurriculumSubjectRepository
{
IEnumerable<CurriculumSubject> ReadCurriculumSubject();
IEnumerable<CurriculumSubject> ReadCurriculumSubject(DateTime? dateForm = null, DateTime? dateTo = null, int? subjectId = null);
void DeleteCurriculumSubject(int id);
void CreateCurriculumSubject(CurriculumSubject curriculumSubject);
}

View File

@ -4,7 +4,7 @@ namespace ProjectShedule.Repositories;
public interface ISheduleRepository
{
IEnumerable<Shedule> ReadShedule(DateTime? dateTime = null, int? groupId = null);
IEnumerable<Shedule> ReadShedule(DateTime? dateForm = null, DateTime? dateTo = null, int? subjectId = null);
void CreateShedule(Shedule shedule);
void DeleteShedule(int id);
}

View File

@ -28,8 +28,8 @@ public class CurriculumSubjectRepository : ICurriculumSubjectRepository
using var transaction = connection.BeginTransaction();
var queryInsert =
@"
INSERT INTO CurriculumSubject (CurriculumId, Course)
VALUES (@CurriculumId, @Course);
INSERT INTO CurriculumSubject (Date, CurriculumId, Course)
VALUES (@Date, @CurriculumId, @Course);
SELECT MAX(Id) FROM CurriculumSubject";
var curriculumSubjectId =
connection.QueryFirst<int>(queryInsert, curriculumSubject, transaction);
@ -61,10 +61,19 @@ public class CurriculumSubjectRepository : ICurriculumSubjectRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM SubjectSubject
WHERE CurriculumSubjectId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM CurriculumSubject
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
DELETE FROM CurriculumSubject
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
@ -72,17 +81,19 @@ public class CurriculumSubjectRepository : ICurriculumSubjectRepository
throw;
}
}
public IEnumerable<CurriculumSubject> ReadCurriculumSubject()
public IEnumerable<CurriculumSubject> ReadCurriculumSubject(DateTime? dateForm = null, DateTime? dateTo = null, int? subjectId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM CurriculumSubject";
var curriculumSubjects = connection.Query<CurriculumSubject>(querySelect);
var querySelect = @"SELECT cs.*, ss.SubjectId, ss.LessonsCount FROM CurriculumSubject cs
INNER JOIN SubjectSubject ss on ss.CurriculumSubjectId = cs.Id";
var curriculumSubjects = connection.Query<TempCurriculumSubject>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(curriculumSubjects));
return curriculumSubjects;
return curriculumSubjects.GroupBy(x => x.Id, y => y, (key, value) => CurriculumSubject.CreateCurriculumSubject(value.First(),
value.Select(z => SubjectSubject.CreateOperation(0, z.SubjectId, z.LessonsCount)))).ToList();
}
catch (Exception ex)
{

View File

@ -23,8 +23,8 @@ public class SheduleRepository : ISheduleRepository
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Shedule (Date, PairNumber, StudentsGroupId, TeacherId, SubjectId, ClassroomId)
VALUES (@Date, @PairNumber, @StudentsGroupId, @TeacherId, @SubjectId, @ClassroomId)";
INSERT INTO Shedule (Date, PairNumber, PairCount, StudentsGroupId, TeacherId, SubjectId, ClassroomId)
VALUES (@Date, @PairNumber, @PairCount, @StudentsGroupId, @TeacherId, @SubjectId, @ClassroomId)";
connection.Execute(queryInsert, shedule);
}
catch (Exception ex)
@ -53,7 +53,7 @@ public class SheduleRepository : ISheduleRepository
}
}
public IEnumerable<Shedule> ReadShedule(DateTime? dateTime = null, int? groupId = null)
public IEnumerable<Shedule> ReadShedule(DateTime? dateForm = null, DateTime? dateTo = null, int? subjectId = null)
{
_logger.LogInformation("Получение всех объектов");
try