5 Commits

Author SHA1 Message Date
9847c6fd9a Lab2 2024-12-23 22:31:20 +04:00
38b550bb97 Lab2 2024-12-17 22:55:09 +04:00
3d7f0ac061 Lab2 2024-12-17 22:50:36 +04:00
ff4579d373 Lab2 2024-12-17 01:26:58 +04:00
962bd7cf42 Lab2 2024-12-17 01:18:26 +04:00
24 changed files with 628 additions and 101 deletions

View File

@@ -12,7 +12,7 @@ public class Contract
public int Id { get; private set; }
public DateTime Date { get; private set; }
public decimal ProjectId { get; private set; }
public IEnumerable<CustomerOnProject> CustomerId
public IEnumerable<CustomerOnProject> CustomerOnContract
{
get;
private set;
@@ -25,7 +25,7 @@ public class Contract
Id = id,
Date = date,
ProjectId = projectid,
CustomerId = customerOnContract
CustomerOnContract = customerOnContract
};
}
}

View File

@@ -10,17 +10,17 @@ namespace ProjectItCompany.Entities;
public class CustomerOnProject
{
public int Id { get; private set; }
public decimal ContractId { get; private set; }
public decimal CustomerId { get; private set; }
public int ContractId { get; private set; }
public int CustomerId { get; private set; }
public string Description { get; private set; } = string.Empty;
public static CustomerOnProject CreateElement(int id, decimal contractId, decimal customerid, string description)
public static CustomerOnProject CreateElement(int id, int contractId, int customerid, string descriptio)
{
return new CustomerOnProject
{
Id = id,
ContractId = contractId,
CustomerId = customerid,
Description = description
Description = descriptio
};
}
}

View File

@@ -32,15 +32,17 @@
ButtonCancel = new Button();
groupBoxContract = new GroupBox();
dataGridViewContract = new DataGridView();
ColumnProject = new DataGridViewComboBoxColumn();
labelProject = new Label();
comboBoxProject = new ComboBox();
ColumnCustomer = new DataGridViewComboBoxColumn();
ColumnDescription = new DataGridViewTextBoxColumn();
groupBoxContract.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewContract).BeginInit();
SuspendLayout();
//
// ButtonSave
//
ButtonSave.Location = new Point(68, 254);
ButtonSave.Location = new Point(68, 294);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(75, 23);
ButtonSave.TabIndex = 11;
@@ -50,7 +52,7 @@
//
// ButtonCancel
//
ButtonCancel.Location = new Point(245, 255);
ButtonCancel.Location = new Point(245, 293);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(75, 23);
ButtonCancel.TabIndex = 12;
@@ -61,7 +63,7 @@
// groupBoxContract
//
groupBoxContract.Controls.Add(dataGridViewContract);
groupBoxContract.Location = new Point(12, 12);
groupBoxContract.Location = new Point(12, 43);
groupBoxContract.Name = "groupBoxContract";
groupBoxContract.Size = new Size(375, 237);
groupBoxContract.TabIndex = 13;
@@ -74,7 +76,7 @@
dataGridViewContract.AllowUserToResizeRows = false;
dataGridViewContract.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewContract.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewContract.Columns.AddRange(new DataGridViewColumn[] { ColumnProject, ColumnCustomer });
dataGridViewContract.Columns.AddRange(new DataGridViewColumn[] { ColumnCustomer, ColumnDescription });
dataGridViewContract.Dock = DockStyle.Right;
dataGridViewContract.Location = new Point(3, 19);
dataGridViewContract.MultiSelect = false;
@@ -85,21 +87,42 @@
dataGridViewContract.Size = new Size(369, 215);
dataGridViewContract.TabIndex = 0;
//
// ColumnProject
// labelProject
//
ColumnProject.HeaderText = "Проект";
ColumnProject.Name = "ColumnProject";
labelProject.AutoSize = true;
labelProject.Location = new Point(15, 17);
labelProject.Name = "labelProject";
labelProject.Size = new Size(47, 15);
labelProject.TabIndex = 14;
labelProject.Text = "Проект";
//
// comboBoxProject
//
comboBoxProject.FormattingEnabled = true;
comboBoxProject.Location = new Point(96, 14);
comboBoxProject.Name = "comboBoxProject";
comboBoxProject.Size = new Size(224, 23);
comboBoxProject.TabIndex = 15;
//
// ColumnCustomer
//
ColumnCustomer.HeaderText = "Заказчик";
ColumnCustomer.Name = "ColumnCustomer";
//
// ColumnDescription
//
ColumnDescription.HeaderText = "Описание";
ColumnDescription.Name = "ColumnDescription";
ColumnDescription.Resizable = DataGridViewTriState.True;
ColumnDescription.SortMode = DataGridViewColumnSortMode.NotSortable;
//
// FormContract
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(399, 286);
ClientSize = new Size(399, 331);
Controls.Add(comboBoxProject);
Controls.Add(labelProject);
Controls.Add(groupBoxContract);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
@@ -109,6 +132,7 @@
groupBoxContract.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewContract).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -120,7 +144,9 @@
private Button ButtonCancel;
private GroupBox groupBoxContract;
private DataGridView dataGridViewContract;
private DataGridViewComboBoxColumn ColumnProject;
private Label labelProject;
private ComboBox comboBoxProject;
private DataGridViewComboBoxColumn ColumnCustomer;
private DataGridViewTextBoxColumn ColumnDescription;
}
}

