ПИбд-21. Басалов А.Д. Лабораторная 2 #2 #2

Closed
Tonby73 wants to merge 9 commits from LabWork_2 into LabWork_1
24 changed files with 721 additions and 132 deletions

View File

@ -9,18 +9,20 @@ namespace ProjectTourAgency.Enities;
public class Client
{
public int Id { get;private set; }
public int Id { get; private set; }
public string FullName { get; private set; } = string.Empty;
public DateTime BirthDate { get; private set; }
public string PhoneNumber { get; private set; } = string.Empty;
public ClientStatus ClientStatus { get; private set; }
public int Money { get; private set; }
public static Client CreateEntity(int id, string fullName,
DateTime birthDate, string phoneNumber, int money)
DateTime birthDate, string phoneNumber, int money, ClientStatus cs)
{
return new Client
{
Id = id,
ClientStatus = cs,
FullName = fullName,
BirthDate = birthDate,
PhoneNumber = phoneNumber,

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTourAgency.Enities.Enums;
[Flags]
public enum ClientStatus
{
None = 0,
RegularCustomer = 1,
AgressiveCustomer = 2,
FriendlyCustomer = 3,
VIPCustomer = 4
}

View File

@ -9,17 +9,15 @@ namespace ProjectTourAgency.Enities;
public class Route
{
public int Id { get; private set; }
public int TourId { get; private set; }
public string Destination { get; private set; } = string.Empty;
public string Departure { get; private set; } = string.Empty;
public int Duration { get; private set; }
public static Route CreateEntity(int id, int TourId, string destination,
public static Route CreateEntity(int id, string destination,
string departure, int duration)
{
return new Route
{
Id = id,
TourId = TourId,
Destination = destination,
Departure = departure,
Duration = duration

View File

@ -38,77 +38,88 @@
textBoxMoney = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
label1 = new Label();
checkedListBoxClientStatus = new CheckedListBox();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 9);
labelName.Location = new Point(17, 15);
labelName.Margin = new Padding(4, 0, 4, 0);
labelName.Name = "labelName";
labelName.Size = new Size(75, 15);
labelName.Size = new Size(112, 25);
labelName.TabIndex = 0;
labelName.Text = "Полное имя";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 45);
labelDate.Location = new Point(17, 75);
labelDate.Margin = new Padding(4, 0, 4, 0);
labelDate.Name = "labelDate";
labelDate.Size = new Size(90, 15);
labelDate.Size = new Size(137, 25);
labelDate.TabIndex = 1;
labelDate.Text = "Дата рождения";
//
// labelNumber
//
labelNumber.AutoSize = true;
labelNumber.Location = new Point(12, 88);
labelNumber.Location = new Point(17, 147);
labelNumber.Margin = new Padding(4, 0, 4, 0);
labelNumber.Name = "labelNumber";
labelNumber.Size = new Size(101, 15);
labelNumber.Size = new Size(150, 25);
labelNumber.TabIndex = 2;
labelNumber.Text = "Номер телефона";
//
// labelMoney
//
labelMoney.AutoSize = true;
labelMoney.Location = new Point(12, 128);
labelMoney.Location = new Point(17, 213);
labelMoney.Margin = new Padding(4, 0, 4, 0);
labelMoney.Name = "labelMoney";
labelMoney.Size = new Size(46, 15);
labelMoney.Size = new Size(67, 25);
labelMoney.TabIndex = 3;
labelMoney.Text = "Баланс";
//
// textBoxName
//
textBoxName.Location = new Point(131, 9);
textBoxName.Location = new Point(187, 15);
textBoxName.Margin = new Padding(4, 5, 4, 5);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(100, 23);
textBoxName.Size = new Size(231, 31);
textBoxName.TabIndex = 4;
//
// dateTimePickerDate
//
dateTimePickerDate.Location = new Point(131, 45);
dateTimePickerDate.Location = new Point(187, 75);
dateTimePickerDate.Margin = new Padding(4, 5, 4, 5);
dateTimePickerDate.Name = "dateTimePickerDate";
dateTimePickerDate.Size = new Size(200, 23);
dateTimePickerDate.Size = new Size(231, 31);
dateTimePickerDate.TabIndex = 5;
//
// textBoxNumber
//
textBoxNumber.Location = new Point(131, 85);
textBoxNumber.Location = new Point(187, 142);
textBoxNumber.Margin = new Padding(4, 5, 4, 5);
textBoxNumber.Name = "textBoxNumber";
textBoxNumber.Size = new Size(100, 23);
textBoxNumber.Size = new Size(231, 31);
textBoxNumber.TabIndex = 6;
//
// textBoxMoney
//
textBoxMoney.Location = new Point(131, 125);
textBoxMoney.Location = new Point(187, 208);
textBoxMoney.Margin = new Padding(4, 5, 4, 5);
textBoxMoney.Name = "textBoxMoney";
textBoxMoney.Size = new Size(100, 23);
textBoxMoney.Size = new Size(231, 31);
textBoxMoney.TabIndex = 7;
//
// buttonSave
//
buttonSave.Location = new Point(49, 198);
buttonSave.Location = new Point(60, 421);
buttonSave.Margin = new Padding(4, 5, 4, 5);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.Size = new Size(107, 38);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -116,19 +127,40 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(173, 198);
buttonCancel.Location = new Point(371, 421);
buttonCancel.Margin = new Padding(4, 5, 4, 5);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.Size = new Size(107, 38);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(17, 295);
label1.Margin = new Padding(4, 0, 4, 0);
label1.Name = "label1";
label1.Size = new Size(135, 25);
label1.TabIndex = 10;
label1.Text = "Статус КЛиента";
//
// checkedListBoxClientStatus
//
checkedListBoxClientStatus.FormattingEnabled = true;
checkedListBoxClientStatus.Location = new Point(187, 280);
checkedListBoxClientStatus.Name = "checkedListBoxClientStatus";
checkedListBoxClientStatus.Size = new Size(231, 88);
checkedListBoxClientStatus.TabIndex = 11;
//
// FormClient
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(389, 251);
ClientSize = new Size(517, 479);
Controls.Add(checkedListBoxClientStatus);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxMoney);
@ -139,6 +171,7 @@
Controls.Add(labelNumber);
Controls.Add(labelDate);
Controls.Add(labelName);
Margin = new Padding(4, 5, 4, 5);
Name = "FormClient";
Text = "FormClient";
ResumeLayout(false);
@ -157,5 +190,7 @@
private TextBox textBoxMoney;
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private CheckedListBox checkedListBoxClientStatus;
}
}

View File

@ -1,6 +1,7 @@

using ProjectRouteAgency.Repositories;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Enities.Enums;
using ProjectTourAgency.Implementations;
using ProjectTourAgency.Repositories;
using System;
@ -36,6 +37,17 @@ namespace ProjectTourAgency.Forms
textBoxMoney.Text = client.Money.ToString();
dateTimePickerDate.Value = client.BirthDate;
foreach (ClientStatus elem in
Enum.GetValues(typeof(ClientStatus)))
{
if ((elem & client.ClientStatus) != 0)
{
checkedListBoxClientStatus.SetItemChecked(checkedListBoxClientStatus.Items.IndexOf(
elem), true);
}
}
_clientId = value;
}
catch (Exception ex)
{
@ -50,7 +62,10 @@ namespace ProjectTourAgency.Forms
InitializeComponent();
_clientRepository = clientRepository ??
throw new ArgumentNullException(nameof(clientRepository));
foreach (var elem in Enum.GetValues(typeof(ClientStatus)))
{
checkedListBoxClientStatus.Items.Add(elem);
}
}
private void buttonSave_Click(object sender, EventArgs e)
@ -59,7 +74,8 @@ namespace ProjectTourAgency.Forms
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) ||
string.IsNullOrWhiteSpace(textBoxNumber.Text)
|| string.IsNullOrWhiteSpace(textBoxMoney.Text) || string.IsNullOrWhiteSpace(dateTimePickerDate.Text))
|| string.IsNullOrWhiteSpace(textBoxMoney.Text) || string.IsNullOrWhiteSpace(dateTimePickerDate.Text)
|| checkedListBoxClientStatus.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
@ -70,7 +86,7 @@ namespace ProjectTourAgency.Forms
}
else
{
_clientRepository.CreateClient(CreateClient(_clientId.Value));
_clientRepository.CreateClient(CreateClient(0));
}
Close();
}
@ -83,6 +99,15 @@ namespace ProjectTourAgency.Forms
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Client CreateClient(int id) => Client.CreateEntity(id, textBoxName.Text, dateTimePickerDate.Value,textBoxNumber.Text, Convert.ToInt32(textBoxMoney.Text));
private Client CreateClient(int id)
{
ClientStatus clientStatus = ClientStatus.None;
foreach (var elem in checkedListBoxClientStatus.CheckedItems)
{
clientStatus |= (ClientStatus)elem;
}
return Client.CreateEntity(id, textBoxName.Text, dateTimePickerDate.Value, textBoxNumber.Text,
int.Parse(textBoxMoney.Text), clientStatus);
}
}
}

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -52,8 +52,9 @@ namespace ProjectTourAgency.Forms
{
throw new Exception("Есть незаполненные поля");
}
_tourRepository.CreateTour(Tour.CreateEntity(0, comboBoxEmployeeId.SelectedIndex,
comboBoxRouteId.SelectedIndex, dateTimePicker.Value,CreateListClientTourFromDataGrid()));
_tourRepository.CreateTour(Tour.CreateEntity(0, (int)comboBoxEmployeeId.SelectedValue,
(int)comboBoxRouteId.SelectedValue, dateTimePicker.Value,CreateListClientTourFromDataGrid()));
Close();
}
catch (Exception ex)
{

View File

@ -2,6 +2,7 @@
using ProjectEmployeeAgency.Repositories;
using ProjectRouteAgency.Repositories;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Enities.Enums;
using ProjectTourAgency.Implementations;
using ProjectTourAgency.Repositories;
using System;
@ -34,6 +35,7 @@ namespace ProjectTourAgency.Forms
}
textBoxName.Text = employee.FullName;
comboBoxJob.SelectedItem = employee.EmployeeJob;
_employeeId = value;
}
@ -50,6 +52,7 @@ namespace ProjectTourAgency.Forms
InitializeComponent();
_employeeRepository = employeeRepository ??
throw new ArgumentNullException(nameof(employeeRepository));
comboBoxJob.DataSource = Enum.GetValues(typeof(EmpoyeeJob));
}
@ -69,7 +72,7 @@ namespace ProjectTourAgency.Forms
}
else
{
_employeeRepository.CreateEmployee(CreateEmployee(_employeeId.Value));
_employeeRepository.CreateEmployee(CreateEmployee(0));
}
Close();
}

