ПИбд-23 Валиуллин Р.А. 2 лабораторная #2 #2

Closed
rinat wants to merge 5 commits from lab2 into lab1
35 changed files with 606 additions and 78 deletions

View File

View File

@ -0,0 +1 @@
DELETE TABLE athletes

View File

@ -24,6 +24,8 @@ public class Athlete
FirstName = first ?? string.Empty,
LastName = last ?? string.Empty,
FatherName = father ?? string.Empty,
Sport = sport,
AthleteClass = athleteClass
};
}

View File

@ -10,6 +10,7 @@ public class AthletePlacingAthlete
{
public int Id { get; set; }
public int AthleteId { get; private set; }
public int PlacingAthleteId{ get; private set; }
public int LengthOfStay { get; private set; }
public static AthletePlacingAthlete CreateElement(int id, int athleteId, int lengthOfStay)
{
@ -17,7 +18,7 @@ public class AthletePlacingAthlete
{
Id = id,
AthleteId = athleteId,
LengthOfStay = lengthOfStay
LengthOfStay = lengthOfStay
};
}

View File

@ -10,16 +10,16 @@ public class Hotel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Adress { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public static Hotel CreateEntity(int id, string name, string adress)
public static Hotel CreateEntity(int id, string name, string address)
{
return new Hotel
{
Id = id,
Name = name,
Adress = adress
Address = address
};

View File

@ -38,7 +38,7 @@ public partial class FormAthlete : Form
checkedListBoxSport.SetItemChecked(checkedListBoxSport.Items.IndexOf(elem), true);
}
}
_athleteId = value;
textBoxFirstName.Text = athlete.FirstName;
textBoxLastName.Text = athlete.LastName;
textBoxFatherName.Text = athlete.FatherName;

View File

@ -109,6 +109,7 @@
Name = "FormAthletes";
StartPosition = FormStartPosition.CenterParent;
Text = "FormAthletes";
Load += FormAthletes_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);

View File

@ -19,6 +19,7 @@ public partial class FormAthletes : Form
private readonly IAthleteRepository _athleteRepository;
public FormAthletes(IUnityContainer container, IAthleteRepository athleteRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_athleteRepository = athleteRepository ?? throw new ArgumentNullException(nameof(athleteRepository));
@ -101,4 +102,6 @@ public partial class FormAthletes : Form
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

@ -83,6 +83,7 @@
Name = "FormCleaningRooms";
StartPosition = FormStartPosition.CenterParent;
Text = "FormCleaningRooms";
Load += FormCleaningRooms_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);

View File

@ -49,6 +49,8 @@ public partial class FormCleaningRooms : Form
}
}
private void LoadList() => dataGridViewData.DataSource = _cleaningRoomRepository.ReadCleaningRooms();
}

View File

@ -111,9 +111,9 @@
private Label label1;
private Label label2;
private TextBox textBoxHotelName;
private TextBox textBoxHotelAdress;
private TextBox textBoxHotelAddress;
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxHotelAddress;
}
}

View File

@ -31,8 +31,8 @@ public partial class FormHotel : Form
InvalidDataException(nameof(hotel));
}
textBoxHotelName.Text = hotel.Name;
textBoxHotelAdress.Text =
hotel.Adress;
textBoxHotelAddress.Text =
hotel.Address;
_hotelId = value;
}
@ -77,8 +77,8 @@ public partial class FormHotel : Form
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Hotel CreateHotel(int id) => Hotel.CreateEntity(id, textBoxHotelName.Text, textBoxHotelAdress.Text);
private Hotel CreateHotel(int id) => Hotel.CreateEntity(id, textBoxHotelName.Text, textBoxHotelAddress.Text);
}

View File