View File

@@ -24,9 +24,9 @@ namespace ProjectItCompany.Forms
InitializeComponent();
_contractRepository = contractRepository ?? throw new ArgumentNullException(nameof(contractRepository));
ColumnProject.DataSource = projectRepository.ReadProjects();
ColumnProject.DisplayMember = "NameProject";
ColumnProject.ValueMember = "Id";
comboBoxProject.DataSource = projectRepository.ReadProjects();
comboBoxProject.DisplayMember = "NameProject";
comboBoxProject.ValueMember = "Id";
ColumnCustomer.DataSource = customerRepository.ReadCustomers();
ColumnCustomer.DisplayMember = "NameCustomer";
@@ -41,7 +41,7 @@ namespace ProjectItCompany.Forms
{
throw new Exception("Имеются незаполненные поля");
}
_contractRepository.CreateContract(Contract.CreateOpeartion(0, DateTime.Now, 0, CreateListExecutorOnProject()));
_contractRepository.CreateContract(Contract.CreateOpeartion(0, DateTime.Now, (int)comboBoxProject.SelectedValue, CreateListExecutorOnProject()));
Close();
}
catch (Exception ex)
@@ -58,13 +58,13 @@ namespace ProjectItCompany.Forms
var list = new List<Entities.CustomerOnProject>();
foreach (DataGridViewRow row in dataGridViewContract.Rows)
{
if (row.Cells["ColumnProject"].Value == null ||
row.Cells["ColumnCustomer"].Value == null)
if (row.Cells["ColumnCustomer"].Value == null ||
row.Cells["ColumnDescription"].Value == null)
{
continue;
}
list.Add(Entities.CustomerOnProject.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnProject"].Value), Convert.ToInt32(row.Cells["ColumnCustomer"].Value), string.Empty));
list.Add(Entities.CustomerOnProject.CreateElement(0, 0,
Convert.ToInt32(row.Cells["ColumnCustomer"].Value), row.Cells["ColumnDescription"].Value?.ToString()));
}
return list;
}

View File

@@ -117,7 +117,7 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumnProject.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<metadata name="ColumnCustomer.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@@ -95,7 +95,6 @@
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(580, 427);

View File

@@ -1140,7 +1140,7 @@
<data name="ButtonDelete.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vwAADr8BOAVTJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAD8lSURBVHhe7d0H
vgAADr4B6kKxwAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAD8lSURBVHhe7d0H
nFTlufjxiRqxd4PtRk2MGjWxEDUq7MxO3QEhatxoLFhQbFGwgWJbFRRjBSsKoogNFVOvsaWbm+v1aqJR
k39u7EmMjaLUnXOe/3OGdwLOvsiWKec95/f7fL4hssvuzJxz3uedYdlNEFG4kykDPi8/PGAreTS1R+ej
LfnSoy3f8R5NjvRmt4xVV6pbvdmD7vNnt/zQf3TQk6XZLb/zZief8x5p+au+7XX1UZWlSqoEv/fp93uk

View File

@@ -85,9 +85,12 @@
// numericUpDownHourlyRate
//
numericUpDownHourlyRate.Location = new Point(136, 84);
numericUpDownHourlyRate.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 });
numericUpDownHourlyRate.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownHourlyRate.Name = "numericUpDownHourlyRate";
numericUpDownHourlyRate.Size = new Size(151, 23);
numericUpDownHourlyRate.TabIndex = 5;
numericUpDownHourlyRate.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// ButtonSave
//

View File

