Pibd-22_Lyakhov_T_I_Lab2_Simple #3

Open
funa4i wants to merge 7 commits from LabWork2 into LabWrk01
17 changed files with 563 additions and 42 deletions

View File

@ -23,5 +23,6 @@ namespace StudentProgressRecord.Entity
Mark = mark
};
}
}
}

View File

@ -17,7 +17,7 @@ namespace StudentProgressRecord.Entity
public DateTime Date { get; set; }
public IEnumerable<Marks> Marks { get; private set; } = [];
public IEnumerable<Marks> Marks { get; set; } = [];
public static Statement CreateOperation(long id, long subjectId, long teacherId,
DateTime timeStamp, IEnumerable<Marks> marks)

View File

@ -16,7 +16,7 @@ namespace StudentProgressRecord.Entity
public Operations Operation { get; set; }
public DateTime TimeStamp { get; set; }
public DateTime Date { get; set; }
public static StudentTransition CreateOperation(long id, long studentId, Operations operation, DateTime time)
{
@ -25,7 +25,7 @@ namespace StudentProgressRecord.Entity
Id = id,
StudentId = studentId,
Operation = operation,
TimeStamp = time
Date = time
};
}
}

View File

@ -20,7 +20,8 @@ namespace StudentProgressRecord.Entity
return new Subject
{
Id = id,
Name = name
Name = name,
direction = direction
};
}
}

View File

@ -61,6 +61,7 @@
//
// dateTimePicker
//
dateTimePicker.Enabled = false;
dateTimePicker.Location = new Point(13, 163);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(250, 27);

View File

@ -35,9 +35,9 @@ namespace StudentProgressRecord.Forms
var list = new List<int>() {1,2,3,4,5};
columnMark.ValueType = typeof(int);
columnMark.DataSource = list;
columnStudent.DataSource = studentRepository.ReadStudents();
columnStudent.DisplayMember = "Name";
columnStudent.ValueMember = "Id";
@ -47,7 +47,7 @@ namespace StudentProgressRecord.Forms
{
try
{
if (dataGridView.RowCount < 1 || comboBoxTeacher.SelectedIndex < 0 || comboBoxSubject.SelectedIndex < 0)
if (dataGridView.RowCount < 2 || comboBoxTeacher.SelectedIndex < 0 || comboBoxSubject.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненые поля");
}
@ -58,6 +58,7 @@ namespace StudentProgressRecord.Forms
dateTimePicker.Value,
CreateMarkListFromDataGrid())
);
Close();
}
catch (Exception ex)
{

View File

@ -62,7 +62,8 @@ namespace StudentProgressRecord
{
try
{
if (string.IsNullOrWhiteSpace(textBoxSubject.Text) || checkedListBoxDir.Items.Count == 0)
if (string.IsNullOrWhiteSpace(textBoxSubject.Text) ||
checkedListBoxDir.CheckedItems.Count == 0)
{
throw new Exception("Имя не может быть пустым");
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentProgressRecord.IRepositories
{
public interface IConnectionString
{
string GetConnectionString();
}
}

View File

@ -1,9 +1,14 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using StudentProgressRecord.Forms;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Repositories;
using StudentProgressRecord.RepositoryImp;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace StudentProgressRecord
{
@ -23,6 +28,9 @@ namespace StudentProgressRecord
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IConnectionString,ConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IStatementRepository, StatementRepository>
(new TransientLifetimeManager());
@ -42,5 +50,16 @@ namespace StudentProgressRecord
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var lf = new LoggerFactory();
lf.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsetting.json")
.Build())
.CreateLogger());
return lf;
}
}
}

View File

@ -0,0 +1,18 @@
using Microsoft.VisualBasic.ApplicationServices;
using StudentProgressRecord.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentProgressRecord.RepositoryImp
{
public class ConnectionString : IConnectionString
{
public string GetConnectionString()
{
return "Server=localhost;Database=University;User Id=root;Password=password;";
}
}
}

View File

