diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs
index ae1c735..4ecbbf9 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/AbstractCompany.cs
@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@@ -13,26 +14,32 @@ public abstract class AbstractCompany
/// Размер места (ширина)
///
protected readonly int _placeSizeWidth = 310;
+
///
/// Размер места (высота)
///
protected readonly int _placeSizeHeight = 125;
+
///
/// Ширина окна
///
protected readonly int _pictureWidth;
+
///
/// Высота окна
///
protected readonly int _pictureHeight;
+
///
/// Коллекция грузовиков
///
protected ICollectionGenericObject? _collection = null;
+
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+
///
/// Конструктор
///
@@ -55,7 +62,7 @@ public abstract class AbstractCompany
///
public static int operator +(AbstractCompany company, DrawningTruck truck)
{
- return company._collection.Insert(truck);
+ return company._collection.Insert(truck,0);
}
///
@@ -66,7 +73,7 @@ public abstract class AbstractCompany
///
public static DrawningTruck? operator -(AbstractCompany company, int position)
{
- return company._collection?.Remove(position-1);
+ return company._collection?.Remove(position);
}
///
@@ -76,7 +83,14 @@ public abstract class AbstractCompany
public DrawningTruck? GetRandomObject()
{
Random rnd = new();
- return _collection?.Get(rnd.Next(GetMaxCount));
+ try
+ {
+ return _collection?.Get(rnd.Next(GetMaxCount));
+ }
+ catch (ObjectNotFoundException)
+ {
+ return null;
+ }
}
///
@@ -92,8 +106,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawningTruck? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawningTruck? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException)
+ {
+ continue;
+ }
}
return bitmap;
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/Autopark.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/Autopark.cs
index 5f237b6..96903c9 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/Autopark.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/Autopark.cs
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@@ -42,25 +43,29 @@ public class Autopark : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- if (_collection?.Get(i) != null)
+ try
{
- int x = 20 + _placeSizeWidth * n;
- int y = 10 + _placeSizeHeight * m;
+ if (_collection?.Get(i) != null)
+ {
+ int x = 20 + _placeSizeWidth * n;
+ int y = 10 + _placeSizeHeight * m;
- _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
- _collection?.Get(i)?.SetPosition(x, y);
+ _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection?.Get(i)?.SetPosition(x, y);
+ }
+
+ if (n < _pictureWidth / _placeSizeWidth) n++;
+
+ else
+ {
+ n = 0;
+ m++;
+ }
}
-
- if (n < _pictureWidth / _placeSizeWidth)
- n++;
- else
+ catch (ObjectNotFoundException)
{
- n = 0;
- m++;
+ break;
}
}
}
-
-
-
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs
index 0599ff4..94d269a 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/ListGenericObjects.cs
@@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using ProjectDumpTruck.Exceptions;
+
namespace ProjectDumpTruck.CollectionGenericObject;
@@ -50,7 +52,7 @@ public class ListGenericObjects : ICollectionGenericObject
{
if (position < 0 || position >= Count)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
return _collection[position];
@@ -60,7 +62,7 @@ public class ListGenericObjects : ICollectionGenericObject
{
if (Count == _maxCount)
{
- return -1;
+ throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
@@ -69,9 +71,13 @@ public class ListGenericObjects : ICollectionGenericObject
public int Insert(T obj, int position)
{
- if (Count == _maxCount || position < 0 || position > Count)
+ if (position < 0 || position > Count)
{
- return -1;
+ throw new PositionOutOfCollectionException(position);
+ }
+ if (Count == _maxCount)
+ {
+ throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
@@ -82,7 +88,7 @@ public class ListGenericObjects : ICollectionGenericObject
{
if (position < 0 || position > Count)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
@@ -91,7 +97,7 @@ public class ListGenericObjects : ICollectionGenericObject
return obj;
}
- public IEnumerable GetItems()
+ public IEnumerable GetItems()
{
for (int i = 0; i < Count; i++) yield return _collection[i];
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs
index 6e37fe0..db74384 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/MassiveGenericObjects.cs
@@ -4,6 +4,7 @@ using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
+using ProjectDumpTruck.Exceptions;
namespace ProjectDumpTruck.CollectionGenericObject;
@@ -52,6 +53,14 @@ public class MassiveGenericObjects : ICollectionGenericObject
public T? Get(int position)
{
+ if (position < 0 || position >= Count)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ if (_collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
// TODO проверка позиции
if (position < 0 || position >= Count)
{
@@ -71,14 +80,15 @@ public class MassiveGenericObjects : ICollectionGenericObject
return i;
}
}
- return -1;
+
+ throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
- return -1;
+ throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@@ -105,17 +115,20 @@ public class MassiveGenericObjects : ICollectionGenericObject
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
- if (_collection[position] == null) return null;
+ if (_collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
T? temp = _collection[position];
_collection[position] = null;
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs
index 15ea39e..b9ced44 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObject/StorageCollection.cs
@@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -102,7 +103,7 @@ public class StorageCollection
{
if (File.Exists(filename)) File.Delete(filename);
- if (_storages.Count == 0) return false;
+ if (_storages.Count == 0) throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
using (StreamWriter sw = new StreamWriter(filename))
{
@@ -143,19 +144,16 @@ public class StorageCollection
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
public bool LoadData(string filename)
{
- if (!File.Exists(filename)) return false;
+ if (!File.Exists(filename)) throw new FileNotFoundException("Файл не существует");
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
- if (line == null || line.Length == 0) return false;
+ if (line == null || line.Length == 0) throw new FileFormatException("В файле нет данных"); ;
+
+ if (!line.Equals(_collectionKey)) throw new FileFormatException("В файле неверные данные");
- if (!line.Equals(_collectionKey))
- {
- //если нет такой записи, то это не те данные
- return false;
- }
_storages.Clear();
while ((line = sr.ReadLine()) != null)
@@ -168,10 +166,8 @@ public class StorageCollection
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObject? collection = StorageCollection.CreateCollection(collectionType);
- if (collection == null)
- {
- return false;
- }
+
+ if (collection == null) throw new InvalidOperationException("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@@ -179,9 +175,16 @@ public class StorageCollection
{
if (elem?.CreateDrawningTruck() is T truck)
{
- if (collection.Insert(truck) == -1)
+ try
{
- return false;
+ if (collection.Insert(truck) == -1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new OverflowException("Коллекция переполнена", ex);
}
}
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..b498440
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectDumpTruck.Exceptions;
+
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+internal class CollectionOverflowException : ApplicationException
+{
+ public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
+
+ public CollectionOverflowException() : base() { }
+
+ public CollectionOverflowException(string message) : base(message) { }
+
+ public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
+
+ protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+
+}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectNotFoundException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..f39ad97
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectDumpTruck.Exceptions;
+
+///
+/// Класс, описывающий ошибку, что по указанной позиции нет элемента
+///
+[Serializable]
+internal class ObjectNotFoundException : ApplicationException
+{
+ public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
+
+ public ObjectNotFoundException() : base() { }
+
+ public ObjectNotFoundException(string message) : base(message) { }
+
+ public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
+
+ protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+
+}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/PositionOutOfCollectionException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..656623a
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectDumpTruck.Exceptions;
+
+///
+/// Класс, описывающий ошибку выхода за границы коллекции
+///
+[Serializable]
+internal class PositionOutOfCollectionException : ApplicationException
+{
+ public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
+
+ public PositionOutOfCollectionException() : base() { }
+
+ public PositionOutOfCollectionException(string message) : base(message) { }
+
+ public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
+
+ protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+
+}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs
index a35e3e0..82bfa83 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs
@@ -1,5 +1,7 @@
-using ProjectDumpTruck.CollectionGenericObject;
+using Microsoft.Extensions.Logging;
+using ProjectDumpTruck.CollectionGenericObject;
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -30,13 +32,16 @@ public partial class FormTruckCollection : Form
///
private AbstractCompany? _company = null;
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormTruckCollection()
+ public FormTruckCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -67,19 +72,24 @@ public partial class FormTruckCollection : Form
///
private void SetTruck(DrawningTruck truck)
{
- if (_company == null || truck == null)
+ try
{
- return;
- }
+ if (_company == null || truck == null)
+ {
+ return;
+ }
- if (_company + truck != -1)
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
+ if (_company + truck != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ _logger.LogInformation($"Добавлен объект {truck.GetDataForSave()}");
+ pictureBox.Image = _company.Show();
+ }
}
- else
+ catch (CollectionOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogWarning($"Ошибка: {ex.Message}");
}
}
@@ -100,15 +110,25 @@ public partial class FormTruckCollection : Form
return;
}
- int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Удален объект по позиции {pos}");
+ pictureBox.Image = _company.Show();
+ }
}
- else
+ catch (ObjectNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogError($"Ошибка: {ex.Message}");
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError($"Ошибка: {ex.Message}");
}
}
@@ -168,6 +188,7 @@ public partial class FormTruckCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@@ -182,6 +203,7 @@ public partial class FormTruckCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RefreshListBoxItems();
}
@@ -211,6 +233,7 @@ public partial class FormTruckCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ _logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RefreshListBoxItems();
}
@@ -248,13 +271,16 @@ public partial class FormTruckCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@@ -268,14 +294,17 @@ public partial class FormTruckCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
+ _logger.LogInformation("Загрузка из фала: {filename}", openFileDialog.FileName);
}
- else
+ catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Program.cs b/ProjectDumpTruck/ProjectDumpTruck/Program.cs
index 589f4a5..79c5baa 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/Program.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/Program.cs
@@ -1,3 +1,10 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.DependencyInjection;
+using Serilog;
+using System;
+
+
namespace ProjectDumpTruck
{
internal static class Program
@@ -11,7 +18,30 @@ namespace ProjectDumpTruck
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormTruckCollection());
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+
+ ///
+ /// DI
+ ///
+ ///
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services
+ .AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ var config = new ConfigurationBuilder()
+ .AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
+ .Build();
+ option.AddSerilog(Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(config)
+ .CreateLogger());
+ });
}
}
}
\ No newline at end of file
diff --git a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
index 244387d..832887d 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
+++ b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
@@ -8,6 +8,18 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +35,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/ProjectDumpTruck/ProjectDumpTruck/serilogConfig.json b/ProjectDumpTruck/ProjectDumpTruck/serilogConfig.json
new file mode 100644
index 0000000..b105243
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/serilogConfig.json
@@ -0,0 +1,25 @@
+{
+ "AllowedHosts": "*",
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
+ "MinimumLevel": {
+ "Default": "Information",
+ "Override": {
+ "Microsoft": "Warning",
+ "System": "Warning"
+ }
+ },
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
+ "WriteTo": [
+ { "Name": "Console" },
+ {
+ "Name": "File",
+ "Args": {
+ "path": "C:\\Users\\dimoo\\OneDrive\\Рабочий стол\\Лабы\\log.txt",
+ "rollingInterval": "Day",
+ "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
+ }
+ }
+ ]
+ }
+}