diff --git a/Bulldoser/Bulldoser/Bulldoser.csproj b/Bulldoser/Bulldoser/Bulldoser.csproj
index 244387d..c44b519 100644
--- a/Bulldoser/Bulldoser/Bulldoser.csproj
+++ b/Bulldoser/Bulldoser/Bulldoser.csproj
@@ -8,6 +8,20 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +37,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/Bulldoser/Bulldoser/Exceptions/BulldozerNotFoundException.cs b/Bulldoser/Bulldoser/Exceptions/BulldozerNotFoundException.cs
new file mode 100644
index 0000000..ad76077
--- /dev/null
+++ b/Bulldoser/Bulldoser/Exceptions/BulldozerNotFoundException.cs
@@ -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) { }
+ }
+}
diff --git a/Bulldoser/Bulldoser/Exceptions/StorageOverflowException.cs b/Bulldoser/Bulldoser/Exceptions/StorageOverflowException.cs
new file mode 100644
index 0000000..3a180e8
--- /dev/null
+++ b/Bulldoser/Bulldoser/Exceptions/StorageOverflowException.cs
@@ -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) { }
+ }
+}
diff --git a/Bulldoser/Bulldoser/Form2.cs b/Bulldoser/Bulldoser/Form2.cs
index 1d4543c..d6ad95a 100644
--- a/Bulldoser/Bulldoser/Form2.cs
+++ b/Bulldoser/Bulldoser/Form2.cs
@@ -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 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? TractorDelegate = new((m) =>
+ Action armoredTransportDelegate = new Action((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();
}
}
}
diff --git a/Bulldoser/Bulldoser/Generic/BulldoserGenericCollection.cs b/Bulldoser/Bulldoser/Generic/BulldoserGenericCollection.cs
index 1775edf..37b64aa 100644
--- a/Bulldoser/Bulldoser/Generic/BulldoserGenericCollection.cs
+++ b/Bulldoser/Bulldoser/Generic/BulldoserGenericCollection.cs
@@ -30,21 +30,21 @@ namespace Bulldoser.Generic
_collection = new SetGeneric(width * height);
}
/// Перегрузка оператора сложения
- public static int operator +(TractorGenericCollection collect, T tract)
+ public static bool operator +(TractorGenericCollection 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 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;
}
diff --git a/Bulldoser/Bulldoser/Generic/SetGeneric.cs b/Bulldoser/Bulldoser/Generic/SetGeneric.cs
index 0de977f..ce3e1a3 100644
--- a/Bulldoser/Bulldoser/Generic/SetGeneric.cs
+++ b/Bulldoser/Bulldoser/Generic/SetGeneric.cs
@@ -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(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]
diff --git a/Bulldoser/Bulldoser/Generic/TractorGenericStorage.cs b/Bulldoser/Bulldoser/Generic/TractorGenericStorage.cs
index 2b0b283..be66ce1 100644
--- a/Bulldoser/Bulldoser/Generic/TractorGenericStorage.cs
+++ b/Bulldoser/Bulldoser/Generic/TractorGenericStorage.cs
@@ -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("Ошибка добавления в коллекцию");
}
}
}
diff --git a/Bulldoser/Bulldoser/Program.cs b/Bulldoser/Bulldoser/Program.cs
index 63fac9b..ae2e4de 100644
--- a/Bulldoser/Bulldoser/Program.cs
+++ b/Bulldoser/Bulldoser/Program.cs
@@ -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());
+ }
+ }
+ private static void ConfigureServices(IServiceCollection services)
+ {
+ services.AddSingleton().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);
+ });
}
}
}
\ No newline at end of file
diff --git a/Bulldoser/Bulldoser/appsettings.json b/Bulldoser/Bulldoser/appsettings.json
new file mode 100644
index 0000000..99ad4bf
--- /dev/null
+++ b/Bulldoser/Bulldoser/appsettings.json
@@ -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"
+ }
+ }
+}
\ No newline at end of file