View File

@ -43,7 +43,7 @@ namespace ProjectTourAgency.Forms
{
try
{
_container.Resolve<FormClient>().ShowDialog();
_container.Resolve<FormEmployee>().ShowDialog();
LoadList();
}
catch (Exception ex)

View File

@ -32,76 +32,72 @@
labelDestination = new Label();
labelDeparture = new Label();
textBoxDuration = new TextBox();
labelTourId = new Label();
textBoxDeparture = new TextBox();
labelDuration = new Label();
buttonSave = new Button();
buttonCancel = new Button();
comboBoxTourId = new ComboBox();
SuspendLayout();
//
// textBoxDestination
//
textBoxDestination.Location = new Point(144, 32);
textBoxDestination.Location = new Point(206, 53);
textBoxDestination.Margin = new Padding(4, 5, 4, 5);
textBoxDestination.Name = "textBoxDestination";
textBoxDestination.Size = new Size(226, 23);
textBoxDestination.Size = new Size(321, 31);
textBoxDestination.TabIndex = 4;
//
// labelDestination
//
labelDestination.AutoSize = true;
labelDestination.Location = new Point(38, 32);
labelDestination.Location = new Point(15, 53);
labelDestination.Margin = new Padding(4, 0, 4, 0);
labelDestination.Name = "labelDestination";
labelDestination.Size = new Size(100, 15);
labelDestination.Size = new Size(148, 25);
labelDestination.TabIndex = 3;
labelDestination.Text = "Место прибытия";
//
// labelDeparture
//
labelDeparture.AutoSize = true;
labelDeparture.Location = new Point(38, 78);
labelDeparture.Location = new Point(15, 131);
labelDeparture.Margin = new Padding(4, 0, 4, 0);
labelDeparture.Name = "labelDeparture";
labelDeparture.Size = new Size(91, 15);
labelDeparture.Size = new Size(135, 25);
labelDeparture.TabIndex = 5;
labelDeparture.Text = "Место отбытия";
//
// textBoxDuration
//
textBoxDuration.Location = new Point(144, 114);
textBoxDuration.Location = new Point(206, 190);
textBoxDuration.Margin = new Padding(4, 5, 4, 5);
textBoxDuration.Name = "textBoxDuration";
textBoxDuration.Size = new Size(226, 23);
textBoxDuration.Size = new Size(321, 31);
textBoxDuration.TabIndex = 7;
//
// labelTourId
//
labelTourId.AutoSize = true;
labelTourId.Location = new Point(38, 163);
labelTourId.Name = "labelTourId";
labelTourId.Size = new Size(94, 15);
labelTourId.TabIndex = 6;
labelTourId.Text = "Стоимость тура";
//
// textBoxDeparture
//
textBoxDeparture.Location = new Point(144, 75);
textBoxDeparture.Location = new Point(206, 125);
textBoxDeparture.Margin = new Padding(4, 5, 4, 5);
textBoxDeparture.Name = "textBoxDeparture";
textBoxDeparture.Size = new Size(226, 23);
textBoxDeparture.Size = new Size(321, 31);
textBoxDeparture.TabIndex = 8;
//
// labelDuration
//
labelDuration.AutoSize = true;
labelDuration.Location = new Point(45, 117);
labelDuration.Location = new Point(15, 193);
labelDuration.Margin = new Padding(4, 0, 4, 0);
labelDuration.Name = "labelDuration";
labelDuration.Size = new Size(84, 15);
labelDuration.Size = new Size(179, 25);
labelDuration.TabIndex = 10;
labelDuration.Text = "Дата отбытия";
labelDuration.Text = "Продолжительность";
//
// buttonSave
//
buttonSave.Location = new Point(63, 251);
buttonSave.Location = new Point(87, 285);
buttonSave.Margin = new Padding(4, 5, 4, 5);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.Size = new Size(107, 38);
buttonSave.TabIndex = 12;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -109,40 +105,32 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(256, 251);
buttonCancel.Location = new Point(363, 285);
buttonCancel.Margin = new Padding(4, 5, 4, 5);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.Size = new Size(107, 38);
buttonCancel.TabIndex = 13;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// comboBoxTourId
//
comboBoxTourId.FormattingEnabled = true;
comboBoxTourId.Location = new Point(144, 163);
comboBoxTourId.Name = "comboBoxTourId";
comboBoxTourId.Size = new Size(226, 23);
comboBoxTourId.TabIndex = 14;
//
// FormRoute
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(414, 284);
Controls.Add(comboBoxTourId);
ClientSize = new Size(591, 337);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelDuration);
Controls.Add(textBoxDeparture);
Controls.Add(textBoxDuration);
Controls.Add(labelTourId);
Controls.Add(labelDeparture);
Controls.Add(textBoxDestination);
Controls.Add(labelDestination);
Margin = new Padding(4, 5, 4, 5);
Name = "FormRoute";
StartPosition = FormStartPosition.CenterParent;
Text = "Тур";
Text = "Маршрут";
ResumeLayout(false);
PerformLayout();
}
@ -153,13 +141,11 @@
private Label labelDestination;
private Label labelDeparture;
private TextBox textBoxDuration;
private Label labelTourId;
private TextBox textBoxDeparture;
private Label labelDate;
private Label labelDuration;
private TextBox textBoxPrice;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxTourId;
}
}

