diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs
index e0135f9..98999ef 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/AbstractCompany.cs
@@ -37,6 +37,7 @@ public abstract class AbstractCompany
/// Вычисление максимального количества элементов, который можно разместить в окне
///
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+
///
/// Конструктор
///
@@ -95,8 +96,12 @@ 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 (Exception) { }
}
return bitmap;
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs
index ba3b83f..e2c9d4f 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,5 @@
-using System;
+using ProjectDumpTruck.Exceptions;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -48,16 +49,18 @@ public class ListGenericObjects : ICollectionGenericObjects
}
public T? Get(int position)
{
- if (position >= 0 && position < Count && _collection[position] != null)
- return _collection[position];
- return null;
+ if (position < 0 || position >= MaxCount)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ return _collection[position];
}
public int Insert(T obj)
{
- if (_collection.Count > _maxCount)
+ if (_collection.Count >= _maxCount)
{
- return -1;
+ throw new CollectionOverflowException(MaxCount);
}
_collection.Add(obj);
return _collection.Count;
@@ -65,40 +68,24 @@ public class ListGenericObjects : ICollectionGenericObjects
public int Insert(T obj, int position)
{
- if (_collection.Count > _maxCount || position < 0 || position > _maxCount)
+ if (position < 0 || position > _maxCount)
{
- return -1;
+ throw new PositionOutOfCollectionException(position);
}
+ if (_collection.Count >= _maxCount)
+ {
+ throw new CollectionOverflowException(MaxCount);
+ }
+ _collection.Insert(position, obj);
+ return position;
- if (_collection[position] == null)
- {
- _collection.Insert(position, obj);
- return position;
- }
- for (int i = position + 1; i < _maxCount; ++i)
- {
- if (_collection[i] == null)
- {
- _collection.Insert(position, obj);
- return position;
- }
- }
- for (int i = 0; i < position; ++i)
- {
- if (_collection[i] == null)
- {
- _collection.Insert(position, obj);
- return position;
- }
- }
- return -1;
}
public T Remove(int position)
{
if (position < 0 || position > _maxCount)
{
- return null;
+ throw new PositionOutOfCollectionException(position);
}
T temp = _collection[position];
_collection.RemoveAt(position);
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs
index 703321a..27de0ac 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -52,13 +53,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects
}
public T? Get(int position)
{
- if (position >= 0 && position < Count && _collection[position] != null)
- return _collection[position];
- return null;
+ if (position < 0 || position >= MaxCount)
+ {
+ throw new PositionOutOfCollectionException(position);
+ }
+ if (_collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
+ return _collection[position];
}
public int Insert(T obj)
{
- for (int i = 0; i < _collection.Length; ++i)
+
+ for (int i = 0; i < MaxCount; ++i)
{
if (_collection[i] == null)
{
@@ -66,13 +74,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return i;
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
- if (position < 0 || position > Count)
+ if (position < 0 || position >= MaxCount)
{
- return -1;
+ throw new PositionOutOfCollectionException(Count);
}
if (_collection[position] == null)
{
@@ -95,17 +103,21 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return position;
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
- if (position >= 0 && position < Count)
+ if (position < 0 || position >= MaxCount)
{
- T remove = _collection[position];
- _collection[position]= null;
- return remove;
+ throw new PositionOutOfCollectionException(position);
}
- return null;
+ if (_collection[position] == null)
+ {
+ throw new ObjectNotFoundException(position);
+ }
+ T remove = _collection[position];
+ _collection[position]= null;
+ return remove;
}
public IEnumerable GetItems()
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs
index b2802be..0d24ee5 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -103,12 +104,13 @@ 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))
{
@@ -143,27 +145,31 @@ public class StorageCollection
wr.Write(_separatorItems);
}
}
- return true;
}
///
/// Загрузка информации по автомобилям в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не существует");
}
using StreamReader rd = new StreamReader(filename);
UTF8Encoding temp = new(true);
string str = rd.ReadLine();
- if (str == null || !str.StartsWith(_collectionKey))
+
+ if (str == null)
{
- return false;
+ throw new Exception("В файле нет данных");
+ }
+ if (!str.StartsWith(_collectionKey))
+ {
+ throw new Exception("В файле неверные данные");
}
_storages.Clear();
@@ -179,7 +185,7 @@ public class StorageCollection
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new Exception("Не удалось создать коллекции");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@@ -187,15 +193,22 @@ public class StorageCollection
{
if (elem?.CreateDrawningTruck() is T truck)
{
- if (collection.Insert(truck) < 0)
+ try
{
- return false;
+ if (collection.Insert(truck) < 0)
+ {
+ throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
}
+ catch (CollectionOverflowException ex)
+ {
+ throw new Exception("Коллекция переполнена", ex);
+ }
+
}
}
_storages.Add(record[0], collection);
}
- return true;
}
///
diff --git a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/TruckSharingService.cs b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/TruckSharingService.cs
index 1bec61c..b6bbfa7 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/TruckSharingService.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/CollectionGenericObjects/TruckSharingService.cs
@@ -68,13 +68,17 @@ public class TruckSharingService : AbstractCompany
x_pos = start_width;
for (int i = 0; i < maxWidth; i++)
{
- if (_collection.Get(i_collection) != null)
+ try
{
- _collection.Get(i_collection).SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(i_collection).SetPosition(x_pos, y_pos);
- x_pos += _placeSizeWidth + width_between;
- i_collection++;
+ if (_collection.Get(i_collection) != null)
+ {
+ _collection.Get(i_collection).SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection.Get(i_collection).SetPosition(x_pos, y_pos);
+ x_pos += _placeSizeWidth + width_between;
+ i_collection++;
+ }
}
+ catch (Exception) { }
}
y_pos = y_pos + _placeSizeHeight;
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs
index a1e0b0d..ec5a0c7 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/Drawnings/DrawningTruck.cs
@@ -103,8 +103,6 @@ public class DrawningTruck
/// true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах
public bool SetPictureSize(int width, int height)
{
- // TODO проверка, что объект "влезает" в размеры поля
- // если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (_drawningTruckWidth > width || _drawningTruckHeight > height)
{
return false;
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..61caf01
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectDumpTruck.Exceptions;
+///
+/// Класс, описывающий ошибку переполнения коллекции
+///
+[Serializable]
+public 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..b47b782
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectDumpTruck.Exceptions;
+
+public 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..43721d7
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/Exceptions/PositionOutOfCollectionException.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 ProjectDumpTruck.Exceptions;
+
+public 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 58e2634..aabce03 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckCollection.cs
@@ -1,5 +1,7 @@
-using ProjectDumpTruck.CollectionGenericObjects;
+using Microsoft.Extensions.Logging;
+using ProjectDumpTruck.CollectionGenericObjects;
using ProjectDumpTruck.Drawnings;
+using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -24,11 +26,17 @@ public partial class FormTruckCollection : Form
/// Компания
///
private AbstractCompany? _company = null;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
- public FormTruckCollection()
+
+ public FormTruckCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -60,19 +68,27 @@ 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 >= 0)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Объект добавлен");
+ }
}
- if (_company + truck >= 0)
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
- }
- else
+ catch (Exception ex)
{
+
MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning($"Ошибка: {ex.Message}");
}
+
+
}
///
@@ -92,14 +108,17 @@ public partial class FormTruckCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _company.Show();
+ if (_company - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _company.Show();
+ }
}
- else
- {
+ catch (Exception ex) {
MessageBox.Show("Не удалось удалить объект");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -245,13 +264,17 @@ 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);
}
}
}
@@ -260,14 +283,16 @@ 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);
RerfreshListBoxItems();
}
- else
- {
- MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs b/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs
index 8916c15..6fdb933 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/FormTruckConfig.cs
@@ -67,8 +67,8 @@ namespace ProjectDumpTruck
/// Передаем информацию при нажатии на Label
///
///
- ///
- private void LabelObject_MouseDown(object sender, MouseEventArgs e)
+ ///
+ private void LabelObject_MouseDown(object sender, MouseEventArgs elabelSimpleObject)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ??
string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
diff --git a/ProjectDumpTruck/ProjectDumpTruck/Program.cs b/ProjectDumpTruck/ProjectDumpTruck/Program.cs
index 589f4a5..7883613 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/Program.cs
+++ b/ProjectDumpTruck/ProjectDumpTruck/Program.cs
@@ -1,3 +1,12 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+using Serilog;
+
+using Serilog.Extensions.Logging;
+using Serilog.Settings.Configuration;
+
namespace ProjectDumpTruck
{
internal static class Program
@@ -10,8 +19,28 @@ namespace ProjectDumpTruck
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
+ ServiceCollection services = new();
+ ConfigureServices(services);
ApplicationConfiguration.Initialize();
- Application.Run(new FormTruckCollection());
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
}
- }
-}
\ No newline at end of file
+
+ ///
+ /// DI
+ ///
+ ///
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(new LoggerConfiguration()
+ .WriteTo.File("log.txt")
+ .CreateLogger());
+ });
+ }
+ }
+
+}
diff --git a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
index 244387d..1dd3c32 100644
--- a/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
+++ b/ProjectDumpTruck/ProjectDumpTruck/ProjectDumpTruck.csproj
@@ -8,6 +8,17 @@
enable
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +34,10 @@
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/ProjectDumpTruck/ProjectDumpTruck/nlog.config b/ProjectDumpTruck/ProjectDumpTruck/nlog.config
new file mode 100644
index 0000000..55b485e
--- /dev/null
+++ b/ProjectDumpTruck/ProjectDumpTruck/nlog.config
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+