This commit is contained in:
Илья Федотов 2024-03-15 20:34:55 +04:00
parent 79fa46d69f
commit 6b7e29018c
9 changed files with 208 additions and 53 deletions

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="NLog.Schema" Version="5.2.8" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.8" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +37,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.Exceptions
{
[Serializable]
internal class BulldozerNotFoundException : ApplicationException
{
public BulldozerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BulldozerNotFoundException() : base() { }
public BulldozerNotFoundException(string message) : base(message) { }
public BulldozerNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BulldozerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception Exception) : base(message, Exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -2,6 +2,8 @@
using Bulldoser.Generic;
using Bulldoser.MovementStrategy;
using Bulldozer.Generics;
using Microsoft.Extensions.Logging;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -17,10 +19,12 @@ namespace Bulldoser
public partial class FormTractorCollection : Form
{
private readonly TractorGenericStorage _storage;
public FormTractorCollection()
private readonly ILogger _logger;
public FormTractorCollection(ILogger<FormTractorCollection> logger)
{
InitializeComponent();
_storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height);
_logger = logger;
}
private void ReloadObjects()
{
@ -45,10 +49,12 @@ namespace Bulldoser
if (string.IsNullOrEmpty(InputNabor.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return;
}
_storage.AddSet(InputNabor.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {InputNabor.Text}");
}
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
{
@ -58,13 +64,21 @@ namespace Bulldoser
{
if (listBoxStorage.SelectedIndex == -1)
{
_logger.LogWarning("Выберите набор для удаления!");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"Удален набор: {name}");
}
}
@ -77,48 +91,71 @@ namespace Bulldoser
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
FormBulldoserConfig form = new(pictureBoxCollections.Width, pictureBoxCollections.Height);
form.Show();
Action<DrawingTractor>? TractorDelegate = new((m) =>
Action<DrawingTractor> armoredTransportDelegate = new Action<DrawingTractor>((tractor) =>
{
int q = (obj + m);
if (q != -1 && q < 10)
try
{
bool selectedArmoredTransport = obj + tractor;
MessageBox.Show("Объект добавлен");
pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorage.SelectedItem.ToString()}");
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
});
form.AddEvent(TractorDelegate);
form.AddEvent(armoredTransportDelegate);
form.Show();
}
private void ButtonRemoveTractor_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1) return;
if (listBoxStorage.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumbers.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollections.Image = obj.ShowTractors();
if (string.IsNullOrEmpty(maskedTextBoxNumbers.Text) || maskedTextBoxNumbers.Text == "_")
{
MessageBox.Show("Введите корректное значение для номера");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumbers.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"Удален объект из набора {listBoxStorage.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}");
}
}
else
catch (BulldozerNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorage.SelectedItem.ToString()}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -136,15 +173,16 @@ namespace Bulldoser
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
@ -153,17 +191,22 @@ namespace Bulldoser
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
foreach (var collection in _storage.Keys)
{
listBoxStorage.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не удалось загрузить: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
ReloadObjects();
}
}
}

View File

@ -30,21 +30,21 @@ namespace Bulldoser.Generic
_collection = new SetGeneric<T>(width * height);
}
/// Перегрузка оператора сложения
public static int operator +(TractorGenericCollection<T, U> collect, T tract)
public static bool operator +(TractorGenericCollection<T, U> collect, T tract)
{
if (tract == null)
{
return -1;
return false;
}
return collect._collection.Insert(tract);
return collect?._collection.Insert(tract) ?? false;
}
public static T? operator -(TractorGenericCollection<T, U> collect, int
pos)
{
T obj = collect._collection[pos];
T? obj = collect._collection[pos];
if (obj != null)
{
return collect._collection.Remove(pos);
collect._collection.Remove(pos);
}
return obj;
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectBulldozer.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -16,25 +17,36 @@ namespace Bulldoser.Generic
_places = new List<T?>(count);
_maxCount = count;
}
public int Insert(T tract)
public bool Insert(T tract)
{
return Insert(tract, 0 );
return Insert(tract, 0);
}
public int Insert(T tract, int position)
public bool Insert(T tract, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return -1;
if (position < 0 || position >= _maxCount)
{
throw new BulldozerNotFoundException(position);
}
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, tract);
return position;
return true;
}
public T? Remove(int position)
public bool Remove(int position)
{
if (position >= Count || position < 0)
return null;
T? tmp = _places[position];
if (position < 0 || position >= _maxCount)
{
return false;
}
if (_places[position] == null)
{
throw new BulldozerNotFoundException(position);
}
_places[position] = null;
return tmp;
return true;
}
//Получение объекта из набора по позиции
public T? this[int position]

View File

@ -67,7 +67,7 @@ namespace Bulldozer.Generics
}
if (data.Length == 0)
{
return false;
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"TractorsStorage{Environment.NewLine}{data}");
@ -77,7 +77,7 @@ namespace Bulldozer.Generics
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = File.OpenText(filename))
{
@ -88,7 +88,7 @@ namespace Bulldozer.Generics
}
if (!str.StartsWith("TractorsStorage"))
{
return false;
throw new FormatException("Неверный формат данных");
}
_TractorsStorage.Clear();
@ -115,9 +115,9 @@ namespace Bulldozer.Generics
_pictureWidth, _pictureHeight);
if (tractor != null)
{
if ((collection + tractor) == -1)
if (!(collection + tractor))
{
return false;
throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Bulldoser
{
internal static class Program
@ -11,7 +16,28 @@ namespace Bulldoser
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTractorCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTractorCollection>());
}
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormTractorCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string appPath = "";
for (int i = 0; i < path.Length - 3; i++)
{
appPath += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs/bulldozerlog-.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Bulldozer"
}
}
}