@ -72,7 +72,7 @@ public partial class FormHotelForAthletes : Form
{
try
{
_container.Resolve<FormCleaningRoom>().ShowDialog();
_container.Resolve<FormCleaningRooms>().ShowDialog();
}
catch (Exception ex)
{

View File

@ -109,6 +109,7 @@
Name = "FormHotels";
StartPosition = FormStartPosition.CenterParent;
Text = "Гостиницы";
Load += FormHotels_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);

View File

@ -26,7 +26,7 @@ public partial class FormHotels : Form
_hotelRepository = hotelRepository ??
throw new ArgumentNullException(nameof(hotelRepository));
}
private void FormRoom_Load(object sender, EventArgs e)
private void FormHotels_Load(object sender, EventArgs e)
{
try
{

View File

@ -36,8 +36,8 @@
comboBoxRoom = new ComboBox();
groupBox1 = new GroupBox();
dataGridView = new DataGridView();
ColumnAthlete = new DataGridViewComboBoxColumn();
ColumnLengthOfStay = new DataGridViewTextBoxColumn();
ColumnAthlete = new DataGridViewComboBoxColumn();
groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
@ -119,18 +119,18 @@
dataGridView.Size = new Size(485, 307);
dataGridView.TabIndex = 0;
//
// ColumnLengthOfStay
//
ColumnLengthOfStay.HeaderText = "Длительность проживания";
ColumnLengthOfStay.Name = "ColumnLengthOfStay";
//
// ColumnAthlete
//
ColumnAthlete.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
ColumnAthlete.HeaderText = "Спортсмен";
ColumnAthlete.Name = "ColumnAthlete";
//
// ColumnLengthOfStay
//
ColumnLengthOfStay.HeaderText = "Длительность проживания";
ColumnLengthOfStay.Name = "ColumnLengthOfStay";
//
// FormAthletePlacingAthlete
// FormPlacingAthlete
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
@ -141,7 +141,7 @@
Controls.Add(buttonSave);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormAthletePlacingAthlete";
Name = "FormPlacingAthlete";
StartPosition = FormStartPosition.CenterParent;
Text = "Размещение спортсмена";
groupBox1.ResumeLayout(false);

View File

@ -50,14 +50,13 @@ public partial class FormPlacingAthlete : Form
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<AthletePlacingAthlete>
CreateListAthletePlacingAthleteFromDataGrid()
private List<AthletePlacingAthlete> CreateListAthletePlacingAthleteFromDataGrid()
{
var list = new List<AthletePlacingAthlete>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["ColumnFeed"].Value == null ||
row.Cells["ColumnCount"].Value == null)
if (row.Cells["ColumnAthlete"].Value == null ||
row.Cells["ColumnLengthOfStay"].Value == null)
{
continue;
}

View File

@ -94,7 +94,9 @@
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormPlacingAthletes";
StartPosition = FormStartPosition.CenterParent;
Text = "FormPlacingAthletes";
Load += FormPlacingAthletes_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);

View File

@ -24,7 +24,7 @@ public partial class FormPlacingAthletes : Form
_placingAthleteRepository = placingAthleteRepository ??
throw new ArgumentNullException(nameof(placingAthleteRepository));
}
private void FormPlacingAthletes_Load1(object sender, EventArgs e)
private void FormPlacingAthletes_Load(object sender, EventArgs e)
{
try
{
@ -48,42 +48,42 @@ public partial class FormPlacingAthletes : Form
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_placingAthleteRepository.DeletePlacingAthlete(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadList();
}
private void LoadList() => dataGridViewData.DataSource =
_placingAthleteRepository.ReadPlacingAthlete();
private bool TryGetIdentifierFromSelectedRow(out int id)
catch (Exception ex)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id =
Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource =
_placingAthleteRepository.ReadPlacingAthlete();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

@ -38,8 +38,10 @@
buttonCancel = new Button();
buttonSave = new Button();
comboBoxHotel = new ComboBox();
hotelBindingSource1 = new BindingSource(components);
((System.ComponentModel.ISupportInitialize)hotelBindingSource).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).BeginInit();
((System.ComponentModel.ISupportInitialize)hotelBindingSource1).BeginInit();
SuspendLayout();
//
// labelHotelName
@ -114,6 +116,10 @@
comboBoxHotel.Size = new Size(197, 23);
comboBoxHotel.TabIndex = 9;
//
// hotelBindingSource1
//
hotelBindingSource1.DataSource = typeof(Entities.Hotel);
//
// FormRoom
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -132,6 +138,7 @@
Text = "Комната";
((System.ComponentModel.ISupportInitialize)hotelBindingSource).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).EndInit();
((System.ComponentModel.ISupportInitialize)hotelBindingSource1).EndInit();
ResumeLayout(false);
PerformLayout();
}
@ -146,5 +153,6 @@
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxHotel;
private BindingSource hotelBindingSource1;
}
}

