Доработан Logger, а также исправлена ошибка с удалением лайнера

This commit is contained in:
gettterot 2024-05-15 09:37:25 +04:00
parent ba8685e9dc
commit 7ac785ccfd
8 changed files with 111 additions and 59 deletions

View File

@ -45,8 +45,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException();
if (_collection[position] == null) throw new ObjectNotFoundException();
// Проверка позиции
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)

View File

@ -77,5 +77,4 @@ public class EntityLiner: EntityCommonLiner
Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
}

View File

@ -75,7 +75,7 @@
// buttonCreateCompany
//
buttonCreateCompany.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
buttonCreateCompany.Location = new Point(8, 520);
buttonCreateCompany.Location = new Point(7, 495);
buttonCreateCompany.Margin = new Padding(5);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(257, 38);
@ -96,13 +96,13 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 43);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(266, 405);
panelStorage.Size = new Size(266, 370);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
buttonCollectionDel.Location = new Point(5, 348);
buttonCollectionDel.Location = new Point(3, 314);
buttonCollectionDel.Margin = new Padding(5);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(257, 38);
@ -180,7 +180,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(20, 458);
comboBoxSelectorCompany.Location = new Point(23, 419);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(242, 49);
comboBoxSelectorCompany.TabIndex = 0;

View File

@ -2,6 +2,7 @@
using Microsoft.Extensions.Logging;
using ProjectLiner.CollectionGenericObjects;
using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
using System.Windows.Forms;
namespace ProjectLiner;
@ -57,20 +58,24 @@ public partial class FormLinerCollection : Form
/// </summary>
/// <param name="airplane"></param>
private void SetLiner(DrawningCommonLiner liner)
{
try
{
if (_company == null || liner == null)
{
return;
}
if (_company + liner != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + liner.GetDataForSave());
}
else
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -81,26 +86,43 @@ public partial class FormLinerCollection : Form
/// <param name="e"></param>
private void ButtonRemoveLiner_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition?.Text) || _company == null)
if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
int pos = Convert.ToInt32(maskedTextBox1.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удаление объекта по индексу " + pos);
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить объект из коллекции по индексу " + pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
@ -118,14 +140,19 @@ public partial class FormLinerCollection : Form
{
liner = _company.GetRandomObject();
counter--;
if (counter <= 0) break;
if (counter <= 0)
{
break;
}
}
if (liner == null)
{
return;
}
FormLiner form = new FormLiner();
form.SetLiner = liner;
FormLiner form = new()
{
SetLiner = liner
};
form.ShowDialog();
}
/// <summary>
@ -153,6 +180,7 @@ public partial class FormLinerCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
@ -166,6 +194,7 @@ public partial class FormLinerCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Добавлена коллекция типа " + collectionType + " с названием " + textBoxCollectionName.Text);
}
/// <summary>
/// Удаление коллекции
@ -184,6 +213,7 @@ public partial class FormLinerCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@ -271,10 +301,12 @@ public partial class FormLinerCollection : Form
listBoxCollection.Items.Add(collection);
}
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,7 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
using Serilog;
namespace ProjectLiner
{
@ -15,28 +15,36 @@ namespace ProjectLiner
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureService(services);
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormLinerCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ Ñåðâåñà DI
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureService(ServiceCollection services)
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormLinerCollection>()
.AddLogging(option =>
{
services
.AddSingleton<FormLinerCollection>()
.AddLogging(option => {
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("serilog.config");
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@ -11,6 +11,10 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
@ -29,7 +33,7 @@
</ItemGroup>
<ItemGroup>
<None Update="serilog.config">
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@ -0,0 +1,19 @@
{
"Serilog": {
"Using": [
"Serilog.Sinks.File"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log"
}
}
],
"Properties": {
"Application": "Sample"
}
}
}