View File

@ -34,7 +34,7 @@ namespace ProjectTourAgency.Forms
textBoxDestination.Text = route.Destination;
textBoxDeparture.Text = route.Departure;
textBoxDuration.Text = route.Duration.ToString();
_routeId = value;
}
catch(Exception ex)
{
@ -49,9 +49,6 @@ namespace ProjectTourAgency.Forms
InitializeComponent();
_routeRepository = routeRepository ??
throw new ArgumentNullException(nameof(routeRepository));
comboBoxTourId.DataSource = tourRepository.ReadTours();
comboBoxTourId.DisplayMember = "FullName";
comboBoxTourId.ValueMember = "Id";
}
@ -61,7 +58,7 @@ namespace ProjectTourAgency.Forms
{
if (string.IsNullOrWhiteSpace(textBoxDestination.Text) ||
string.IsNullOrWhiteSpace(textBoxDeparture.Text) || string.IsNullOrWhiteSpace(textBoxDuration.Text)
|| string.IsNullOrWhiteSpace(textBoxPrice.Text) || string.IsNullOrWhiteSpace(dateTimePickerDepartureDate.Text))
)
{
throw new Exception("Имеются незаполненные поля");
}
@ -72,7 +69,7 @@ namespace ProjectTourAgency.Forms
}
else
{
_routeRepository.CreateRoute(CreateRoute(_routeId.Value));
_routeRepository.CreateRoute(CreateRoute(0));
}
Close();
}
@ -85,7 +82,7 @@ namespace ProjectTourAgency.Forms
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Route CreateRoute(int id) => Route.CreateEntity(id, (int)comboBoxTourId.SelectedValue!, textBoxDestination.Text,
private Route CreateRoute(int id) => Route.CreateEntity(id, textBoxDestination.Text,
textBoxDeparture.Text, int.Parse(textBoxDuration.Text));
}
}

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -1,39 +1,146 @@
using ProjectTourAgency.Enities;
using Microsoft.Extensions.Logging;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using Npgsql;
using System.Transactions;
namespace ProjectTourAgency.Implementations
namespace ProjectTourAgency.Implementations;
public class AddMoneyRepository : IAddMoneyRepository
{
internal class AddMoneyRepository : IAddMoneyRepository
private readonly IConnectionString _connectionString;
private readonly ILogger<AddMoneyRepository> _logger;
public AddMoneyRepository(IConnectionString connectionString, ILogger<AddMoneyRepository> logger)
{
public void CreateAddMoney(AddMoney client)
_connectionString = connectionString;
_logger = logger;
}
public void CreateAddMoney(AddMoney AddMoney)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {jspn}", JsonConvert.SerializeObject(AddMoney));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open(); // Открываем соединение
// Начинаем транзакцию
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO AddMoneys (ClientId,Date,MoneyAmount)
VALUES (@ClientId,@Date,@MoneyAmount)";
connection.Execute(queryInsert, AddMoney);
var queryUpdate = @"
UPDATE Clients
SET Money = Money + @MoneyAmount
WHERE Id = @ClientId
";
connection.Execute(queryUpdate, new { MoneyAmount = AddMoney.MoneyAmount, ClientId = AddMoney.ClientId }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAddMoney(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM AddMoneys
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
public void DeleteAddMoney(int id)
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при ужалении объекта");
throw;
}
}
public AddMoney ReadAddMoneyById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM AddMoneys
WHERE Id = @Id";
var AddMoney = connection.QueryFirst<AddMoney>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(AddMoney));
return AddMoney;
}
public AddMoney ReadAddMoneyById(int id)
catch (Exception ex)
{
return AddMoney.CreateEntity(0,0,DateTime.Now,0);
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<AddMoney> ReadAddMoneys()
public IEnumerable<AddMoney> ReadAddMoneys()
{
_logger.LogInformation("Получение всех объектов");
try
{
return [];
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM AddMoneys";
var AddMoneys = connection.Query<AddMoney>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(AddMoneys));
return AddMoneys;
}
public void UpdateAddMoney(AddMoney client)
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateAddMoney(AddMoney AddMoney)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(AddMoney));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE AddMoneys
SET
ClientId = @ClientId,
Date = @Date,
MoneyAmount = @MoneyAmount";
connection.Execute(queryUpdate, AddMoney);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редкатировании объекта");
throw;
}
}
}

