diff --git a/GasolineTanker/GasolineTanker/CollectionGenericObjects/AbstractCompany.cs b/GasolineTanker/GasolineTanker/CollectionGenericObjects/AbstractCompany.cs
index 541c071..cc8fcd0 100644
--- a/GasolineTanker/GasolineTanker/CollectionGenericObjects/AbstractCompany.cs
+++ b/GasolineTanker/GasolineTanker/CollectionGenericObjects/AbstractCompany.cs
@@ -27,6 +27,11 @@ public abstract class AbstractCompany
///
protected readonly int _pictureHeight;
+ ///
+ /// Максимальное количество мест
+ ///
+ protected int _maxCount;
+
///
/// Коллекция грузовиков
///
@@ -35,7 +40,19 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+
+ private int GetMaxCount
+ {
+ get
+ {
+ double _divisibleOfWidth = _pictureWidth / _placeSizeWidth;
+ double _divisibleOfHeight = _pictureHeight / _placeSizeHeight;
+ double _placesInWidth = Math.Truncate(_divisibleOfWidth);
+ double _placesInHeight = Math.Truncate(_divisibleOfHeight);
+ _maxCount = (int)(_placesInWidth * _placesInHeight);
+ return _maxCount;
+ }
+ }
///
/// Конструктор
diff --git a/GasolineTanker/GasolineTanker/CollectionGenericObjects/ListGenericObjects.cs b/GasolineTanker/GasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
index 1bf33d1..261e8e9 100644
--- a/GasolineTanker/GasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
+++ b/GasolineTanker/GasolineTanker/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,5 @@
using GasolineTanker.CollectionGenericObjects;
+using GasolineTanker.Exceptions;
///
/// Параметризованный набор объектов
@@ -46,9 +47,9 @@ public class ListGenericObjects : ICollectionGenericObjects
public T? Get(int position)
{
- if (position < 0 || position >= Count)
+ if (position < 0 || position >= _maxCount)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
@@ -57,7 +58,7 @@ public class ListGenericObjects : ICollectionGenericObjects
{
if (Count == _maxCount)
{
- return false;
+ throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return true;
@@ -65,9 +66,13 @@ public class ListGenericObjects : ICollectionGenericObjects
public bool Insert(T obj, int position)
{
- if (Count >= _maxCount || position < 0 || position >= Count)
+ if (Count == _maxCount)
{
- return false;
+ throw new CollectionOverflowException(Count);
+ }
+ if (position < 0 || position >= _maxCount)
+ {
+ throw new PositionOutOfCollectionException(position);
}
_collection.Insert(position, obj);
return true;
@@ -75,12 +80,13 @@ public class ListGenericObjects : ICollectionGenericObjects
public bool Remove(int position)
{
- if (position < 0 || position >= Count || _collection[position] == null)
+ if (position < 0 || position >= _maxCount)
{
- return false;
+ throw new PositionOutOfCollectionException(position);
}
_collection.RemoveAt(position);
return true;
+
}
public IEnumerable GetItems()
diff --git a/GasolineTanker/GasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs b/GasolineTanker/GasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs
index c551091..d8ec037 100644
--- a/GasolineTanker/GasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/GasolineTanker/GasolineTanker/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,6 @@
-namespace GasolineTanker.CollectionGenericObjects;
+using GasolineTanker.Exceptions;
+
+namespace GasolineTanker.CollectionGenericObjects;
///
/// Параметризованный набор объектов
@@ -48,9 +50,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects
public T? Get(int position)
{
- if(position < 0 || position >= Count)
+ if (position < 0 || position >= _collection.Length)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
@@ -69,7 +71,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return true;
}
}
- return false;
+ throw new CollectionOverflowException(Count);
}
///
@@ -77,7 +79,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects
///
public bool Insert(T obj, int position)
- {
+ {
+ if (position < 0 || position >= Count)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+
if (_collection[position] == null)
{
_collection[position] = obj;
@@ -103,14 +110,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects
}
}
}
- return false;
+ throw new CollectionOverflowException(Count);
}
public bool Remove(int position)
{
+ if (position < 0 || position >= Count)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
if (_collection[position] == null)
{
- return false;
+ throw new ObjectNotFoundException(position);
}
_collection[position] = null;
return true;
diff --git a/GasolineTanker/GasolineTanker/CollectionGenericObjects/StorageCollection.cs b/GasolineTanker/GasolineTanker/CollectionGenericObjects/StorageCollection.cs
index 9206374..e69f405 100644
--- a/GasolineTanker/GasolineTanker/CollectionGenericObjects/StorageCollection.cs
+++ b/GasolineTanker/GasolineTanker/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
using GasolineTanker.Drawnings;
+using GasolineTanker.Exceptions;
using System.Text;
namespace GasolineTanker.CollectionGenericObjects;
@@ -53,7 +54,7 @@ public class StorageCollection
{
if (_storages.ContainsKey(name) || name == null)
{
- return;
+ throw new Exception("Неверное имя коллекции");
}
if (collectionType == CollectionType.Massive)
{
@@ -98,12 +99,11 @@ public class StorageCollection
/// Сохранение информации по грузовикам в хранилище в файл
///
/// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -146,19 +146,17 @@ public class StorageCollection
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
- return true;
}
///
/// Загрузка информации по грузовикам в хранилище из файла
///
/// Путь и имя файла
- /// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не существует");
}
string bufferTextFromFile = "";
@@ -175,13 +173,12 @@ public class StorageCollection
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
- return false;
+ throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey))
{
- //если нет такой записи, то это не те данные
- return false;
+ throw new Exception("В файле неверные данные");
}
_storages.Clear();
@@ -194,11 +191,8 @@ public class StorageCollection
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
- ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
- if (collection == null)
- {
- return false;
- }
+ ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType) ??
+ throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -207,17 +201,22 @@ public class StorageCollection
{
if (elem?.CreateDrawningTanker() is T tanker)
{
- if (!collection.Insert(tanker))
+ try
{
- return false;
+ if (!collection.Insert(tanker))
+ {
+ throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
-
- return true;
}
///
diff --git a/GasolineTanker/GasolineTanker/Exceptions/CollectionOverflowException.cs b/GasolineTanker/GasolineTanker/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..838beb3
--- /dev/null
+++ b/GasolineTanker/GasolineTanker/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace GasolineTanker.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) { }
+}
\ No newline at end of file
diff --git a/GasolineTanker/GasolineTanker/Exceptions/ObjectNotFoundException.cs b/GasolineTanker/GasolineTanker/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..62995c4
--- /dev/null
+++ b/GasolineTanker/GasolineTanker/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace GasolineTanker.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/GasolineTanker/GasolineTanker/Exceptions/PositionOutOfCollectionException.cs b/GasolineTanker/GasolineTanker/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..edef9eb
--- /dev/null
+++ b/GasolineTanker/GasolineTanker/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace GasolineTanker.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/GasolineTanker/GasolineTanker/FormTankerCollection.cs b/GasolineTanker/GasolineTanker/FormTankerCollection.cs
index f94c0d9..f80c861 100644
--- a/GasolineTanker/GasolineTanker/FormTankerCollection.cs
+++ b/GasolineTanker/GasolineTanker/FormTankerCollection.cs
@@ -1,5 +1,7 @@
using GasolineTanker.CollectionGenericObjects;
using GasolineTanker.Drawnings;
+using GasolineTanker.Entities;
+using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace GasolineTanker;
@@ -19,13 +21,19 @@ public partial class FormTankerCollection : Form
///
private AbstractCompany? _company = null;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormTankerCollection()
+ public FormTankerCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -61,14 +69,19 @@ public partial class FormTankerCollection : Form
return;
}
- if (_company + tanker)
+ try
{
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
+ if (_company + tanker)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Добавлен объект: {tanker}", tanker.GetDataForSave());
+ }
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -90,14 +103,19 @@ public partial class FormTankerCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ if (_company - pos)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Удален объект с индексом: {pos}", pos);
+ }
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -257,13 +275,16 @@ public partial class FormTankerCollection : 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);
}
}
}
@@ -278,13 +299,16 @@ public partial class FormTankerCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
- {
- MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
+ try
{
- MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _storageCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
RerfreshListBoxItems();
diff --git a/GasolineTanker/GasolineTanker/GasolineTanker.csproj b/GasolineTanker/GasolineTanker/GasolineTanker.csproj
index 244387d..8ca229c 100644
--- a/GasolineTanker/GasolineTanker/GasolineTanker.csproj
+++ b/GasolineTanker/GasolineTanker/GasolineTanker.csproj
@@ -8,6 +8,12 @@
enable
+
+
+
+
+
+
True
@@ -23,4 +29,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/GasolineTanker/GasolineTanker/Program.cs b/GasolineTanker/GasolineTanker/Program.cs
index a73ebe1..7afe9da 100644
--- a/GasolineTanker/GasolineTanker/Program.cs
+++ b/GasolineTanker/GasolineTanker/Program.cs
@@ -1,3 +1,7 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+
namespace GasolineTanker
{
internal static class Program
@@ -11,7 +15,25 @@ namespace GasolineTanker
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormTankerCollection());
+
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+
+ ///
+ /// Configuration of DI service
+ ///
+ ///
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddNLog("nlog.config");
+ });
}
}
}
\ No newline at end of file
diff --git a/GasolineTanker/GasolineTanker/nlog.config b/GasolineTanker/GasolineTanker/nlog.config
new file mode 100644
index 0000000..5c71e85
--- /dev/null
+++ b/GasolineTanker/GasolineTanker/nlog.config
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file