From 1a50d8d5c4936f14a819b0ea2a4e8ab0bf14701f Mon Sep 17 00:00:00 2001 From: user Date: Mon, 25 Nov 2024 14:50:53 +0400 Subject: [PATCH] without db and logs --- DELETE TABLE athletes.pgsql | 1 + .../Forms/FormAthletes.Designer.cs | 1 + .../ProjectHotel/Forms/FormAthletes.cs | 3 + .../Forms/FormCleaningRooms.Designer.cs | 1 + .../ProjectHotel/Forms/FormCleaningRooms.cs | 2 + .../Forms/FormHotelForAthletes.cs | 2 +- .../ProjectHotel/Forms/FormHotels.Designer.cs | 1 + ProjectHotel/ProjectHotel/Forms/FormHotels.cs | 2 +- .../Forms/FormPlacingAthletes.Designer.cs | 2 + .../ProjectHotel/Forms/FormPlacingAthletes.cs | 68 +++++++-------- .../ProjectHotel/Forms/FormRooms.Designer.cs | 1 + ProjectHotel/ProjectHotel/Forms/FormRooms.cs | 5 +- .../Implementations/CleaningRoomRepository.cs | 17 +++- .../Implementations/ConnectionString.cs | 2 +- .../Implementations/HotelRepository.cs | 83 ++++++++++++++++++- .../PlacingAthleteRepository.cs | 81 ++++++++++++++++-- .../Implementations/RoomRepository.cs | 82 +++++++++++++++++- 17 files changed, 299 insertions(+), 55 deletions(-) create mode 100644 DELETE TABLE athletes.pgsql diff --git a/DELETE TABLE athletes.pgsql b/DELETE TABLE athletes.pgsql new file mode 100644 index 0000000..4ec55eb --- /dev/null +++ b/DELETE TABLE athletes.pgsql @@ -0,0 +1 @@ +DELETE TABLE athletes \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/Forms/FormAthletes.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormAthletes.Designer.cs index 9257812..7db3298 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormAthletes.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormAthletes.Designer.cs @@ -109,6 +109,7 @@ Name = "FormAthletes"; StartPosition = FormStartPosition.CenterParent; Text = "FormAthletes"; + Load += FormAthletes_Load; panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit(); ResumeLayout(false); diff --git a/ProjectHotel/ProjectHotel/Forms/FormAthletes.cs b/ProjectHotel/ProjectHotel/Forms/FormAthletes.cs index 0a15bd6..105081a 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormAthletes.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormAthletes.cs @@ -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; } + + } diff --git a/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.Designer.cs index 17b6da6..fd8d7cd 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.Designer.cs @@ -83,6 +83,7 @@ Name = "FormCleaningRooms"; StartPosition = FormStartPosition.CenterParent; Text = "FormCleaningRooms"; + Load += FormCleaningRooms_Load; ((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit(); panel1.ResumeLayout(false); ResumeLayout(false); diff --git a/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.cs b/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.cs index 4ccfd97..871b940 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormCleaningRooms.cs @@ -49,6 +49,8 @@ public partial class FormCleaningRooms : Form } } private void LoadList() => dataGridViewData.DataSource = _cleaningRoomRepository.ReadCleaningRooms(); + + } diff --git a/ProjectHotel/ProjectHotel/Forms/FormHotelForAthletes.cs b/ProjectHotel/ProjectHotel/Forms/FormHotelForAthletes.cs index 8c05fc4..0e3a985 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormHotelForAthletes.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormHotelForAthletes.cs @@ -72,7 +72,7 @@ public partial class FormHotelForAthletes : Form { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { diff --git a/ProjectHotel/ProjectHotel/Forms/FormHotels.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormHotels.Designer.cs index d8f13ae..2e524b5 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormHotels.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormHotels.Designer.cs @@ -109,6 +109,7 @@ Name = "FormHotels"; StartPosition = FormStartPosition.CenterParent; Text = "Гостиницы"; + Load += FormHotels_Load; panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit(); ResumeLayout(false); diff --git a/ProjectHotel/ProjectHotel/Forms/FormHotels.cs b/ProjectHotel/ProjectHotel/Forms/FormHotels.cs index 099b259..cb643d6 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormHotels.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormHotels.cs @@ -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 { diff --git a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.Designer.cs index fe7af57..a1dbaec 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.Designer.cs @@ -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); diff --git a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.cs b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.cs index 1ca386d..3f4e6d0 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthletes.cs @@ -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; + } + +} diff --git a/ProjectHotel/ProjectHotel/Forms/FormRooms.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormRooms.Designer.cs index 9c070fb..d6f44a1 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormRooms.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormRooms.Designer.cs @@ -109,6 +109,7 @@ Name = "FormRooms"; StartPosition = FormStartPosition.CenterParent; Text = "FormRooms"; + Load += FormRooms_Load; ((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit(); panel1.ResumeLayout(false); ResumeLayout(false); diff --git a/ProjectHotel/ProjectHotel/Forms/FormRooms.cs b/ProjectHotel/ProjectHotel/Forms/FormRooms.cs index 929bcc4..115e178 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormRooms.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormRooms.cs @@ -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; } - + } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs index 4a3cadf..89b31b1 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs @@ -23,7 +23,22 @@ internal class CleaningRoomRepository : ICleaningRoomRepository } public IEnumerable 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(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(cleaningRoom)); + return cleaningRoom; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении всех объектов"); + throw; + } } public void CreateCleaningRoom(CleaningRoom cleaningRoom) { diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs index b06ca55..2deb046 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs @@ -8,6 +8,6 @@ namespace ProjectHotel.Repositories.Implementations { public class ConnectionString : IConnectionString { - string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=OTP"; + string IConnectionString.ConnectionString => "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=otp"; } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs index 3b952f6..4ab5205 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs @@ -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,17 +13,74 @@ namespace ProjectHotel.Repositories.Implementations; internal class HotelRepository : IHotelRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + public HotelRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public IEnumerable ReadHotels() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var querySelect = @"SELECT * FROM Hotels"; + var hotel = connection.Query(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(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) { @@ -27,6 +88,22 @@ internal class HotelRepository : IHotelRepository } 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; + } } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs index 747eb62..ca03a95 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs @@ -1,7 +1,11 @@ -using Microsoft.Extensions.Logging; +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.Linq; using System.Text; using System.Threading.Tasks; @@ -10,26 +14,85 @@ namespace ProjectHotel.Repositories.Implementations; internal class PlacingAthleteRepository : IPlacingAthleteRepository { - private readonly IConnectionString _connectionString; private readonly ILogger _logger; - public PlacingAthleteRepository(IConnectionString connectionString, - ILogger logger) + + public PlacingAthleteRepository(IConnectionString connectionString, ILogger logger) { _connectionString = connectionString; _logger = logger; } - public IEnumerable ReadPlacingAthlete(int? roomId = null, DateTime? placing = null) - { - return []; - } 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) RETURNING Id"; + + var placingAthleteId = connection.QueryFirst(queryInsert, placingAthlete, transaction); + var querySubInsert = @"INSERT INTO AthletePlacingAthlete (PlacingAthleteId, AthleteId, LengthOfStay) VALUES (@PlacingAthleteId, @AthleteId, @LengthOfStay)"; + + foreach (var elem in placingAthlete.AthletePlacingAthletes) + { + connection.Execute(querySubInsert, new + { + PlacingAthleteId = placingAthleteId, + elem.AthleteId, + 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 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(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(placingAthletes)); + return placingAthletes; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs index 0aed54d..958200b 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs @@ -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,17 +13,73 @@ namespace ProjectHotel.Repositories.Implementations { internal class RoomRepository : IRoomRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + public RoomRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public IEnumerable ReadRooms() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var querySelect = @"SELECT * FROM Rooms"; + var rooms = connection.Query(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(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) { @@ -27,7 +87,23 @@ namespace ProjectHotel.Repositories.Implementations } 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; + } } }