@ -1,29 +1,106 @@
using StudentProgressRecord.Entity;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgressRecord.Entity;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace StudentProgressRecord.RepositoryImp
{
public class StatementRepository : IStatementRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StatementRepository> _logger;
public StatementRepository(IConnectionString connectionString, ILogger<StatementRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStatement(Statement statement)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(statement));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Statement (SubjectId, TeacherId, Date)
VALUES (@SubjectId, @TeacherId, @Date);
SELECT MAX(Id) FROM Statement";
var statementID = connection.QueryFirst<int>(queryInsert, statement, transaction);
var querySubInsert = @"
INSERT INTO Marks (StatementId, StudentId, Mark)
VALUES (@StatementId, @StudentId,@Mark)";
foreach (var elem in statement.Marks)
{
connection.Execute(querySubInsert, new
{
statementID,
elem.StudentId,
elem.Mark
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteStatement(long id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryDelete = @"
DELETE FROM Statement
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Statement> ReadStatements(long? subjectId = null, long? teacherId = null,
DateTime? dateFrom = null, DateTime? dateTo = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = "SELECT * FROM Statement";
var objs = connection.Query<Statement>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(objs));
return objs;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -1,4 +1,10 @@
using StudentProgressRecord.Entity;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Serilog.Core;
using StudentProgressRecord.Entity;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Repositories;
using System;
using System.Collections.Generic;
@ -10,29 +16,117 @@ namespace StudentProgressRecord.RepositoryImp
{
public class StudentRepository : IStudentRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StudentRepository> _logger;
public StudentRepository(IConnectionString connectionString, ILogger<StudentRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStudent(Student student)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект, {json}", JsonConvert.SerializeObject(student));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var query = @"
INSERT INTO Student (Name, FamilyPos, Domitory)
VALUES (@Name, @FamilyPos, @Domitory)";
connection.Execute(query, student);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении обЪекта");
throw;
}
}
public void DeleteStudent(long id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryDelete = @"
DELETE FROM Student
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Student ReadStudentById(long id)
{
return Student.CreateEntity(0, string.Empty, false , false);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = @"
SELECT * FROM Student
WHERE Id=@id";
var obj = connection.QueryFirst<Student>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(obj));
return obj;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Student> ReadStudents(bool? familyPos = null, bool? domitory = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = "SELECT * FROM Student";
var objs = connection.Query<Student>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(objs));
return objs;
}
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.GetConnectionString());
var queryUpdate = @"
UPDATE Student
SET
Name=@Name,
FamilyPos=@FamilyPos,
Domitory=@Domitory
WHERE Id=@Id";
connection.Execute(queryUpdate, student);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -1,28 +1,101 @@
using StudentProgressRecord.Entity;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Entity.Enums;
using Newtonsoft.Json;
using Npgsql;
using Microsoft.Extensions.Logging;
using Dapper;
namespace StudentProgressRecord.RepositoryImp
{
public class StudentTransitionRepository : IStudentTransitionRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StudentTransitionRepository> _logger;
public StudentTransitionRepository(IConnectionString connectionString, ILogger<StudentTransitionRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStudentTransition(StudentTransition studentTransition)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект, {json}", JsonConvert.SerializeObject(studentTransition));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var query = @"
INSERT INTO StudentTransition (StudentId, Operation, Date)
VALUES (@StudentId, @Operation, @Date)";
connection.Execute(query, studentTransition);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении обЪекта");
throw;
}
}
public void DeleteStudentTransition(long id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryDelete = @"
DELETE FROM StudentTransition
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public StudentTransition ReadStudentTransitionById(long id)
{
return StudentTransition.CreateOperation(0, 0, Operations.Transfer, DateTime.Now);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = @"
SELECT * FROM StudentTransition
WHERE Id=@id";
var obj = connection.QueryFirst<StudentTransition>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(obj));
return obj;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<StudentTransition> ReadStudentTransitions(long? groupId = null, bool? familyPos = null, bool? domitory = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = "SELECT * FROM StudentTransition";
var objs = connection.Query<StudentTransition>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(objs));
return objs;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -1,39 +1,126 @@
using StudentProgressRecord.Entity;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgressRecord.Entity;
using StudentProgressRecord.Entity.Enums;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentProgressRecord.RepositoryImp
{
public class SubjectRepository : ISubjectRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SubjectRepository> _logger;
public SubjectRepository(IConnectionString connectionString, ILogger<SubjectRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSubject(Subject subject)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект, {json}", JsonConvert.SerializeObject(subject));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var query = @"
INSERT INTO Subject (direction, Name)
VALUES (@direction ,@Name)";
connection.Execute(query, subject);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении обЪекта");
throw;
}
}
public void DeleteSubject(long id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryDelete = @"
DELETE FROM Subject
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Subject ReadSubjectById(long id)
{
return Subject.CreateEntity(0, string.Empty, Direction.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = @"
SELECT * FROM Subject
WHERE Id=@id";
var obj = connection.QueryFirst<Subject>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(obj));
return obj;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Subject> ReadSubjects()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = "SELECT * FROM Subject";
var objs = connection.Query<Subject>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(objs));
return objs;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateSubject(Subject subject)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(subject));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryUpdate = @"
UPDATE Subject
SET
Name=@Name
WHERE Id=@Id";
connection.Execute(queryUpdate, subject);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -1,8 +1,14 @@
using StudentProgressRecord.Entity;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using StudentProgressRecord.Entity;
using StudentProgressRecord.IRepositories;
using StudentProgressRecord.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
@ -10,28 +16,118 @@ namespace StudentProgressRecord.RepositoryImp
{
public class TeacherRepository : ITeacherRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<TeacherRepository> _logger;
public TeacherRepository(IConnectionString connectionString, ILogger<TeacherRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateTeacher(Teacher teacher)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект, {json}", JsonConvert.SerializeObject(teacher));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var query = @"
INSERT INTO Teacher (Name)
VALUES (@Name)";
connection.Execute(query, teacher);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении обЪекта");
throw;
}
}
public void DeleteTeacher(long id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryDelete = @"
DELETE FROM Teacher
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Teacher ReadTeacherById(long id)
{
return Teacher.CreateEntity(0, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = @"
SELECT * FROM Teacher
WHERE Id=@id";
var obj = connection.QueryFirst<Teacher>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(obj));
return obj;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Teacher> ReadTeachers(long? departmentID = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var querySelect = "SELECT * FROM Teacher";
var objs = connection.Query<Teacher>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(objs));
return objs;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateTeacher(Teacher teacher)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(teacher));
try
{
using var connection = new NpgsqlConnection(_connectionString.GetConnectionString());
var queryUpdate = @"
UPDATE Teacher
SET
Name=@Name
WHERE Id=@Id";
connection.Execute(queryUpdate, teacher);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -9,9 +9,29 @@
</PropertyGroup>
<ItemGroup>
<None Remove="appsetting.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsetting.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="8.0.5" />
<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="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Abstractions" Version="5.11.7" />
<PackageReference Include="Unity.Container" Version="5.11.11" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -29,4 +49,8 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</Project>

View File

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