@@ -80,6 +80,6 @@ namespace ProjectItCompany.Forms
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Executor CreateExecutor(int id) => Executor.CreateEntity(id, textBoxFullName.Text, dateTimePickerDateOfBirth.Value, numericUpDownHourlyRate.Value, Entities.Enums.JobTitles.Analyst);
private Executor CreateExecutor(int id) => Executor.CreateEntity(id, textBoxFullName.Text, dateTimePickerDateOfBirth.Value, numericUpDownHourlyRate.Value, (JobTitles)comboBoxJobTitle.SelectedItem!);
}
}

View File

@@ -51,7 +51,6 @@
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(638, 450);
@@ -111,6 +110,7 @@
Name = "FormExecutors";
StartPosition = FormStartPosition.CenterParent;
Text = "Исполнители";
Load += FormExecutors_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);

View File

@@ -121,7 +121,7 @@
<data name="ButtonUpd.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAABLAAAASwCAIAAABkQySYAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAA/7JJREFUeF7s/UlsbUua74fxNtlXZr16neBnC7b8BEiC5YGggXsJFmDA8MywbAuQ
vQAADr0BR/uQrQAA/7JJREFUeF7s/UlsbUua74fxNtlXZr16neBnC7b8BEiC5YGggXsJFmDA8MywbAuQ
ZFgTTeyJAQHWxJAnHnhgAxbgRjZgCLAnBoSnga2np6rK9vb3Ztar0itVVWZlZXfzno49D09/zqV/Eb9v
fwzuvcnDQ/Jwr334/UAEvogVK1asWGtF/P97bZIbR0VRFEVRFEVRFMWNpAxhURRFURRFURTFDaUMYVEU
RVEURVEUxQ2lDGFRFEVRFEVRFMUNpQxhURRFURRFURTFDaUMYVEURVEURVEUxQ2lDGFRFEVRFEVRFMUN
@@ -6527,7 +6527,7 @@
<data name="ButtonDelete.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vQAADr0BR/uQrQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAD8lSURBVHhe7d0H
vAAADrwBlbxySQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAD8lSURBVHhe7d0H
nFTlufjxiRqxd4PtRk2MGjWxEDUq7MxO3QEhatxoLFhQbFGwgWJbFRRjBSsKoogNFVOvsaWbm+v1aqJR
k39u7EmMjaLUnXOe/3OGdwLOvsiWKec95/f7fL4hssvuzJxz3uedYdlNEFG4kykDPi8/PGAreTS1R+ej
LfnSoy3f8R5NjvRmt4xVV6pbvdmD7vNnt/zQf3TQk6XZLb/zZief8x5p+au+7XX1UZWlSqoEv/fp93uk

View File

@@ -49,10 +49,20 @@ namespace ProjectItCompany.Forms
}
}
}
public FormProject(IProjectRepository projectRepository)
public FormProject(IProjectRepository projectRepository, ICustomerRepository customerRepository)
{
InitializeComponent();
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
comboBoxCustomer.DataSource = customerRepository.ReadCustomers();
comboBoxCustomer.DisplayMember = "NameCustomer";
comboBoxCustomer.ValueMember = "Id";
foreach (var elem in Enum.GetValues(typeof(CompletedStages)))
{
checkedListBoxCompletedStage.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)

View File

@@ -81,13 +81,17 @@
// numericUpDownYear
//
numericUpDownYear.Location = new Point(130, 32);
numericUpDownYear.Maximum = new decimal(new int[] { 2200, 0, 0, 0 });
numericUpDownYear.Minimum = new decimal(new int[] { 1950, 0, 0, 0 });
numericUpDownYear.Name = "numericUpDownYear";
numericUpDownYear.Size = new Size(120, 23);
numericUpDownYear.TabIndex = 5;
numericUpDownYear.Value = new decimal(new int[] { 1950, 0, 0, 0 });
//
// numericUpDownNumberOfHours
//
numericUpDownNumberOfHours.Location = new Point(130, 60);
numericUpDownNumberOfHours.Maximum = new decimal(new int[] { 100000000, 0, 0, 0 });
numericUpDownNumberOfHours.Name = "numericUpDownNumberOfHours";
numericUpDownNumberOfHours.Size = new Size(120, 23);
numericUpDownNumberOfHours.TabIndex = 6;
@@ -145,7 +149,7 @@
Controls.Add(labelMonth);
Name = "FormWage";
StartPosition = FormStartPosition.CenterParent;
Text = "FormWage";
Text = "Зарплата";
((System.ComponentModel.ISupportInitialize)numericUpDownYear).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownNumberOfHours).EndInit();
ResumeLayout(false);