View File

@ -1,34 +1,131 @@
using ProjectTourAgency.Enities;
using Microsoft.Extensions.Logging;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Dapper;
using Npgsql;
namespace ProjectTourAgency.Implementations;
public class ClientRepository : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepository> _logger;
public ClientRepository(IConnectionString connectionString, ILogger<ClientRepository> logger )
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {jspn}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Clients (FullName, BirthDate, PhoneNumber, Money, ClientStatus)
VALUES (@FullName, @BirthDate, @PhoneNumber, @Money, @ClientStatus)";
connection.Execute(queryInsert, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteClient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM CLients
WHERE Id = @Id";
connection.Execute(queryDelete, new {id});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при ужалении объекта");
throw;
}
}
public Client ReadClientById(int id)
{
return Client.CreateEntity(0, string.Empty, DateTime.Now, string.Empty, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM CLients
WHERE Id = @Id";
var client = connection.QueryFirst<Client>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Client> ReadClients()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM CLients";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateClient(Client client)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE CLients
SET
FullName = @FullName,
BirthDate = @BirthDate,
PhoneNumber = @PhoneNumber,
Money = @Money,
CLientStatus = @CLientStatus
WHERE Id = @Id";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редкатировании объекта");
throw;
}
}
}

View File

@ -0,0 +1,13 @@
using ProjectTourAgency.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTourAgency.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localHost;Port=5432;Database=otp;Username=postgres;Password=1488;Include Error Detail = True ";
}

