diff --git a/.lab2.vpp.lck b/.lab2.vpp.lck deleted file mode 100644 index e69de29..0000000 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/Entities/Athlete.cs b/ProjectHotel/ProjectHotel/Entities/Athlete.cs index 24f0f5d..3347259 100644 --- a/ProjectHotel/ProjectHotel/Entities/Athlete.cs +++ b/ProjectHotel/ProjectHotel/Entities/Athlete.cs @@ -24,6 +24,8 @@ public class Athlete FirstName = first ?? string.Empty, LastName = last ?? string.Empty, FatherName = father ?? string.Empty, + Sport = sport, + AthleteClass = athleteClass }; } diff --git a/ProjectHotel/ProjectHotel/Entities/AthletePlacingAthlete.cs b/ProjectHotel/ProjectHotel/Entities/AthletePlacingAthlete.cs index c715d0f..58d04d8 100644 --- a/ProjectHotel/ProjectHotel/Entities/AthletePlacingAthlete.cs +++ b/ProjectHotel/ProjectHotel/Entities/AthletePlacingAthlete.cs @@ -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 }; } diff --git a/ProjectHotel/ProjectHotel/Entities/Hotel.cs b/ProjectHotel/ProjectHotel/Entities/Hotel.cs index 5425230..573c8ea 100644 --- a/ProjectHotel/ProjectHotel/Entities/Hotel.cs +++ b/ProjectHotel/ProjectHotel/Entities/Hotel.cs @@ -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 }; diff --git a/ProjectHotel/ProjectHotel/Forms/FormAthlete.cs b/ProjectHotel/ProjectHotel/Forms/FormAthlete.cs index 8ed43b9..c17ea06 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormAthlete.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormAthlete.cs @@ -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; 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/FormHotel.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormHotel.Designer.cs index 8fbb75a..a9203b7 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormHotel.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormHotel.Designer.cs @@ -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; + } } \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/Forms/FormHotel.cs b/ProjectHotel/ProjectHotel/Forms/FormHotel.cs index eb664df..c47406e 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormHotel.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormHotel.cs @@ -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); - + } 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/FormPlacingAthlete.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.Designer.cs index 8be2f83..c4de78b 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.Designer.cs @@ -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); diff --git a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.cs b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.cs index 8c7ef6a..c27d32b 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormPlacingAthlete.cs @@ -50,14 +50,13 @@ public partial class FormPlacingAthlete : Form } } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - private List - CreateListAthletePlacingAthleteFromDataGrid() + private List CreateListAthletePlacingAthleteFromDataGrid() { var list = new List(); 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; } 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/FormRoom.Designer.cs b/ProjectHotel/ProjectHotel/Forms/FormRoom.Designer.cs index 6972411..09a9f94 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormRoom.Designer.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormRoom.Designer.cs @@ -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; } } \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/Forms/FormRoom.cs b/ProjectHotel/ProjectHotel/Forms/FormRoom.cs index 8b866aa..33fc4e9 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormRoom.cs +++ b/ProjectHotel/ProjectHotel/Forms/FormRoom.cs @@ -30,6 +30,7 @@ namespace ProjectHotel.Forms } textBoxRoomName.Text = room.Name; numericUpDownCapacity.Value = room.Capacity; + comboBoxHotel.SelectedValue = room.HotelId; _roomId = value; } catch (Exception ex) diff --git a/ProjectHotel/ProjectHotel/Forms/FormRoom.resx b/ProjectHotel/ProjectHotel/Forms/FormRoom.resx index b922c5b..4967353 100644 --- a/ProjectHotel/ProjectHotel/Forms/FormRoom.resx +++ b/ProjectHotel/ProjectHotel/Forms/FormRoom.resx @@ -141,6 +141,9 @@ True + + 175, 17 + 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/Program.cs b/ProjectHotel/ProjectHotel/Program.cs index 6834d59..6399c78 100644 --- a/ProjectHotel/ProjectHotel/Program.cs +++ b/ProjectHotel/ProjectHotel/Program.cs @@ -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 (new SingletonLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(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; + } } } \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/ProjectHotel.csproj b/ProjectHotel/ProjectHotel/ProjectHotel.csproj index 8fef0f9..3f5e845 100644 --- a/ProjectHotel/ProjectHotel/ProjectHotel.csproj +++ b/ProjectHotel/ProjectHotel/ProjectHotel.csproj @@ -24,7 +24,25 @@ + + + + + + + + + + + + + + + + + Always + \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs b/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs new file mode 100644 index 0000000..ef53d98 --- /dev/null +++ b/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs @@ -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; } + +} diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs index d5866c8..8da6c5e 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs @@ -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 _logger; + + public AthleteRepository(IConnectionString connectionString, ILogger 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(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(athlete)); + return athlete; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadAthletes() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var querySelect = @"SELECT * FROM Athletes"; + var athletes = connection.Query(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; + } } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs index 71713ea..89b31b1 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/CleaningRoomRepository.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,16 +13,72 @@ namespace ProjectHotel.Repositories.Implementations; internal class CleaningRoomRepository : ICleaningRoomRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public CleaningRoomRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } 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) { + _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(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(cleaningRoom)); + return cleaningRoom; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..2deb046 --- /dev/null +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs @@ -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"; + } +} diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs index 3b952f6..49408bf 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,24 +13,115 @@ 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) { + _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; + } } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs index af90ecd..b660e12 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs @@ -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 ReadPlacingAthlete(int? roomId = null, DateTime? placing = null) + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public PlacingAthleteRepository(IConnectionString connectionString, ILogger 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(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 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..8996240 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,25 +13,114 @@ 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) { + _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; + } } } diff --git a/ProjectHotel/ProjectHotel/appsettings.json b/ProjectHotel/ProjectHotel/appsettings.json new file mode 100644 index 0000000..d6a0247 --- /dev/null +++ b/ProjectHotel/ProjectHotel/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/hotel_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} diff --git a/lab2.vpp b/lab2.vpp index 77c6cab..a459240 100644 Binary files a/lab2.vpp and b/lab2.vpp differ