From c1c71548a4e63a19e519874dabacc567a61f510d Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Mon, 25 Nov 2024 10:52:52 +0400 Subject: [PATCH 1/5] log + logic for cleaning and athlete --- .lab2.vpp.lck | 0 ProjectHotel/ProjectHotel/ProjectHotel.csproj | 10 ++++++++++ .../Repositories/IConnectionString.cs | 13 +++++++++++++ .../Implementations/ConnectionString.cs | 12 ++++++++++++ ProjectHotel/ProjectHotel/appsettings.json | 10 ++++++++++ lab2.vpp | Bin 716800 -> 716800 bytes 6 files changed, 45 insertions(+) delete mode 100644 .lab2.vpp.lck create mode 100644 ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs create mode 100644 ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs create mode 100644 ProjectHotel/ProjectHotel/appsettings.json diff --git a/.lab2.vpp.lck b/.lab2.vpp.lck deleted file mode 100644 index e69de29..0000000 diff --git a/ProjectHotel/ProjectHotel/ProjectHotel.csproj b/ProjectHotel/ProjectHotel/ProjectHotel.csproj index 8fef0f9..db19495 100644 --- a/ProjectHotel/ProjectHotel/ProjectHotel.csproj +++ b/ProjectHotel/ProjectHotel/ProjectHotel.csproj @@ -24,7 +24,17 @@ + + + + + + + + + + \ 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..4380187 --- /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; + +internal interface IConnectionString +{ + string ConnectionString { get; } + +} diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..fe8722e --- /dev/null +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectHotel.Repositories.Implementations +{ + internal class ConnectionString + { + } +} diff --git a/ProjectHotel/ProjectHotel/appsettings.json b/ProjectHotel/ProjectHotel/appsettings.json new file mode 100644 index 0000000..afb797c --- /dev/null +++ b/ProjectHotel/ProjectHotel/appsettings.json @@ -0,0 +1,10 @@ +{ + "exclude": [ + "**/bin", + "**/bower_components", + "**/jspm_packages", + "**/node_modules", + "**/obj", + "**/platforms" + ] +} \ No newline at end of file diff --git a/lab2.vpp b/lab2.vpp index 77c6cababd1a0bd98c76a39ce865c052a73c9996..a459240f9689875aca54f07be53f0b48270d2b08 100644 GIT binary patch delta 806 zcmZwFT}V@57y#h&p5N~rw|(=sWlYaTWj3{CUW9jERC*z-MuthCtz)J!hpV@NnMu{eI5(9=`4cPxpdn zurQ~tljFE&Xc)OsSFEhkiq#5#vlY`ke%(}jq*UgUpo4B?`}$MG5C$2?Y8wxk&_~OZ?YD# zgKpmZKuV!_Vsx_ugh@MWQhezk`ee?I+r;qTp-?Och(`hvk%VLx3o2LVg?v7lX_e=b zscheMUOuYJJN|9)fKbk9{1Rt-Ym3-&tqE(jC2gtCn#pS5m;U!KZ!;MNQ78u|OSg~~ z5IK&Nng;{qG)Brhb09#zVkCcIUFS$8kD)lmUS1$IAPWIJJ7?%n%M1DJNE;d4S`9ty z^F`v3Gp#ADc-S)vYwaW>BvYZQsqE23%2o%6Ll>}praULV=yvo5qwQH6IBT7+LRO?}i*(YbD!S^zHIL9! z(;ifJ)s18L7>%JP=q^g4d*~s0fJV`M!*;?c*6dT8*H-`;yP}noKMX135dZ)H delta 3771 zcmeHJYgAO%6~1TY&V9`jc~%IFsGz{Wya5S`gMx`j1py!U;yoj8WX9(*2#gM*25>A# zBO+KeZIk$5jCWO=7L5;BRUifKcT7?Wm2)SkH*aE7G)+aH~^zI*T4cb|Q~ zz0W@1nT@x@H{K3!8b9u}H5i5+LD+>LLs;D$q4q-7$njk~5M8()pr3>0#-o(ppDw(>EgE>G0Xx2XGW2s^udplzV_fm#Hw|XMbZ~IPgVR zfBQg#4EVt6kEp4*cPKyIUbD{+KDbAVfLCYxvvR;YAp_5(=q3kvsvVcDvCC!Nw&n_e zz(e38;0OW)f^DuKt3Klk$=%JxQ%AGv=Mih+Gb1&VM`#>HAbvDK6BR{%gL#8)Omace zAn_FM6HgOe6r~7zh4blal!1Iq93_8`uOkZiTX8*K0lHabHnj`jwc~?G_F@i|1Mnq* zgfCR(QCWD+lmHSo=22hbbt}e`>>K%%nupgCek6OmkTL)Qqfjj{yBs9pbsjz>n`ok% zfTIk=a)iFa2|yY#(&+F=T}raX)zn^!0MdR;+VAjazbj??8!10IpP({W@+kF0$|od4 zEZK#gkk=3<9b!EOsfSW_=ranJwTX0!mo;GUpSZv0%2DOP2f7UP7OQK7#~@sE0;`o zCx?7xY+$em`2AvmtMB{~POy0%coiNgA}5hCDim9;xDU>L- zUaQha2gflqy7Yj;9Y8x{pfBiDFYt4Vkmuw#A=hH6 z$V@4nWvEP8ZAddEO`5x=;zh%3_+%127bYj8!jF&#Iyn6xu5U?UNE{K>!wwT2#*ybf z%#nvj#LR?OUd&}fmD!SCP-ZqNwss?YoNx8#Ia_G5LTroVT1e}f<6PJVm;l)rYfcd= z)zUJWc3;s9xT=hv=vn0&CKc5YR))|%KhZC$;eN?;osl-&FYa+*dok??8_MaWBYEjj z?4QUBxaO7M8h+7mUSq8PEw9p}CUb8E7&V`X zg&#-JKH;McIVM>#QX(9Ciiy-z3I0Cz6p8;ppiPSl6_XWcak1_B(lMVq7DENd-P0fA zh05Utmv_)Jg&I{vv@TAiR!1mdYAjXgPBjq*1Y>mHkbT)NMTz zVV4#7hPqjk+{TH|b;S+}?(kGPcx(le!B^>G?7gMmyO%x5?om90uR^+bx(-D0kQn~S z$ZY4KLf2S9Fe+d&7@-s3em;KpSEEY$Sq#kS5^$3ADFU>NI+_QX7kkM7{*s9I}b+45oJp;Ia%xjFwkp zR76rn#kTh>)^PeqMffGBbn9Z)%^5u`SC~0Pkhof*yqocXw*V6XyX;8T%3SAIUflkE zgkB$`Q>&d+##0)-UZ>ZqqlY!XZQiP34REtshQ%$A&y>zkYV^@6jY{JxZkq;;ip^8= zopocdAWYmNJS&{VoM&cG^N1<dg)+>hD^p z2)Q-u-AX=TKK@Bg{$N$=>nk&IZt-Tff%GfkrY(hG$F1YUZI>JiZ=9LBzNS9$6w`jS zYw47#sG<<;_~HxIo2=AkUul29}ZGY+HoF~_}ofz!Ps^J-K_Ix1WCw{UlE9K-Fe|E}6adEJ%JiM#+;ZyZM ztXBTRmM^mY+;=*$YW1}#9yhm?yz{|I+wqo@XKevDMK`h%CVy*+&0AT0YUjLx>6Op! zcuxH7^0(h5+8*DuXp2n&)k`M|6ApZLChTBi!<W|wt!qgu<|RnCO+!{C`}7ob5!kNYr`fCb83pxk98v8Q -- 2.25.1 From 0b03273946903db6ff7be85563a58427e70dd6d7 Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Mon, 25 Nov 2024 10:54:16 +0400 Subject: [PATCH 2/5] log +logic 2.0 for cleaning and athlete --- ProjectHotel/ProjectHotel/Entities/Athlete.cs | 2 + ProjectHotel/ProjectHotel/Program.cs | 17 +++ ProjectHotel/ProjectHotel/ProjectHotel.csproj | 8 ++ .../Repositories/IConnectionString.cs | 2 +- .../Implementations/AthleteRepository.cs | 107 +++++++++++++++++- .../Implementations/CleaningRoomRepository.cs | 49 +++++++- .../Implementations/ConnectionString.cs | 3 +- .../PlacingAthleteRepository.cs | 13 ++- ProjectHotel/ProjectHotel/appsettings.json | 23 ++-- 9 files changed, 206 insertions(+), 18 deletions(-) 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/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 db19495..3f5e845 100644 --- a/ProjectHotel/ProjectHotel/ProjectHotel.csproj +++ b/ProjectHotel/ProjectHotel/ProjectHotel.csproj @@ -28,6 +28,8 @@ + + @@ -37,4 +39,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs b/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs index 4380187..ef53d98 100644 --- a/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs +++ b/ProjectHotel/ProjectHotel/Repositories/IConnectionString.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace ProjectHotel.Repositories; -internal interface IConnectionString +public interface IConnectionString { string ConnectionString { get; } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs index d5866c8..6a55349 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..4a3cadf 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,57 @@ 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 []; } 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 index fe8722e..b06ca55 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/ConnectionString.cs @@ -6,7 +6,8 @@ using System.Threading.Tasks; namespace ProjectHotel.Repositories.Implementations { - internal class ConnectionString + public class ConnectionString : IConnectionString { + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=OTP"; } } diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs index af90ecd..747eb62 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs @@ -1,4 +1,5 @@ -using ProjectHotel.Entities; +using Microsoft.Extensions.Logging; +using ProjectHotel.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,6 +10,16 @@ namespace ProjectHotel.Repositories.Implementations; internal class PlacingAthleteRepository : IPlacingAthleteRepository { + + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public PlacingAthleteRepository(IConnectionString connectionString, + ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public IEnumerable ReadPlacingAthlete(int? roomId = null, DateTime? placing = null) { return []; diff --git a/ProjectHotel/ProjectHotel/appsettings.json b/ProjectHotel/ProjectHotel/appsettings.json index afb797c..d6a0247 100644 --- a/ProjectHotel/ProjectHotel/appsettings.json +++ b/ProjectHotel/ProjectHotel/appsettings.json @@ -1,10 +1,15 @@ { - "exclude": [ - "**/bin", - "**/bower_components", - "**/jspm_packages", - "**/node_modules", - "**/obj", - "**/platforms" - ] -} \ No newline at end of file + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/hotel_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} -- 2.25.1 From 1a50d8d5c4936f14a819b0ea2a4e8ab0bf14701f Mon Sep 17 00:00:00 2001 From: user Date: Mon, 25 Nov 2024 14:50:53 +0400 Subject: [PATCH 3/5] 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; + } } } -- 2.25.1 From adc93488c9a00f861cb1536925a90b6b0e65ca8a Mon Sep 17 00:00:00 2001 From: pnevmoslon1 Date: Mon, 9 Dec 2024 06:05:57 +0400 Subject: [PATCH 4/5] lab2 done --- .../Entities/AthletePlacingAthlete.cs | 3 ++- ProjectHotel/ProjectHotel/Entities/Hotel.cs | 6 +++--- .../ProjectHotel/Forms/FormHotel.Designer.cs | 4 ++-- ProjectHotel/ProjectHotel/Forms/FormHotel.cs | 8 ++++---- .../Forms/FormPlacingAthlete.Designer.cs | 16 +++++++-------- .../ProjectHotel/Forms/FormPlacingAthlete.cs | 7 +++---- .../Implementations/HotelRepository.cs | 18 +++++++++++++++++ .../PlacingAthleteRepository.cs | 20 +++++++++++-------- 8 files changed, 52 insertions(+), 30 deletions(-) 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/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/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/Repositories/Implementations/HotelRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs index 4ab5205..49408bf 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/HotelRepository.cs @@ -84,8 +84,26 @@ internal class HotelRepository : IHotelRepository } 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("Удаление объекта"); diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs index ca03a95..b660e12 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/PlacingAthleteRepository.cs @@ -6,6 +6,7 @@ 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; @@ -32,20 +33,23 @@ internal class PlacingAthleteRepository : IPlacingAthleteRepository 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 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 (PlacingAthleteId, AthleteId, LengthOfStay) VALUES (@PlacingAthleteId, @AthleteId, @LengthOfStay)"; + var querySubInsert = @" + INSERT INTO AthletePlacingAthlete (AthleteId, PlacingAthleteId, LengthOfStay) + VALUES (@AthleteId, @PlacingAthleteId, @LengthOfStay); + "; foreach (var elem in placingAthlete.AthletePlacingAthletes) { - connection.Execute(querySubInsert, new - { - PlacingAthleteId = placingAthleteId, - elem.AthleteId, - elem.LengthOfStay, - }, transaction); + connection.Execute(querySubInsert, new { elem.AthleteId, placingAthleteId , elem.LengthOfStay }, transaction); } + transaction.Commit(); } catch (Exception ex) -- 2.25.1 From c870a04204c081c7469e9dffbc1dc1cd0211840b Mon Sep 17 00:00:00 2001 From: user Date: Mon, 9 Dec 2024 13:47:36 +0400 Subject: [PATCH 5/5] final --- ProjectHotel/ProjectHotel/Forms/FormAthlete.cs | 2 +- .../ProjectHotel/Forms/FormRoom.Designer.cs | 8 ++++++++ ProjectHotel/ProjectHotel/Forms/FormRoom.cs | 1 + ProjectHotel/ProjectHotel/Forms/FormRoom.resx | 3 +++ .../Implementations/AthleteRepository.cs | 2 +- .../Implementations/RoomRepository.cs | 17 +++++++++++++++++ 6 files changed, 31 insertions(+), 2 deletions(-) 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/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/Repositories/Implementations/AthleteRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs index 6a55349..8da6c5e 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/AthleteRepository.cs @@ -114,7 +114,7 @@ public class AthleteRepository : IAthleteRepository using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryUpdate = @" UPDATE Athletes - SET FirstName = @FirstName, LastName = @LastName, FatherName = @FatherName, @Sport = Sport, @AthleteClass = AthleteClass + SET FirstName = @FirstName, LastName = @LastName, FatherName = @FatherName, Sport = @Sport, AthleteClass = @AthleteClass WHERE Id = @Id; "; connection.Execute(queryUpdate, athlete); diff --git a/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs b/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs index 958200b..8996240 100644 --- a/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs +++ b/ProjectHotel/ProjectHotel/Repositories/Implementations/RoomRepository.cs @@ -83,7 +83,24 @@ namespace ProjectHotel.Repositories.Implementations } 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) { -- 2.25.1