diff --git a/ProjectMonorail/CollectionGenericObjects/AbstractCompany.cs b/ProjectMonorail/CollectionGenericObjects/AbstractCompany.cs
index 4533710..739a979 100644
--- a/ProjectMonorail/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectMonorail/CollectionGenericObjects/AbstractCompany.cs
@@ -1,5 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
+using ProjectMonorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -41,7 +42,7 @@ public abstract class AbstractCompany
///
/// Вычисление максимального количества элементов, которые можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => (_pictureHeight / _placeSizeHeight) * (_pictureWidth / _placeSizeWidth);
///
/// Конструктор
@@ -106,8 +107,12 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- DrawingTrain? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawingTrain? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException) { }
}
return bitmap;
}
diff --git a/ProjectMonorail/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMonorail/CollectionGenericObjects/ListGenericObjects.cs
index 5a75b52..2f3e2a4 100644
--- a/ProjectMonorail/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectMonorail/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,9 +1,5 @@
using ProjectMonorail.CollectionGenericObject;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObjects;
@@ -40,28 +36,28 @@ public class ListGenericObjects : ICollectionGenericObjects
public T? Get(int position)
{
- if (position < 0 || position >= Count) { return null; }
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
return _collection[position];
}
public int Insert(T obj)
{
- if (obj == null || Count + 1 > _maxCount) { return -1; }
+ if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
_collection.Add(obj);
return Count + 1;
}
public int Insert(T obj, int position)
{
- if (obj == null || Count + 1 > _maxCount) { return -1; }
- if (position < 0 || position >= Count) { return -1; }
+ if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
_collection.Insert(position, obj);
return Count + 1;
}
public T Remove(int position)
{
- if (position < 0 || position >= Count) { return null; }
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
T tmp = _collection[position];
_collection.RemoveAt(position);
return tmp;
diff --git a/ProjectMonorail/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMonorail/CollectionGenericObjects/MassiveGenericObjects.cs
index ef9f7d4..e5716b6 100644
--- a/ProjectMonorail/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectMonorail/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,9 +1,5 @@
using ProjectMonorail.CollectionGenericObjects;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObject;
@@ -55,11 +51,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects
public T? Get(int position)
{
- if (position >= 0 && position < Count)
- {
- return _collection[position];
- }
- return null;
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
+ if (_collection[position] == null) { throw new ObjectNotFoundException(); }
+ return _collection[position];
}
public int Insert(T obj)
@@ -72,15 +66,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return i;
}
}
- return -1;
+ throw new CollectionOverflowException();
}
public int Insert(T obj, int position)
{
- if (position < 0 || position >= Count)
- {
- return -1;
- }
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
@@ -97,15 +88,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects
return i;
}
}
- return -1;
+ throw new CollectionOverflowException();
}
public T Remove(int position)
{
- if (position < 0 || position >= Count)
- {
- return null;
- }
+ if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
+ if (_collection == null) { throw new ObjectNotFoundException(); }
T tmp = _collection[position];
_collection[position] = null;
return tmp;
diff --git a/ProjectMonorail/CollectionGenericObjects/StorageCollection.cs b/ProjectMonorail/CollectionGenericObjects/StorageCollection.cs
index b5a533c..6442606 100644
--- a/ProjectMonorail/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectMonorail/CollectionGenericObjects/StorageCollection.cs
@@ -1,10 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObjects;
@@ -97,12 +93,11 @@ public class StorageCollection
/// Сохранение информации по поездам в хранилище в файл
///
/// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (_storages.Count == 0)
{
- return false;
+ throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -142,19 +137,17 @@ public class StorageCollection
streamWriter.Write(_separatorItems);
}
}
- return true;
}
///
/// Загрузка информации по автомобилям в хранилище из файла
///
/// Путь и имя файла
- /// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Данный файл не существует");
}
using FileStream fs = new(filename, FileMode.Open);
@@ -162,12 +155,11 @@ public class StorageCollection
string firstString = streamReader.ReadLine();
if (firstString != _collectionKey || firstString.Length == 0)
{
- return false;
+ throw new ArgumentException("В файле нет данных");
}
if (!firstString.Equals(_collectionKey))
{
- //если нет такой записи, то это не те данные
- return false;
+ throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
@@ -182,7 +174,7 @@ public class StorageCollection
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidCastException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -192,18 +184,22 @@ public class StorageCollection
{
if (elem?.CreateDrawingTrain() is T train)
{
- if (collection.Insert(train) == -1)
+ try
{
- return false;
+ if (collection.Insert(train) == -1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
-
-
- return true;
}
///
diff --git a/ProjectMonorail/CollectionGenericObjects/TrainSharingService.cs b/ProjectMonorail/CollectionGenericObjects/TrainSharingService.cs
index 0153a3f..4d3636c 100644
--- a/ProjectMonorail/CollectionGenericObjects/TrainSharingService.cs
+++ b/ProjectMonorail/CollectionGenericObjects/TrainSharingService.cs
@@ -1,5 +1,6 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
+using ProjectMonorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -45,9 +46,14 @@ public class TrainSharingService : AbstractCompany
{
for (int x = 10; x + _placeSizeWidth < _pictureWidth; x += _placeSizeWidth)
{
- _collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
- _collection?.Get(counter)?.SetPosition(x, y);
- counter++;
+ try
+ {
+ _collection?.Get(counter)?.SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection?.Get(counter)?.SetPosition(x, y);
+ counter++;
+ }
+ catch (ObjectNotFoundException) { }
+ catch (PositionOutOfCollectionException) { }
}
}
}
diff --git a/ProjectMonorail/Exceptions/CollectionOverflowException.cs b/ProjectMonorail/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..a54e3e1
--- /dev/null
+++ b/ProjectMonorail/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectMonorail.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 context) : base(info, context) { }
+}
diff --git a/ProjectMonorail/Exceptions/ObjectNotFoundException.cs b/ProjectMonorail/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..8897fba
--- /dev/null
+++ b/ProjectMonorail/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectMonorail.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 context) : base(info, context) { }
+}
diff --git a/ProjectMonorail/Exceptions/PositionOutOfCollectionException.cs b/ProjectMonorail/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..d149c14
--- /dev/null
+++ b/ProjectMonorail/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ProjectMonorail.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 context) : base(info, context) { }
+}
diff --git a/ProjectMonorail/FormTrainCollection.cs b/ProjectMonorail/FormTrainCollection.cs
index d0cbddf..c9c3217 100644
--- a/ProjectMonorail/FormTrainCollection.cs
+++ b/ProjectMonorail/FormTrainCollection.cs
@@ -1,14 +1,7 @@
-using ProjectMonorail.CollectionGenericObject;
+using Microsoft.Extensions.Logging;
using ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using ProjectMonorail.Exceptions;
using System.Windows.Forms;
namespace ProjectMonorail;
@@ -28,13 +21,19 @@ public partial class FormTrainCollection : Form
///
private AbstractCompany? _company = null;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormTrainCollection()
+ public FormTrainCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -70,14 +69,17 @@ public partial class FormTrainCollection : Form
return;
}
- if (_company + train != -1)
+ try
{
+ var set = _company + train;
MessageBox.Show("Объект добавлен");
+ _logger.LogInformation($"Добавлен объект: {train.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
- else
+ catch (CollectionOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ MessageBox.Show("Коллекция переполнена");
+ _logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
}
@@ -90,6 +92,7 @@ public partial class FormTrainCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
+ _logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
@@ -98,15 +101,30 @@ public partial class FormTrainCollection : 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("Объект удален");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Удаление объекта по индексу {pos}", pos);
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ _logger.LogInformation("Не удалось удалить объект из коллекции по индексу {pos}", pos);
+ }
}
- else
+ catch (ObjectNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show("Ошибка: отсутствует объект");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show("Ошибка: неправильная позиция");
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -126,11 +144,17 @@ public partial class FormTrainCollection : Form
int counter = 100;
while (train == null)
{
- train = _company.GetRandomObject();
- counter--;
- if (counter <= 0)
+ try
{
- break;
+ train = _company.GetRandomObject();
+ }
+ catch (ObjectNotFoundException)
+ {
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
}
}
@@ -171,6 +195,7 @@ public partial class FormTrainCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Создание компании без данных");
return;
}
@@ -185,6 +210,7 @@ public partial class FormTrainCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ _logger.LogInformation($"Добавлена коллекция {textBoxCollectionName.Text}");
RefreshListBoxItems();
}
@@ -198,13 +224,16 @@ public partial class FormTrainCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
+ _logger.LogWarning("Удаление компании, не выбрав коллекцию");
return;
}
+ string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
+ _logger.LogInformation($"Удалена коллекция {name}");
RefreshListBoxItems();
}
@@ -234,13 +263,15 @@ public partial class FormTrainCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
+ _logger.LogWarning("Создание компании, не выбрав коллекцию");
return;
}
- ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
+ CollectionGenericObject.ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
+ _logger.LogWarning("Не далось иницализировать коллекцию");
return;
}
@@ -248,6 +279,7 @@ public partial class FormTrainCollection : Form
{
case "Хранилище":
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
+ _logger.LogInformation("Компания создана");
break;
}
@@ -264,13 +296,16 @@ public partial class FormTrainCollection : 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);
}
}
}
@@ -284,14 +319,17 @@ public partial class FormTrainCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RefreshListBoxItems();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось загрузить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
diff --git a/ProjectMonorail/Program.cs b/ProjectMonorail/Program.cs
index 6b0f3bb..4cd087f 100644
--- a/ProjectMonorail/Program.cs
+++ b/ProjectMonorail/Program.cs
@@ -1,4 +1,10 @@
-namespace ProjectMonorail
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using ProjectMonorail;
+using Serilog;
+
+namespace ProjectAirFighter
{
internal static class Program
{
@@ -10,8 +16,30 @@ namespace ProjectMonorail
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
+ ServiceCollection serviceCollection = new();
+ ConfigureService(serviceCollection);
ApplicationConfiguration.Initialize();
- Application.Run(new FormTrainCollection());
+ using ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+
+ private static void ConfigureService(ServiceCollection services)
+ {
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile(path: "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
diff --git a/ProjectMonorail/ProjectMonorail.csproj b/ProjectMonorail/ProjectMonorail.csproj
index b57c89e..ac4a608 100644
--- a/ProjectMonorail/ProjectMonorail.csproj
+++ b/ProjectMonorail/ProjectMonorail.csproj
@@ -8,4 +8,17 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ProjectMonorail/appSettings.json b/ProjectMonorail/appSettings.json
new file mode 100644
index 0000000..3c8bacf
--- /dev/null
+++ b/ProjectMonorail/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": "ProjectMonorail"
+ }
+ }
+}
\ No newline at end of file