diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs
index e0d11d0..88c0438 100644
--- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs
+++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AbstractCompany.cs
@@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
+using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -96,8 +97,13 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawningAirCraft? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawningAirCraft? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException e){}
+ catch (PositionOutOfCollectionException e){}
}
return bitmap;
diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AirCraftAngar.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AirCraftAngar.cs
index d29a594..3cbac34 100644
--- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AirCraftAngar.cs
+++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/AirCraftAngar.cs
@@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
+using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -49,13 +50,17 @@ public class AirCraftAngar : AbstractCompany
{
for (int i = pamat_i; i >= 0; i--)
{
- if (_collection?.Get(currentIndex) != null)
+ try
{
- _collection.Get(currentIndex)?.SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(currentIndex)?.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
-
- currentIndex++;
+ if (_collection?.Get(currentIndex) != null)
+ {
+ _collection.Get(currentIndex)?.SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection.Get(currentIndex)?.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
+ }
}
+ catch (ObjectNotFoundException e){}
+ catch (PositionOutOfCollectionException e){}
+ currentIndex++;
}
}
}
diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs
index 3d3ddc1..b7fc4d7 100644
--- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs
+++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,6 @@
+using ProjectAirFighter.Exceptions;
+
namespace ProjectAirFighter.CollectionGenericObjects;
///
/// Параметризованный набор объектов
@@ -42,25 +44,26 @@ public class ListGenericObjects : ICollectionGenericObjects
}
public T? Get(int position)
{
- if (position >= Count || position < 0) return null;
+ if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
{
- if (Count + 1 > _maxCount) return -1;
+ if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
- if (Count + 1 > _maxCount) return -1;
- if (position < 0 || position > Count) return -1;
+ if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
+ if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
- return 1;
+ return position;
}
public T? Remove(int position)
{
- if (position < 0 || position > Count) return null;
+ if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
return temp;
@@ -73,5 +76,4 @@ public class ListGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
-}
-
+}
\ No newline at end of file
diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs
index bb050b3..849f17b 100644
--- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,6 @@
+using ProjectAirFighter.Exceptions;
+
namespace ProjectAirFighter.CollectionGenericObjects;
///
@@ -50,12 +52,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(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
+ return _collection[position];
}
public int Insert(T obj)
@@ -68,7 +67,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
if (position < 0 || position >= Count)
{
- return -1;
+ throw new PositionOutOfCollectionException();
}
if (_collection[position] != null)
@@ -99,7 +98,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects
if (!pushed)
{
- return position;
+ throw new CollectionOverflowException(Count);
}
}
@@ -109,13 +108,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects
public T? Remove(int position)
{
- if (position < 0 || position >= Count)
- {
- return null;
- }
-
- if (_collection[position] == null) return null;
-
+ if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
@@ -128,4 +122,4 @@ public class MassiveGenericObjects : ICollectionGenericObjects
yield return _collection[i];
}
}
-}
+}
\ No newline at end of file
diff --git a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs
index 28c8d46..d8dbd29 100644
--- a/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs
+++ b/ProjectAirFighter/ProjectAirFighter/CollectionGenericObjects/StorageCollection.cs
@@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
+using ProjectAirFighter.Exceptions;
using System.Text;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -88,12 +89,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))
@@ -135,19 +135,17 @@ public class StorageCollection
}
}
- 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 fs = File.OpenText(filename))
@@ -155,11 +153,11 @@ public class StorageCollection
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
- return false;
+ throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
- return false;
+ throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
@@ -174,7 +172,7 @@ public class StorageCollection
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@@ -182,15 +180,21 @@ public class StorageCollection
{
if (elem?.CreateDrawningAirCraft() is T aircraft)
{
- if (collection.Insert(aircraft) == -1)
+ try
{
- return false;
+ if (collection.Insert(aircraft) == -1)
+ {
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
- return true;
}
}
diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..c8f38f7
--- /dev/null
+++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirFighter.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/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..eba0aae
--- /dev/null
+++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirFighter.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) { }
+}
\ No newline at end of file
diff --git a/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..13db41a
--- /dev/null
+++ b/ProjectAirFighter/ProjectAirFighter/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,20 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirFighter.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) { }
+}
\ No newline at end of file
diff --git a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs
index 49ed162..6b764da 100644
--- a/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs
+++ b/ProjectAirFighter/ProjectAirFighter/FormAirCraftCollection.cs
@@ -1,5 +1,8 @@
-using ProjectAirFighter.CollectionGenericObjects;
+using Microsoft.Extensions.Logging;
+using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
+using ProjectAirFighter.Exceptions;
+using System.Xml.Linq;
namespace ProjectAirFighter;
@@ -18,13 +21,19 @@ public partial class FormAirCraftCollection : Form
///
private AbstractCompany? _company = null;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormAirCraftCollection()
+ public FormAirCraftCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
}
///
@@ -59,15 +68,17 @@ public partial class FormAirCraftCollection : Form
{
return;
}
-
- if (_company + aircraft != -1)
+ try
{
+ int addingObject = (_company + aircraft);
MessageBox.Show("Объект добавлен");
+ _logger.LogInformation($"Добавлен объект {aircraft.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
- else
+ catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
}
@@ -80,6 +91,7 @@ public partial class FormAirCraftCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
+ _logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
@@ -89,14 +101,22 @@ public partial class FormAirCraftCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_company - pos != null)
+ try
{
+ object decrementObject = _company - pos;
MessageBox.Show("Объект удален");
+ _logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show();
}
- else
+ catch (ObjectNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show("Объект не найден");
+ _logger.LogWarning($"Удаление не найденного объекта в позиции {pos} ");
+ }
+ catch (PositionOutOfCollectionException ex)
+ {
+ MessageBox.Show("Удаление вне рамках коллекции");
+ _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
}
}
@@ -161,6 +181,7 @@ public partial class FormAirCraftCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не заполненная коллекция");
return;
}
@@ -175,6 +196,7 @@ public partial class FormAirCraftCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
+ _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems();
}
@@ -188,14 +210,16 @@ public partial class FormAirCraftCollection : 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}");
RerfreshListBoxItems();
}
@@ -224,6 +248,7 @@ public partial class FormAirCraftCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
+ _logger.LogWarning("Создание компании невыбранной коллекции");
return;
}
@@ -231,6 +256,7 @@ public partial class FormAirCraftCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
+ _logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
@@ -254,13 +280,16 @@ public partial class FormAirCraftCollection : 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);
}
}
}
@@ -274,17 +303,18 @@ public partial class FormAirCraftCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _storageCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
-}
+}
\ No newline at end of file
diff --git a/ProjectAirFighter/ProjectAirFighter/Program.cs b/ProjectAirFighter/ProjectAirFighter/Program.cs
index 7addb2e..334caf4 100644
--- a/ProjectAirFighter/ProjectAirFighter/Program.cs
+++ b/ProjectAirFighter/ProjectAirFighter/Program.cs
@@ -1,17 +1,44 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+
namespace ProjectAirFighter
{
internal static class Program
{
- ///
- /// The main entry point for the application.
- ///
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormAirCraftCollection());
+ 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}serilogConfig.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/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj
index 244387d..d5a50d2 100644
--- a/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj
+++ b/ProjectAirFighter/ProjectAirFighter/ProjectAirFighter.csproj
@@ -8,6 +8,16 @@
enable
+
+
+
+
+
+
+
+
+
+
True
diff --git a/ProjectAirFighter/ProjectAirFighter/serilogConfig.json b/ProjectAirFighter/ProjectAirFighter/serilogConfig.json
new file mode 100644
index 0000000..2fa3b4e
--- /dev/null
+++ b/ProjectAirFighter/ProjectAirFighter/serilogConfig.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": "AirFighter"
+ }
+ }
+}
\ No newline at end of file