лабораторная работа №2

This commit is contained in:
vkobi 2024-11-24 17:03:10 +04:00
parent 93c765b48b
commit 2a44642cf9
18 changed files with 537 additions and 98 deletions

View File

@ -9,13 +9,15 @@ public class Medicine
public int Id { get; set; }
public MedicineType MedicineType { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Description { get; private set; } = string.Empty;
public static Medicine CreateEntity(int id, MedicineType medicineType, string description)
public static Medicine CreateEntity(int id, MedicineType medicineType, string name, string description)
{
return new Medicine
{
Id = id,
MedicineType = medicineType,
Name = name,
Description = description ?? string.Empty
};
}

View File

@ -11,7 +11,7 @@ public class ReceptionMedicine
{
Id = id,
MedicineId = medicineId,
Count = count
Count = count,
};
}
}

View File

@ -34,6 +34,8 @@
textBoxDescription = new TextBox();
ButtonSave = new Button();
ButtonCancel = new Button();
textBoxName = new TextBox();
label3 = new Label();
SuspendLayout();
//
// label1
@ -56,7 +58,7 @@
// label2
//
label2.AutoSize = true;
label2.Location = new Point(65, 190);
label2.Location = new Point(65, 217);
label2.Name = "label2";
label2.Size = new Size(82, 20);
label2.TabIndex = 2;
@ -64,7 +66,7 @@
//
// textBoxDescription
//
textBoxDescription.Location = new Point(195, 190);
textBoxDescription.Location = new Point(195, 217);
textBoxDescription.Multiline = true;
textBoxDescription.Name = "textBoxDescription";
textBoxDescription.Size = new Size(247, 72);
@ -90,11 +92,30 @@
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// textBoxName
//
textBoxName.Location = new Point(195, 171);
textBoxName.Multiline = true;
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(247, 28);
textBoxName.TabIndex = 7;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(65, 171);
label3.Name = "label3";
label3.Size = new Size(80, 20);
label3.TabIndex = 6;
label3.Text = "Название:";
//
// FormMedicine
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(593, 421);
Controls.Add(textBoxName);
Controls.Add(label3);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(textBoxDescription);
@ -116,5 +137,7 @@
private TextBox textBoxDescription;
private Button ButtonSave;
private Button ButtonCancel;
private TextBox textBoxName;
private Label label3;
}
}

View File

@ -38,6 +38,7 @@ public partial class FormMedicine : Form
}
textBoxDescription.Text = medicine.Description;
textBoxName.Text = medicine.Name;
_medicineId = value;
}
catch (Exception ex)
@ -62,7 +63,7 @@ public partial class FormMedicine : Form
{
try
{
if (string.IsNullOrWhiteSpace(textBoxDescription.Text) || checkedListBoxMedicineType.CheckedItems.Count == 0)
if (string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxDescription.Text) || checkedListBoxMedicineType.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
@ -91,6 +92,6 @@ public partial class FormMedicine : Form
{
medicineType |= (MedicineType)elem;
}
return Medicine.CreateEntity(id, medicineType, textBoxDescription.Text);
return Medicine.CreateEntity(id, medicineType, textBoxName.Text, textBoxDescription.Text);
}
}

View File

