diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/AbstractCompany.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/AbstractCompany.cs
index 167cb08..7de004a 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/AbstractCompany.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/AbstractCompany.cs
@@ -1,4 +1,5 @@
using ProjectAirplaneWithRadar.Drawnings;
+using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@@ -35,7 +36,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
///
/// Вычисление максимального количества элементов, который можно разместить в окне
///
- private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
+ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight);
///
/// Конструктор
@@ -80,7 +81,14 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public DrawningAirplane? GetRandomObject()
{
Random rnd = new();
- return _collection?.Get(rnd.Next(GetMaxCount));
+ try
+ {
+ return _collection?.Get(rnd.Next(GetMaxCount));
+ }
+ catch (ObjectNotFoundException)
+ {
+ return null;
+ }
}
///
@@ -96,8 +104,15 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
- DrawningAirplane? obj = _collection?.Get(i);
- obj?.DrawTransport(graphics);
+ try
+ {
+ DrawningAirplane? obj = _collection?.Get(i);
+ obj?.DrawTransport(graphics);
+ }
+ catch (ObjectNotFoundException)
+ {
+ continue;
+ }
}
return bitmap;
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/ListGenericObjects.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/ListGenericObjects.cs
index 8463540..1e335d1 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/ListGenericObjects.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/ListGenericObjects.cs
@@ -1,4 +1,6 @@
+using ProjectAirplaneWithRadar.Exceptions;
+
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
///
@@ -48,33 +50,33 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public T? Get(int position)
{
if (position >= Count || position < 0)
- return null;
+ throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
- if (Count + 1 > _maxCount)
- return -1;
+ if (Count == _maxCount)
+ throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
- if (Count + 1 > _maxCount)
- return -1;
+ if (Count == _maxCount)
+ throw new CollectionOverflowException(Count);
if (position < 0 || position > Count)
- return -1;
+ throw new PositionOutOfCollectionException(position); ;
_collection.Insert(position, obj);
- return 1;
+ return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count)
- return null;
+ throw new PositionOutOfCollectionException(position);
T? temp = _collection[position];
_collection.RemoveAt(position);
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/MassiveGenericObjects.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/MassiveGenericObjects.cs
index 0f4dfab..859797c 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/MassiveGenericObjects.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/MassiveGenericObjects.cs
@@ -1,4 +1,6 @@
+using ProjectAirplaneWithRadar.Exceptions;
+
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
///
@@ -50,8 +52,10 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
public T? Get(int position)
{
- if (position < 0 || position >= Count)
- return null;
+ if (position < 0 || position >= Count)
+ throw new PositionOutOfCollectionException(position);
+ if (_collection[position] == null)
+ throw new ObjectNotFoundException(position);
return _collection[position];
}
@@ -65,13 +69,13 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return i;
}
}
- return -1;
+ throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
- if (position < 0 || position >= Count)
- return -1;
+ if (position >= Count || position < 0)
+ throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@@ -101,18 +105,16 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
temp--;
}
- 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;
- }
+ throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/PlaneSharingService.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/PlaneSharingService.cs
index 86437bd..0ad8986 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/PlaneSharingService.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/PlaneSharingService.cs
@@ -1,4 +1,5 @@
using ProjectAirplaneWithRadar.Drawnings;
+using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@@ -33,22 +34,29 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
- if (_collection.Get(i) != null)
+ try
{
- _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
- _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
- }
+ if (_collection.Get(i) != null)
+ {
+ _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
+ _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
+ }
- if (curWidth > 0)
- curWidth--;
- else
- {
- curWidth = width - 1;
- curHeight++;
+ if (curWidth > 0)
+ curWidth--;
+ else
+ {
+ curWidth = width - 1;
+ curHeight++;
+ }
+ if (curHeight > height)
+ {
+ return;
+ }
}
- if (curHeight > height)
+ catch (ObjectNotFoundException)
{
- return;
+ break;
}
}
}
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/StorageCollection.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/StorageCollection.cs
index 81db8f9..86acf32 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/StorageCollection.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/CollectionGenericObjects/StorageCollection.cs
@@ -1,6 +1,8 @@
-using System.IO;
+using System.Data;
+using System.IO;
using System.Text;
using ProjectAirplaneWithRadar.Drawnings;
+using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
@@ -98,45 +100,46 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
///
/// Путь и имя файла
/// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if(_storages.Count == 0)
- return false;
+ throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
- if(File.Exists(filename))
- File.Delete(filename);
+ if (File.Exists(filename))
+ File.Delete(filename);
- using FileStream fs = new(filename, FileMode.Create);
- using StreamWriter sw = new StreamWriter(fs);
- sw.Write(_collectionKey);
- foreach (KeyValuePair> value in _storages)
+
+ using (StreamWriter sw = new(filename))
{
- sw.Write(Environment.NewLine);
- if (value.Value.Count == 0)
+ sw.Write(_collectionKey);
+ foreach (KeyValuePair> value in _storages)
{
- continue;
- }
-
- sw.Write(value.Key);
- sw.Write(_separatorForKeyValue);
- sw.Write(value.Value.GetCollectionType);
- sw.Write(_separatorForKeyValue);
- sw.Write(value.Value.MaxCount);
- sw.Write(_separatorForKeyValue);
-
- foreach (T? item in value.Value.GetItems())
- {
- string data = item?.GetDataForSave() ?? string.Empty;
- if (string.IsNullOrEmpty(data))
+ sw.Write(Environment.NewLine);
+ if (value.Value.Count == 0)
{
continue;
}
- sw.Write(data);
- sw.Write(_separatorItems);
+ sw.Write(value.Key);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.GetCollectionType);
+ sw.Write(_separatorForKeyValue);
+ sw.Write(value.Value.MaxCount);
+ sw.Write(_separatorForKeyValue);
+
+ foreach (T? item in value.Value.GetItems())
+ {
+ string data = item?.GetDataForSave() ?? string.Empty;
+ if (string.IsNullOrEmpty(data))
+ {
+ continue;
+ }
+
+ sw.Write(data);
+ sw.Write(_separatorItems);
+ }
}
}
- return true;
}
///
@@ -144,26 +147,24 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
///
/// Путь и имя файла
/// 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))
+ using (StreamReader sr = new(filename))
{
- using StreamReader sr = new StreamReader(fs);
-
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
- return false;
+ throw new FileFormatException("В файле нет данных");
}
if (!str.Equals(_collectionKey))
{
- return false;
+ throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
@@ -179,7 +180,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);
if (collection == null)
{
- return false;
+ throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@@ -189,14 +190,20 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
if (elem?.CreateDrawningAirplane() is T airplane)
{
- if (collection.Insert(airplane) == -1)
- return false;
+ try
+ {
+ if (collection.Insert(airplane) == -1)
+ throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
+ }
+ catch (CollectionOverflowException ex)
+ {
+ throw new OverflowException("Коллекция переполнена", ex);
+ }
}
}
_storages.Add(record[0], collection);
}
}
- return true;
}
///
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/CollectionOverflowException.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/CollectionOverflowException.cs
new file mode 100644
index 0000000..f3d47c0
--- /dev/null
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/CollectionOverflowException.cs
@@ -0,0 +1,21 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirplaneWithRadar.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/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/ObjectNotFoundException.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/ObjectNotFoundException.cs
new file mode 100644
index 0000000..08e76a3
--- /dev/null
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/ObjectNotFoundException.cs
@@ -0,0 +1,21 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirplaneWithRadar.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/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/PositionOutOfCollectionException.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..dbb4f60
--- /dev/null
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/Exceptions/PositionOutOfCollectionException.cs
@@ -0,0 +1,21 @@
+using System.Runtime.Serialization;
+
+namespace ProjectAirplaneWithRadar.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/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.Designer.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.Designer.cs
index 79d7649..0f8f332 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.Designer.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.Designer.cs
@@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
- groupBoxTools.Location = new Point(883, 24);
+ groupBoxTools.Location = new Point(445, 24);
groupBoxTools.Name = "groupBoxTools";
- groupBoxTools.Size = new Size(206, 583);
+ groupBoxTools.Size = new Size(206, 523);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@@ -82,7 +82,7 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
- panelCompanyTools.Location = new Point(3, 393);
+ panelCompanyTools.Location = new Point(3, 333);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 187);
panelCompanyTools.TabIndex = 8;
@@ -249,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
- pictureBox.Size = new Size(883, 583);
+ pictureBox.Size = new Size(445, 523);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@@ -258,7 +258,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
- menuStrip.Size = new Size(1089, 24);
+ menuStrip.Size = new Size(651, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
@@ -297,7 +297,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
- ClientSize = new Size(1089, 607);
+ ClientSize = new Size(651, 547);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.cs
index 6074f1f..f91062e 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/FormAirplaneCollection.cs
@@ -1,5 +1,7 @@
-using ProjectAirplaneWithRadar.CollectionGenericObjects;
+using Microsoft.Extensions.Logging;
+using ProjectAirplaneWithRadar.CollectionGenericObjects;
using ProjectAirplaneWithRadar.Drawnings;
+using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar
{
@@ -18,13 +20,20 @@ namespace ProjectAirplaneWithRadar
///
private AbstractCompany? _company = null;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+
///
/// Конструктор
///
- public FormAirplaneCollection()
+ public FormAirplaneCollection(ILogger logger)
{
InitializeComponent();
_storageCollection = new();
+ _logger = logger;
+ _logger.LogInformation("Форма загрузилась");
}
///
@@ -55,20 +64,25 @@ namespace ProjectAirplaneWithRadar
///
private void SetAirplane(DrawningAirplane airplane)
{
- if (_company == null || airplane == null)
+ try
{
- return;
- }
+ if (_company == null || airplane == null)
+ {
+ return;
+ }
- if (_company + airplane != -1)
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _company.Show();
+ if (_company + airplane != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _company.Show();
+ _logger.LogInformation("Добавлен объект: {0}", airplane.GetDataForSave());
+ }
}
- else
+ catch (CollectionOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
- }
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
}
///
@@ -88,15 +102,25 @@ namespace ProjectAirplaneWithRadar
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("Удалён объект по позиции {0}", pos);
+ }
}
- else
+ catch (PositionOutOfCollectionException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ catch (ObjectNotFoundException ex)
+ {
+ MessageBox.Show(ex.Message);
+ _logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -112,28 +136,35 @@ namespace ProjectAirplaneWithRadar
return;
}
- DrawningAirplane? plane = null;
- int counter = 100;
- while (plane == null)
+ try
{
- plane = _company.GetRandomObject();
- counter--;
- if (counter <= 0)
+ DrawningAirplane? plane = null;
+ int counter = 100;
+ while (plane == null)
{
- break;
+ plane = _company.GetRandomObject();
+ counter--;
+ if (counter <= 0)
+ {
+ break;
+ }
}
- }
- if (plane == null)
- {
- return;
- }
+ if (plane == null)
+ {
+ return;
+ }
- FormAirplaneWithRadar form = new()
+ FormAirplaneWithRadar form = new()
+ {
+ SetAirplane = plane
+ };
+ form.ShowDialog();
+ }
+ catch (ObjectNotFoundException)
{
- SetAirplane = plane
- };
- form.ShowDialog();
+ _logger.LogError("Ошибка при передаче объекта на FormAirplaneWithRadar");
+ }
}
///
@@ -161,6 +192,7 @@ namespace ProjectAirplaneWithRadar
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@@ -172,6 +204,7 @@ namespace ProjectAirplaneWithRadar
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
+ _logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
}
///
@@ -193,6 +226,7 @@ namespace ProjectAirplaneWithRadar
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
+ _logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text);
}
///
@@ -233,6 +267,8 @@ namespace ProjectAirplaneWithRadar
{
case "Хранилище":
_company = new PlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
+ _logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text);
+ _logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text);
break;
}
@@ -249,13 +285,16 @@ namespace ProjectAirplaneWithRadar
{
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);
}
}
}
@@ -269,14 +308,17 @@ namespace ProjectAirplaneWithRadar
{
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}", 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);
}
}
}
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/Program.cs b/AirplaneWithRadar/ProjectAirplaneWithRadar/Program.cs
index 42c6dca..e1fe689 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/Program.cs
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+
namespace ProjectAirplaneWithRadar
{
internal static class Program
@@ -11,7 +16,27 @@ namespace ProjectAirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormAirplaneCollection());
+ ServiceCollection services = new();
+ ConfigureService(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ private static void ConfigureService(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/AirplaneWithRadar/ProjectAirplaneWithRadar/ProjectAirplaneWithRadar.csproj b/AirplaneWithRadar/ProjectAirplaneWithRadar/ProjectAirplaneWithRadar.csproj
index af03d74..0a3f429 100644
--- a/AirplaneWithRadar/ProjectAirplaneWithRadar/ProjectAirplaneWithRadar.csproj
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/ProjectAirplaneWithRadar.csproj
@@ -8,6 +8,18 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +35,10 @@
+
+
+ PreserveNewest
+
+
+
\ No newline at end of file
diff --git a/AirplaneWithRadar/ProjectAirplaneWithRadar/serilogConfig.json b/AirplaneWithRadar/ProjectAirplaneWithRadar/serilogConfig.json
new file mode 100644
index 0000000..abba1ee
--- /dev/null
+++ b/AirplaneWithRadar/ProjectAirplaneWithRadar/serilogConfig.json
@@ -0,0 +1,24 @@
+{
+ "AllowedHosts": "*",
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": {
+ "Default": "Information",
+ "Override": {
+ "Microsoft": "Warning",
+ "System": "Warning"
+ }
+ },
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "Logs\\log.txt",
+ "rollingInterval": "Day",
+ "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}|{Level:u}|{SourceContext}|{Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ]
+ }
+}