diff --git a/Bulldozer/Bulldozer/AppSettings.json b/Bulldozer/Bulldozer/AppSettings.json
new file mode 100644
index 0000000..4a2321d
--- /dev/null
+++ b/Bulldozer/Bulldozer/AppSettings.json
@@ -0,0 +1,20 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "Logs/log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
+ "Properties": {
+ "Application": "Bulldozers"
+ }
+ }
+}
\ No newline at end of file
diff --git a/Bulldozer/Bulldozer/Bulldozer.csproj b/Bulldozer/Bulldozer/Bulldozer.csproj
index 13ee123..bcffee6 100644
--- a/Bulldozer/Bulldozer/Bulldozer.csproj
+++ b/Bulldozer/Bulldozer/Bulldozer.csproj
@@ -8,7 +8,20 @@
enable
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
True
True
@@ -23,4 +36,6 @@
+
+
\ No newline at end of file
diff --git a/Bulldozer/Bulldozer/Exceptions/BulldozerNotFoundException.cs b/Bulldozer/Bulldozer/Exceptions/BulldozerNotFoundException.cs
new file mode 100644
index 0000000..32da881
--- /dev/null
+++ b/Bulldozer/Bulldozer/Exceptions/BulldozerNotFoundException.cs
@@ -0,0 +1,16 @@
+
+
+using System.Runtime.Serialization;
+
+namespace Bulldozer.Exceptions
+{
+ 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 contex) : base(info, contex) { }
+ }
+}
diff --git a/Bulldozer/Bulldozer/Exceptions/StorageOverflowException.cs b/Bulldozer/Bulldozer/Exceptions/StorageOverflowException.cs
new file mode 100644
index 0000000..74ea391
--- /dev/null
+++ b/Bulldozer/Bulldozer/Exceptions/StorageOverflowException.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Bulldozer.Exceptions
+{
+ 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 contex) : base(info, contex) { }
+ }
+}
diff --git a/Bulldozer/Bulldozer/FormBulldozerCollection.cs b/Bulldozer/Bulldozer/FormBulldozerCollection.cs
index 38d1a6f..97e804a 100644
--- a/Bulldozer/Bulldozer/FormBulldozerCollection.cs
+++ b/Bulldozer/Bulldozer/FormBulldozerCollection.cs
@@ -1,8 +1,11 @@
using Bulldozer.DrawingObjects;
using Bulldozer.Generics;
using Bulldozer.MovementStrategy;
+using System.Numerics;
using System.Windows.Forms;
-
+using Microsoft.VisualBasic.Logging;
+using Bulldozer.Exceptions;
+using Microsoft.Extensions.Logging;
namespace Bulldozer
{
@@ -12,13 +15,12 @@ namespace Bulldozer
/// Набор объектов
///
private readonly BulldozersGenericStorage _storage;
-
-
- public FormBulldozerCollection()
+ private readonly ILogger _logger;
+ public FormBulldozerCollection(ILogger logger)
{
InitializeComponent();
_storage = new BulldozersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
-
+ _logger = logger;
}
///
@@ -52,10 +54,12 @@ namespace Bulldozer
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+ _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
///
@@ -83,6 +87,7 @@ namespace Bulldozer
{
_storage.DelSet(listBoxBulldozerStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
+ _logger.LogInformation($"Удален набор: {Name}");
}
}
@@ -116,14 +121,15 @@ namespace Bulldozer
{
return;
}
- if (obj + bulldozer > -1)
+ try
{
+ _ = obj + bulldozer;
MessageBox.Show("Объект добавлен");
+ _logger.LogInformation("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBulldozers();
- }
- else
- {
- MessageBox.Show("Не удалось добавить объект");
+ } catch(Exception ex) {
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"Объект не добавлен в набор {listBoxBulldozerStorages.SelectedItem.ToString()}");
}
}
@@ -148,15 +154,28 @@ namespace Bulldozer
{
return;
}
- int pos = Convert.ToInt32(textBoxDeletingBulldozer.Text);
- if (obj - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBoxCollection.Image = obj.ShowBulldozers();
+ int pos = Convert.ToInt32(textBoxDeletingBulldozer.Text);
+ if (obj - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation("Объект удален");
+ pictureBoxCollection.Image = obj.ShowBulldozers();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Не удалось удалить объект");
+ }
}
- else
+ catch (BulldozerNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ }
+ catch (Exception ex) {
+ MessageBox.Show("Неверный ввод");
+ _logger.LogWarning("Неверный ввод");
}
}
@@ -188,13 +207,16 @@ namespace Bulldozer
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
+ try
{
+ _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
+ _logger.LogInformation("Сохранение прошло успешно");
+
+ } catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogInformation($"Не сохранилось: {ex.Message}");
}
}
}
@@ -207,15 +229,17 @@ namespace Bulldozer
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
+ _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Загрузка прошла успешно");
ReloadObjects();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
-
+ MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
}
diff --git a/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs b/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs
index 4e6e5b9..ca6d47e 100644
--- a/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs
+++ b/Bulldozer/Bulldozer/Generics/BulldozersGenericCollection.cs
@@ -50,11 +50,11 @@ namespace Bulldozer.Generics
///
///
///
- public static int operator +(BulldozersGenericCollection collect, T? obj)
+ public static bool operator +(BulldozersGenericCollection collect, T obj)
{
if (obj == null)
- return -1;
- return collect?._collection.Insert(obj) ?? -1;
+ return false;
+ return collect._collection.Insert(obj);
}
///
diff --git a/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs b/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs
index e8e5b83..36f2155 100644
--- a/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs
+++ b/Bulldozer/Bulldozer/Generics/BulldozersGenericStorage.cs
@@ -1,6 +1,8 @@
using Bulldozer.DrawingObjects;
using Bulldozer.MovementStrategy;
using System.Text;
+using Bulldozer.Exceptions;
+using System.Numerics;
namespace Bulldozer.Generics
{
@@ -116,7 +118,7 @@ namespace Bulldozer.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new Exception("Невалидная операция, нет данных для сохранения");
}
string toWrite = $"BulldozerStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@@ -139,7 +141,7 @@ namespace Bulldozer.Generics
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -147,11 +149,11 @@ namespace Bulldozer.Generics
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
- throw new IOException("Нет данных для загрузки");
+ throw new ArgumentException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("BulldozerStorage"))
{
- throw new IOException("Неверный формат данных");
+ throw new ArgumentException("Неверный формат данных");
}
_bulldozerStorages.Clear();
do
@@ -170,9 +172,20 @@ namespace Bulldozer.Generics
elem?.CreateDrawingBulldozer(_separatorForObject, _pictureWidth, _pictureHeight);
if (bulldozer != null)
{
- if ((collection + bulldozer) == -1)
+ if (collection + bulldozer)
{
- throw new IOException("Ошибка добавления в коллекцию");
+ try
+ {
+ _ = collection + bulldozer;
+ }
+ catch (BulldozerNotFoundException e)
+ {
+ throw e;
+ }
+ catch (StorageOverflowException e)
+ {
+ throw e;
+ }
}
}
}
diff --git a/Bulldozer/Bulldozer/Generics/SetGeneric.cs b/Bulldozer/Bulldozer/Generics/SetGeneric.cs
index 9873cb8..165e25f 100644
--- a/Bulldozer/Bulldozer/Generics/SetGeneric.cs
+++ b/Bulldozer/Bulldozer/Generics/SetGeneric.cs
@@ -1,4 +1,5 @@
-using System.Numerics;
+using Bulldozer.Exceptions;
+using System.Numerics;
namespace Bulldozer.Generics
{
@@ -38,12 +39,9 @@ namespace Bulldozer.Generics
///
/// Добавляемый бульдозер
///
- public int Insert(T bulldozer)
+ public bool Insert(T bulldozer)
{
- if (_places.Count == _maxCount)
- return -1;
- Insert(bulldozer, 0);
- return 1;
+ return Insert(bulldozer, 0);
}
///
@@ -51,11 +49,14 @@ namespace Bulldozer.Generics
///
/// Добавляемый бульдозер
///
- public int Insert(T bulldozer , int position)
+ public bool Insert(T bulldozer , int position)
{
- if (position < 0 || position >= _maxCount) return -1;
+ if (position < 0 || position >= _maxCount) {
+ throw new StorageOverflowException("Вставка невозможна.");
+ }
+ if (Count >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, bulldozer);
- return position;
+ return true;
}
///
@@ -66,8 +67,8 @@ namespace Bulldozer.Generics
public bool Remove(int position)
{
if (position < 0 || position >= Count)
- return false;
-
+ throw new BulldozerNotFoundException("Невалидная операция");
+ if (_places[position] == null) throw new BulldozerNotFoundException(position);
_places.RemoveAt(position);
return true;
diff --git a/Bulldozer/Bulldozer/Program.cs b/Bulldozer/Bulldozer/Program.cs
index f68daeb..4b73731 100644
--- a/Bulldozer/Bulldozer/Program.cs
+++ b/Bulldozer/Bulldozer/Program.cs
@@ -1,4 +1,10 @@
-namespace Bulldozer.MovementStrategy
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Bulldozer;
+
+namespace Bulldozer
{
internal static class Program
{
@@ -9,7 +15,29 @@ namespace Bulldozer.MovementStrategy
static void Main()
{
ApplicationConfiguration.Initialize();
- Application.Run(new FormBulldozerCollection());
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ using (ServiceProvider serviceProvider = services.BuildServiceProvider())
+ {
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ }
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton().AddLogging(option =>
+ {
+ string[] path = Directory.GetCurrentDirectory().Split('\\');
+ string pathNeed = "";
+ for (int i = 0; i < path.Length - 3; i++)
+ {
+ pathNeed += path[i] + "\\";
+ }
+ var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}AppSettings.json", optional: false, reloadOnChange: true).Build();
+ var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
+
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(logger);
+ });
}
}
}
\ No newline at end of file