@ -40,10 +40,10 @@
ButtonCancel = new Button();
groupBoxMedicine = new GroupBox();
dataGridViewMedicines = new DataGridView();
Column1 = new DataGridViewComboBoxColumn();
Column2 = new DataGridViewTextBoxColumn();
label5 = new Label();
dateTimePickerReception = new DateTimePicker();
ColumnMedicine = new DataGridViewComboBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
groupBoxMedicine.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewMedicines).BeginInit();
SuspendLayout();
@ -158,7 +158,7 @@
dataGridViewMedicines.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridViewMedicines.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewMedicines.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewMedicines.Columns.AddRange(new DataGridViewColumn[] { Column1, Column2 });
dataGridViewMedicines.Columns.AddRange(new DataGridViewColumn[] { ColumnMedicine, ColumnCount });
dataGridViewMedicines.Location = new Point(3, 23);
dataGridViewMedicines.MultiSelect = false;
dataGridViewMedicines.Name = "dataGridViewMedicines";
@ -168,18 +168,6 @@
dataGridViewMedicines.Size = new Size(276, 121);
dataGridViewMedicines.TabIndex = 0;
//
// Column1
//
Column1.HeaderText = "Лекарство";
Column1.MinimumWidth = 6;
Column1.Name = "Column1";
//
// Column2
//
Column2.HeaderText = "Количество";
Column2.MinimumWidth = 6;
Column2.Name = "Column2";
//
// label5
//
label5.AutoSize = true;
@ -197,6 +185,18 @@
dateTimePickerReception.Size = new Size(178, 27);
dateTimePickerReception.TabIndex = 12;
//
// ColumnMedicine
//
ColumnMedicine.HeaderText = "Лекарство";
ColumnMedicine.MinimumWidth = 6;
ColumnMedicine.Name = "ColumnMedicine";
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
//
// FormReception
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -237,9 +237,9 @@
private Button ButtonCancel;
private GroupBox groupBoxMedicine;
private DataGridView dataGridViewMedicines;
private DataGridViewComboBoxColumn Column1;
private DataGridViewTextBoxColumn Column2;
private Label label5;
private DateTimePicker dateTimePickerReception;
private DataGridViewComboBoxColumn ColumnMedicine;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -1,6 +1,7 @@
using RegistrationOfPatients.Entities;
using RegistrationOfPatients.Entities.Enums;
using RegistrationOfPatients.Repositories;
using RegistrationOfPatients.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -19,7 +20,7 @@ public partial class FormReception : Form
private int? _receptionId;
public FormReception(IReceptionRepository receptionRepository, IPatientRepository patientRepository, IDoctorRepository doctorRepository)
public FormReception(IReceptionRepository receptionRepository, IPatientRepository patientRepository, IDoctorRepository doctorRepository, IMedicineRepository medicineRepository)
{
InitializeComponent();
_receptionRepository = receptionRepository ?? throw new ArgumentNullException(nameof(receptionRepository));
@ -33,6 +34,10 @@ public partial class FormReception : Form
comboBoxDoctor.DataSource = doctorRepository.ReadDoctors();
comboBoxDoctor.DisplayMember = "DoctorName";
comboBoxDoctor.ValueMember = "Id";
ColumnMedicine.DataSource = medicineRepository.ReadMedicine();
ColumnMedicine.DisplayMember = "Name";
ColumnMedicine.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
@ -60,11 +65,11 @@ public partial class FormReception : Form
var list = new List<ReceptionMedicine>();
foreach (DataGridViewRow row in dataGridViewMedicines.Rows)
{
if (row.Cells["ColumnFeed"].Value == null || row.Cells["ColumnCount"].Value == null)
if (row.Cells["ColumnMedicine"].Value == null || row.Cells["ColumnCount"].Value == null)
{
continue;
}
list.Add(ReceptionMedicine.CreateElement(0, Convert.ToInt32(row.Cells["ColumnFeed"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value)));
list.Add(ReceptionMedicine.CreateElement(0, Convert.ToInt32(row.Cells["ColumnMedicine"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value)));
}
return list;
}

View File

@ -117,16 +117,10 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="Column1.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<metadata name="ColumnMedicine.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>
<metadata name="Column2.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -39,9 +39,9 @@
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(639, 0);
panel1.Location = new Point(704, 0);
panel1.Name = "panel1";
panel1.Size = new Size(161, 450);
panel1.Size = new Size(161, 437);
panel1.TabIndex = 0;
//
// buttonAdd
@ -71,14 +71,14 @@
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 51;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(639, 450);
dataGridViewData.Size = new Size(704, 437);
dataGridViewData.TabIndex = 1;
//
// FormReceptions
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(865, 437);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormReceptions";

View File

@ -1,7 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using RegistrationOfPatients.Repositories;
using RegistrationOfPatients.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace RegistrationOfPatients
{
@ -23,13 +27,28 @@ namespace RegistrationOfPatients
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IDoctorRepository, DoctorRepository>(new TransientLifetimeManager());
container.RegisterType<IPatientRepository, PatientRepository>(new TransientLifetimeManager());
container.RegisterType<IPaymentRepository, PaymentRepository>(new TransientLifetimeManager());
container.RegisterType<IReceptionRepository, ReceptionRepository>(new TransientLifetimeManager());
container.RegisterType<IMedicineRepository, MedicineRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>(new TransientLifetimeManager());
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@ -9,7 +9,19 @@
</PropertyGroup>
<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="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -27,4 +39,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegistrationOfPatients.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=mydatabase;";
}

View File

@ -1,6 +1,12 @@
using RegistrationOfPatients.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RegistrationOfPatients.Entities;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,28 +15,98 @@ namespace RegistrationOfPatients.Repositories.Implementations;
public class DoctorRepository : IDoctorRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DoctorRepository> _logger;
public DoctorRepository(IConnectionString connectionString, ILogger<DoctorRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateDoctor(Doctor doctor)
{
}
public void DeleteDoctor(int id)
{
}
public IEnumerable<Doctor> ReadDoctors()
{
return [];
}
public Doctor ReadDoctorById(int id)
{
return Doctor.CreateEntity(0, string.Empty);
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(doctor));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Doctor (Name) VALUES (@Name)";
connection.Execute(queryInsert, doctor);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateDoctor(Doctor doctor)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(doctor));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @" UPDATE Doctor SET Name=@Name WHERE Id=@Id"; connection.Execute(queryUpdate, doctor);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteDoctor(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" DELETE FROM Doctor WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Doctor> ReadDoctors()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Doctor";
var doctors = connection.Query<Doctor>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(doctors));
return doctors;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Doctor ReadDoctorById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" SELECT * FROM Doctor WHERE Id=@id";
var doctor = connection.QueryFirst<Doctor>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(doctor));
return doctor;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
}