View File

@@ -1,7 +1,11 @@
using Unity.Lifetime;
using Unity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectItCompany.Repositories;
using ProjectItCompany.Repositories.Implementations;
using Unity.Microsoft.Logging;
using Serilog;
namespace ProjectItCompany
{
@@ -22,13 +26,27 @@ namespace ProjectItCompany
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ICustomerRepository, CustomerRepository>(new TransientLifetimeManager());
container.RegisterType<IExecutorRepository, ExecutorRepository>(new TransientLifetimeManager());
container.RegisterType<IProjectRepository, ProjectRepository>(new TransientLifetimeManager());
container.RegisterType<IWageRepository, WageRepository>(new TransientLifetimeManager());
container.RegisterType<IContractRepository, ContractRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@@ -10,7 +10,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="5.0.8" />
<PackageReference Include="Npgsql" Version="6.0.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@@ -28,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 ProjectItCompany.Repositories;
public interface IConnectionString
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectItCompany.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost, 5432; Database=itcompanyotp;Uid=postgres;Pwd=marva;";
}

View File

@@ -1,26 +1,95 @@
using ProjectItCompany.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace ProjectItCompany.Repositories.Implementations;
internal class ContractRepository : IContractRepository
public class ContractRepository : IContractRepository
{
public void CreateContract(Contract contract)
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ContractRepository> _logger;
public ContractRepository(IConnectionString connectionString, ILogger<ContractRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateContract(Entities.Contract contract)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(contract));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"INSERT INTO contract (Date, ProjectId)
VALUES (@Date, @ProjectId);
SELECT MAX(Id) FROM contract";
var feedReplenishmentId = connection.QueryFirst<int>(queryInsert, contract, transaction);
var querySubInsert = @"INSERT INTO customeronproject (Description, ContractId, CustomerId)
VALUES ( @Description, @ContractId,@CustomerId)";
foreach (var elem in contract.CustomerOnContract)
{
connection.Execute(querySubInsert, new
{
elem.ContractId,
elem.Description,
elem.CustomerId
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteContract(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM contract
WHERE ID=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Contract> ReadContract(DateTime? dateForm = null, DateTime? dateTo = null, decimal? typeProject = null, int? customerId = null)
public IEnumerable<Entities.Contract> ReadContract(DateTime? dateForm = null, DateTime? dateTo = null, decimal? typeProject = null, int? customerId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM contract";
var contracts = connection.Query<Entities.Contract>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts));
return contracts;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@@ -1,4 +1,8 @@
using ProjectItCompany.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,30 +11,111 @@ using System.Threading.Tasks;
namespace ProjectItCompany.Repositories.Implementations;
internal class CustomerRepository : ICustomerRepository
public class CustomerRepository : ICustomerRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CustomerRepository> _logger;
public CustomerRepository(IConnectionString connectionString, ILogger<CustomerRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateCustomer(Customer customer)
{
}
public void DeleteCustomer(int id)
{
}
public Customer ReadCustomerById(int id)
{
return Customer.CreateEntity(0, string.Empty, string.Empty);
}
public IEnumerable<Customer> ReadCustomers()
{
return [];
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO customer (NameCustomer, Description)
VALUES (@NameCustomer, @Description)";
connection.Execute(queryInsert, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateCustomer(Customer customer)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE customer SET
NameCustomer=@NameCustomer,
Description=@Description
WHERE ID=@Id";
connection.Execute(queryUpdate, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteCustomer(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM customer WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Customer ReadCustomerById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM customer WHERE ID=@id";
var customer = connection.QueryFirst<Customer>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(customer));
return customer;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Customer> ReadCustomers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM customer";
var customers = connection.Query<Customer>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(customers));
return customers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@@ -1,4 +1,8 @@
using ProjectItCompany.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,30 +11,113 @@ using System.Threading.Tasks;
namespace ProjectItCompany.Repositories.Implementations;
internal class ExecutorRepository : IExecutorRepository
public class ExecutorRepository : IExecutorRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ExecutorRepository> _logger;
public ExecutorRepository(IConnectionString connectionString, ILogger<ExecutorRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateExecutor(Executor executor)
{
}
public void DeleteExecutor(int id)
{
}
public Executor ReadExecutorById(int id)
{
return Executor.CreateEntity(0, string.Empty, DateTime.Today, 1000, Entities.Enums.JobTitles.Developer);
}
public IEnumerable<Executor> ReadExecutors()
{
return [];
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(executor));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO executor (FullName, DateOfBirth, HourlyRate, JobTitles)
VALUES (@FullName, @DateOfBirth, @HourlyRate, @JobTitles)";
connection.Execute(queryInsert, executor);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateExecutor(Executor executor)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(executor));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE executor SET
FullName=@FullName,
DateOfBirth=@DateOfBirth,
HourlyRate=@HourlyRate,
JobTitles = @JobTitles
WHERE ID=@Id";
connection.Execute(queryUpdate, executor);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteExecutor(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM executor WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Executor ReadExecutorById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM executor WHERE ID=@id";
var executor = connection.QueryFirst<Executor>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(executor));
return executor;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Executor> ReadExecutors()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM executor";
var executors = connection.Query<Executor>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(executors));
return executors;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@@ -1,4 +1,8 @@
using ProjectItCompany.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,30 +11,112 @@ using System.Threading.Tasks;
namespace ProjectItCompany.Repositories.Implementations;
internal class ProjectRepository : IProjectRepository
public class ProjectRepository : IProjectRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProjectRepository> _logger;
public ProjectRepository(IConnectionString connectionString, ILogger<ProjectRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProject(Project project)
{
}
public void DeleteProject(int id)
{
}
public Project ReadProjectById(int id)
{
return Project.CreateEntity(1, string.Empty, 0, Entities.Enums.CompletedStages.Planning);
}
public IEnumerable<Project> ReadProjects()
{
return [];
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(project));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO project (NameProject, CustomerId, CompletedStages)
VALUES (@NameProject, @CustomerId, @CompletedStages)";
connection.Execute(queryInsert, project);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateProject(Project project)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(project));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE project SET
NameProject=@NameProject,
CustomerId=@CustomerId,
CompletedStages=@CompletedStages
WHERE ID=@Id";
connection.Execute(queryUpdate, project);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteProject(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM project WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Project ReadProjectById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM project WHERE ID=@id";
var project = connection.QueryFirst<Project>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(project));
return project;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Project> ReadProjects()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM project";
var projects = connection.Query<Project>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(projects));
return projects;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@@ -1,4 +1,8 @@
using ProjectItCompany.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectItCompany.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -7,15 +11,52 @@ using System.Threading.Tasks;
namespace ProjectItCompany.Repositories.Implementations;
internal class WageRepository : IWageRepository
public class WageRepository : IWageRepository
{
public void CreateWage(Wage wages)
private readonly IConnectionString _connectionString;
private readonly ILogger<WageRepository> _logger;
public WageRepository(IConnectionString connectionString, ILogger<WageRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateWage(Wage wage)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(wage));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO wage (Month, Year, NumberOfHours, ExecutorID)
VALUES (@Month, @Year, @NumberOfHours, @ExecutorID)";
connection.Execute(queryInsert, wage);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Wage> ReadWage(int? yearForm = null, int? yearTo = null, int? numberOfHoursFrom = null, int? numberOfHoursTo = null, int? executorId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM wage";
var wages = connection.Query<Wage>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(wages));
return wages;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

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

44
SQL.pgsql Normal file
View File

@@ -0,0 +1,44 @@
CREATE TABLE contract (
ID SERIAL PRIMARY KEY,
Date timestamp NOT NULL,
ProjectId INT REFERENCES project(ID),
CustomerId INT REFERENCES customer(ID)
);
CREATE TABLE customer (
ID SERIAL PRIMARY KEY,
NameCustomer VARCHAR(30) NOT NULL,
Description VARCHAR NOT NULL
);
CREATE TABLE customeronproject (
ID SERIAL PRIMARY KEY,
Descriptio VARCHAR NOT NULL,
ContractId INT REFERENCES contract(ID),
CustomerId INT REFERENCES customer(ID)
);
CREATE TABLE executor (
ID SERIAL PRIMARY KEY,
FullName VARCHAR NOT NULL,
DateOfBirth timestamp NOT NULL,
HourlyRate DECIMAL NOT NULL,
JobTitles INT NOT NULL
);
CREATE TABLE project (
ID SERIAL PRIMARY KEY,
NameProject VARCHAR NOT NULL,
CustomerId INT REFERENCES customer(ID),
CompletedStages INT NOT NULL
);
CREATE TABLE wage (
ID SERIAL PRIMARY KEY,
Month INT NOT NULL,
Year INT NOT NULL,
NumberOfHours INT,
ExecutorId INT REFERENCES executor(ID)
);
SELECT * FROM wage;