View File

@ -1,35 +1,124 @@
using ProjectEmployeeAgency.Repositories;
using Microsoft.Extensions.Logging;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Dapper;
using ProjectEmployeeAgency.Repositories;
using System.Data.SqlClient;
using Npgsql;
namespace ProjectTourAgency.Implementations;
public class EmployeeRepository : IEmployeeRepository
{
public void CreateEmployee(Employee employee)
private readonly IConnectionString _connectionString;
private readonly ILogger<EmployeeRepository> _logger;
public EmployeeRepository(IConnectionString connectionString, ILogger<EmployeeRepository> logger )
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateEmployee(Employee Employee)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {jspn}", JsonConvert.SerializeObject(Employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Employees (FullName, EmployeeJob)
VALUES (@FullName, @EmployeeJob)";
connection.Execute(queryInsert, Employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteEmployee(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Employees
WHERE Id = @Id";
connection.Execute(queryDelete, new {id});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при ужалении объекта");
throw;
}
}
public Employee ReadEmployeeById(int id)
{
return Employee.CreateEntity(0, string.Empty,0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Employees
WHERE Id = @Id";
var Employee = connection.QueryFirst<Employee>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(Employee));
return Employee;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Employee> ReadEmployees()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Employees";
var Employees = connection.Query<Employee>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(Employees));
return Employees;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateEmployee(Employee employee)
public void UpdateEmployee(Employee Employee)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(Employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Employees
SET
FullName = @FullName,
EmployeeJob = @EmployeeJob
WHERE Id = @Id";
connection.Execute(queryUpdate, Employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редкатировании объекта");
throw;
}
}
}

