without db and logs

This commit is contained in:
user 2024-11-25 14:50:53 +04:00
parent 0b03273946
commit 1a50d8d5c4
17 changed files with 299 additions and 55 deletions

View File

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

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

@ -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

@ -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

@ -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

@ -23,7 +23,22 @@ internal class CleaningRoomRepository : ICleaningRoomRepository
}
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)
{

View File

@ -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";
}
}

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,17 +13,74 @@ 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)
{
@ -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;
}
}
}

View File

@ -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<PlacingAthleteRepository> _logger;
public PlacingAthleteRepository(IConnectionString connectionString,
ILogger<PlacingAthleteRepository> logger)
public PlacingAthleteRepository(IConnectionString connectionString, ILogger<PlacingAthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<PlacingAthlete> 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<int>(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<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,17 +13,73 @@ 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)
{
@ -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;
}
}
}