View File

@ -1,30 +1,109 @@
using Microsoft.VisualBasic.FileIO;
using Dapper;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using Npgsql;
using RegistrationOfPatients.Entities;
using RegistrationOfPatients.Entities.Enums;
using System.Data.SqlClient;
using System.Numerics;
namespace RegistrationOfPatients.Repositories.Implementations;
public class MedicineRepository : IMedicineRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<MedicineRepository> _logger;
public MedicineRepository(IConnectionString connectionString, ILogger<MedicineRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateMedicine(Medicine medicine)
{
}
public void DeleteMedicine(int id)
{
}
public Medicine ReadMedicineById(int id)
{
return Medicine.CreateEntity(0, MedicineType.None, string.Empty);
}
public IEnumerable<Medicine> ReadMedicine()
{
return [];
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(medicine));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Medicine (MedicineType, Description, Name) VALUES (@MedicineType, @Description, @Name)";
connection.Execute(queryInsert, medicine);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateMedicine(Medicine medicine)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(medicine));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @" UPDATE Medicine SET MedicineType=@MedicineType, Description=@Description, Name=@Name WHERE Id=@Id"; connection.Execute(queryUpdate, medicine);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteMedicine(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" DELETE FROM Medicine WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Medicine ReadMedicineById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" SELECT * FROM Medicine WHERE Id=@id";
var medicine = connection.QueryFirst<Medicine>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(medicine));
return medicine;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Medicine> ReadMedicine()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Medicine";
var medicines = connection.Query<Medicine>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(medicines));
return medicines;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,6 +1,11 @@
using RegistrationOfPatients.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RegistrationOfPatients.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,28 +14,98 @@ namespace RegistrationOfPatients.Repositories.Implementations;
internal class PatientRepository : IPatientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PatientRepository> _logger;
public PatientRepository(IConnectionString connectionString, ILogger<PatientRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreatePatient(Patient patient)
{
}
public void DeletePatient(int id)
{
}
public IEnumerable<Patient> ReadPatients()
{
return [];
}
public Patient ReadPatientById(int id)
{
return Patient.CreateEntity(0, string.Empty, string.Empty);
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(patient));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Patient (Name, Phone) VALUES (@Name, @Phone)";
connection.Execute(queryInsert, patient);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdatePatient(Patient patient)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(patient));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @" UPDATE Patient SET Name=@Name, Phone=@Phone WHERE Id=@Id"; connection.Execute(queryUpdate, patient);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeletePatient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" DELETE FROM Patient WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Patient> ReadPatients()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Patient";
var patients = connection.Query<Patient>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(patients));
return patients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Patient ReadPatientById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" SELECT * FROM Patient WHERE Id=@id";
var patient = connection.QueryFirst<Patient>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(patient));
return patient;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
}

View File

@ -1,6 +1,11 @@
using RegistrationOfPatients.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RegistrationOfPatients.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,18 +14,63 @@ namespace RegistrationOfPatients.Repositories.Implementations;
public class PaymentRepository : IPaymentRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PaymentRepository> _logger;
public PaymentRepository(IConnectionString connectionString, ILogger<PaymentRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreatePayment(Payment payment)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(payment));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Payment (Salary, TotalPatients, Date, PercentageOfRecoveries, DoctorId) VALUES (@Salary, @TotalPatients, @Date, @PercentageOfRecoveries, @DoctorId)";
connection.Execute(queryInsert, payment);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletePayment(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" DELETE FROM Payment WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Payment> ReadPayment(DateTime? dateForm = null, DateTime? dateTo = null, int? doctorId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Payment";
var payments = connection.Query<Payment>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(payments));
return payments;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,20 +1,78 @@
using RegistrationOfPatients.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RegistrationOfPatients.Entities;
using RegistrationOfPatients.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Transactions;
using Npgsql;
namespace RegistrationOfPatients.Repositories.Implementations;
public class ReceptionRepository : IReceptionRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ReceptionRepository> _logger;
public ReceptionRepository(IConnectionString connectionString, ILogger<ReceptionRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateReception(Reception reception)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(reception));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @" INSERT INTO Reception (Date, HealthStatus, Illness, PatientId, DoctorId) VALUES (@Date, @HealthStatus, @Illness, @PatientId, @DoctorId); SELECT MAX(Id) FROM Reception";
var receptionId = connection.QueryFirst<int>(queryInsert, reception, transaction);
var querySubInsert = @" INSERT INTO ReceptionMedicine (MedicineId, Count) VALUES (@MedicineId, @Count)";
foreach (var elem in reception.ReceptionMedicine)
{
connection.Execute(querySubInsert, new
{
receptionId,
elem.MedicineId,
elem.Count,
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Reception> ReadReceptions(DateTime? dateForm = null, DateTime? dateTo = null, int? doctorId = null, int? patientId = null, int? medicineId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Reception";
var receptions = connection.Query<Reception>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(receptions));
return receptions;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

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