View File

@ -1,37 +1,130 @@
using ProjectRouteAgency.Repositories;
using Microsoft.Extensions.Logging;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using ProjectRouteAgency.Repositories;
using Npgsql;
namespace ProjectTourAgency.Implementations;
public class RouteRepository : IRouteRepository
{
public void CreateRoute(Route route)
private readonly IConnectionString _connectionString;
private readonly ILogger<RouteRepository> _logger;
public RouteRepository(IConnectionString connectionString, ILogger<RouteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateRoute(Route Route)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {jspn}", JsonConvert.SerializeObject(Route));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Routes (Destination, Departure, Duration)
VALUES (@Destination, @Departure, @Duration)";
connection.Execute(queryInsert, Route);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteRoute(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Routes
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при ужалении объекта");
throw;
}
}
public Route ReadRouteById(int id)
{
return Route.CreateEntity(0,0, string.Empty,string.Empty, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Routes
WHERE Id = @Id";
var Route = connection.QueryFirst<Route>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(Route));
return Route;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Route> ReadRoutes()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Routes";
var Routes = connection.Query<Route>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(Routes));
return Routes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateRoute(Route route)
public void UpdateRoute(Route Route)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(Route));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Routes
SET
Destination = @Destination,
Departure = @Departure,
Duration = @Duration
WHERE Id = @Id";
connection.Execute(queryUpdate, Route);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редкатировании объекта");
throw;
}
}
}