View File

@ -30,6 +30,7 @@ namespace ProjectHotel.Forms
}
textBoxRoomName.Text = room.Name;
numericUpDownCapacity.Value = room.Capacity;
comboBoxHotel.SelectedValue = room.HotelId;
_roomId = value;
}
catch (Exception ex)

View File

@ -141,6 +141,9 @@
<metadata name="buttonSave.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="hotelBindingSource1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>175, 17</value>
</metadata>
<metadata name="$this.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>

View File

@ -109,6 +109,7 @@
Name = "FormRooms";
StartPosition = FormStartPosition.CenterParent;
Text = "FormRooms";
Load += FormRooms_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);

View File

@ -26,7 +26,8 @@ public partial class FormRooms : Form
_roomRepository = roomRepository ??
throw new ArgumentNullException(nameof(roomRepository));
}
private void FormRoom_Load(object sender, EventArgs e)
private void FormRooms_Load(object sender, EventArgs e)
{
try
{
@ -105,7 +106,7 @@ public partial class FormRooms : Form
return true;
}
}

View File

@ -2,6 +2,10 @@ using Unity.Lifetime;
using Unity;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity.Microsoft.Logging;
namespace ProjectHotel
{
@ -22,6 +26,8 @@ namespace ProjectHotel
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType <IConnectionString, ConnectionString> (new SingletonLifetimeManager());
container.RegisterType<IAthleteRepository, AthleteRepository>(new TransientLifetimeManager());
container.RegisterType<ICleaningRoomRepository, CleaningRoomRepository>(new TransientLifetimeManager());
container.RegisterType<IHotelRepository, HotelRepository>(new TransientLifetimeManager());
@ -30,5 +36,16 @@ namespace ProjectHotel
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

@ -24,7 +24,25 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

@ -1,29 +1,128 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ProjectHotel.Repositories.Implementations;
internal class AthleteRepository : IAthleteRepository
public class AthleteRepository : IAthleteRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AthleteRepository> _logger;
public AthleteRepository(IConnectionString connectionString, ILogger<AthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAthlete(Athlete athlete)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Athletes (FirstName, LastName, FatherName, Sport, AthleteClass)
VALUES (@FirstName, @LastName, @FatherName, @Sport, @AthleteClass)";
connection.Execute(queryInsert, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAthlete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Athletes
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Athlete ReadAthleteById(int id)
{
return Athlete.CreateEntity(0, string.Empty, string.Empty,string.Empty, Entities.Enums.Sport.None, Entities.Enums.AthleteClass.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Athletes WHERE Id = @Id;
";
var athlete = connection.QueryFirst<Athlete>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(athlete));
return athlete;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Athlete> ReadAthletes()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Athletes";
var athletes = connection.Query<Athlete>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(athletes));
return athletes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public void UpdateAthlete(Athlete athlete)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Athletes
SET FirstName = @FirstName, LastName = @LastName, FatherName = @FatherName, Sport = @Sport, AthleteClass = @AthleteClass
WHERE Id = @Id;
";
connection.Execute(queryUpdate, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,16 +13,72 @@ namespace ProjectHotel.Repositories.Implementations;
internal class CleaningRoomRepository : ICleaningRoomRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CleaningRoomRepository> _logger;
public CleaningRoomRepository(IConnectionString connectionString, ILogger<CleaningRoomRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<CleaningRoom> ReadCleaningRooms(int? id = null, int? roomId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM CleaningRoom";
var cleaningRoom = connection.Query<CleaningRoom>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(cleaningRoom));
return cleaningRoom;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public void CreateCleaningRoom(CleaningRoom cleaningRoom)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO CleaningRoom (RoomId, CleaningDate)
VALUES (@RoomId, @CleaningDate);
";
connection.Execute(queryInsert, cleaningRoom);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public CleaningRoom ReadCleaningRoomById(int id)
{
return CleaningRoom.CreateOperation(0, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM CleaningRoom WHERE Id = @Id;
";
var cleaningRoom = connection.QueryFirst<CleaningRoom>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
return cleaningRoom;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
}

View File

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

View File

@ -1,4 +1,8 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,24 +13,115 @@ namespace ProjectHotel.Repositories.Implementations;
internal class HotelRepository : IHotelRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<HotelRepository> _logger;
public HotelRepository(IConnectionString connectionString, ILogger<HotelRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Hotel> ReadHotels()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Hotels";
var hotel = connection.Query<Hotel>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(hotel));
return hotel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public Hotel ReadHotelById(int id)
{
return Hotel.CreateEntity(0, string.Empty, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Hotels WHERE Id = @Id;
";
var hotel = connection.QueryFirst<Hotel>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(hotel));
return hotel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateHotel(Hotel hotel)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(hotel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Hotels (Name, Address)
VALUES (@Name, @Address)";
connection.Execute(queryInsert, hotel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateHotel(Hotel hotel)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(hotel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Hotels
SET Name = @Name, Address = @Address
WHERE Id = @Id;
";
connection.Execute(queryUpdate, hotel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteHotel(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Hotels
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -1,6 +1,12 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,16 +15,88 @@ namespace ProjectHotel.Repositories.Implementations;
internal class PlacingAthleteRepository : IPlacingAthleteRepository
{
public IEnumerable<PlacingAthlete> ReadPlacingAthlete(int? roomId = null, DateTime? placing = null)
private readonly IConnectionString _connectionString;
private readonly ILogger<PlacingAthleteRepository> _logger;
public PlacingAthleteRepository(IConnectionString connectionString, ILogger<PlacingAthleteRepository> logger)
{
return [];
_connectionString = connectionString;
_logger = logger;
}
public void CreatePlacingAthlete(PlacingAthlete placingAthlete)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(placingAthlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO PlacingAthlete (RoomId, PlacingDate)
VALUES (@RoomId, @PlacingDate);
SELECT MAX(Id) FROM PlacingAthlete;
";
var placingAthleteId = connection.QueryFirst<int>(queryInsert, placingAthlete, transaction);
var querySubInsert = @"
INSERT INTO AthletePlacingAthlete (AthleteId, PlacingAthleteId, LengthOfStay)
VALUES (@AthleteId, @PlacingAthleteId, @LengthOfStay);
";
foreach (var elem in placingAthlete.AthletePlacingAthletes)
{
connection.Execute(querySubInsert, new { elem.AthleteId, placingAthleteId , elem.LengthOfStay }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletePlacingAthlete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM PlacingAthlete
WHERE Id = @id
";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<PlacingAthlete> ReadPlacingAthlete(int? roomId = null, DateTime? placing = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM PlacingAthlete";
var placingAthletes = connection.Query<PlacingAthlete>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(placingAthletes));
return placingAthletes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,25 +13,114 @@ namespace ProjectHotel.Repositories.Implementations
{
internal class RoomRepository : IRoomRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<RoomRepository> _logger;
public RoomRepository(IConnectionString connectionString, ILogger<RoomRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Room> ReadRooms()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Rooms";
var rooms = connection.Query<Room>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(rooms));
return rooms;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public Room ReadRoomById(int id)
{
return Room.CreateEntity(0, 0, string.Empty, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Rooms WHERE Id = @Id;
";
var room = connection.QueryFirst<Room>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(room));
return room;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateRoom(Room rooms)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(rooms));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Rooms (HotelId, Name,Capacity)
VALUES (@HotelId, @Name, @Capacity)";
connection.Execute(queryInsert, rooms);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateRoom(Room rooms)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(rooms));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Rooms
SET HotelId = @HotelId, Name = @Name, Capacity = @Capacity
WHERE Id = @Id;
";
connection.Execute(queryUpdate, rooms);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteRoom(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Rooms
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
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/hotel_log.txt",
"rollingInterval": "Day"
}
}
]
}
}

BIN
lab2.vpp

Binary file not shown.