View File

@ -1,7 +1,12 @@
using ProjectTourAgency.Enities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,26 +15,83 @@ namespace ProjectTourAgency.Implementations;
public class TourRepository : ITourRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<TourRepository> _logger;
public TourRepository(IConnectionString connectionString, ILogger<TourRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateTour(Tour tour)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(tour));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Tour(EmployeeId, RouteId, DepartureDate)
VALUES (@EmployeeId, @RouteId, @DepartureDate);
SELECT MAX(Id) FROM Tour
";
var tourID = connection.QueryFirst<int>(queryInsert, tour, transaction);
var querySubInsert = @"
INSERT INTO ClientTour(ClientId, TourId, Cost)
VALUES (@ClientId, @TourId, @Cost)";
foreach (var elem in tour.ClientTours)
{
connection.Execute(querySubInsert, new { tourID, elem.ClientId, elem.Cost }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteTour(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объекьт: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Tour
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Tour ReadTourById(int id)
{
return Tour.CreateEntity(0,0, 0,DateTime.Now, []);
}
public IEnumerable<Tour> ReadTours()
{
return [];
}
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Tour";
var tour = connection.Query<Tour>(querySelect);
_logger.LogDebug("Получение объектов {json}", JsonConvert.SerializeObject(tour));
return tour;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении");
throw;
}
public void UpdateTour(Tour tour)
{
}
}

View File

@ -1,8 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectEmployeeAgency.Repositories;
using ProjectRouteAgency.Repositories;
using ProjectTourAgency.Implementations;
using ProjectTourAgency.Repositories;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectTourAgency
{
@ -24,6 +28,8 @@ namespace ProjectTourAgency
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ITourRepository, TourRepository>();
container.RegisterType<IAddMoneyRepository, AddMoneyRepository>();
container.RegisterType<IClientRepository, ClientRepository>();
@ -31,7 +37,21 @@ namespace ProjectTourAgency
container.RegisterType<IEmployeeRepository, EmployeeRepository>();
container.RegisterType<ITourRepository, TourRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

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

View File

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

View File

@ -11,11 +11,9 @@ public interface ITourRepository
{
IEnumerable<Tour> ReadTours();
Tour ReadTourById(int id);
void CreateTour(Tour tour);
void UpdateTour(Tour tour);
void DeleteTour(int id);
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/zoo_log.txt",
"rollingInterval": "Day"
}
}
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB