diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs
new file mode 100644
index 0000000..3e24f0f
--- /dev/null
+++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Runtime.Serialization;
+
+namespace AirplaneWithRadar.Exceptoins
+{
+ [Serializable]
+ internal class AirplaneNotFoundException : ApplicationException
+ {
+ public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+ public AirplaneNotFoundException() : base() { }
+ public AirplaneNotFoundException(string message) : base(message) { }
+ public AirplaneNotFoundException(string message, Exception exception) :
+ base(message, exception) { }
+ protected AirplaneNotFoundException(SerializationInfo info,
+ StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs
index 1f5ae6d..d061c7e 100644
--- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs
+++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs
@@ -96,7 +96,7 @@ namespace AirplaneWithRadar.Generics
///
/// Путь и имя файла
/// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -115,24 +115,25 @@ namespace AirplaneWithRadar.Generics
}
if (data.Length == 0)
{
- return false;
+ throw new Exception("Невалиданя операция, нет данных для сохранения");
+
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
- return true;
+ return;
}
///
/// Загрузка информации по самолетам в хранилище из файла
///
/// Путь и имя файла
/// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@@ -148,12 +149,13 @@ namespace AirplaneWithRadar.Generics
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
- return false;
+ throw new Exception("Нет данных для загрузки");
+
}
if (!strs[0].StartsWith("AirplaneStorage"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new Exception("Неверный формат данных");
}
_airplaneStorages.Clear();
foreach (string data in strs)
@@ -176,13 +178,13 @@ namespace AirplaneWithRadar.Generics
{
if (!(collection + airplane))
{
- return false;
+ throw new Exception("Ошибка добавления в коллекцию");
+
}
}
}
_airplaneStorages.Add(record[0], collection);
}
- return true;
}
}
}
diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs
index 40db2ed..1bc0988 100644
--- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs
+++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs
@@ -1,15 +1,18 @@
-using System;
+/*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 System.Threading.Tasks;*/
using System.Windows.Forms;
+//using AirplaneWithRadar.MovementStrategy;
using AirplaneWithRadar.DrawningObjects;
using AirplaneWithRadar.Generics;
-using AirplaneWithRadar.MovementStrategy;
+using AirplaneWithRadar.Exceptoins;
+using Microsoft.Extensions.Logging;
+//using NLog.Extensions.Logging;
namespace AirplaneWithRadar
{
@@ -23,12 +26,17 @@ namespace AirplaneWithRadar
///
private readonly AirplanesGenericStorage _storage;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormAirplaneCollection()
+ public FormAirplaneCollection(ILogger logger)
{
InitializeComponent();
_storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
+ _logger = logger;
}
///
/// Обработка нажатия "Сохранение"
@@ -39,15 +47,16 @@ namespace AirplaneWithRadar
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.SaveData(saveFileDialog.FileName))
+ try
{
+ _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не сохранилось: {ex.Message}",
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -60,18 +69,18 @@ namespace AirplaneWithRadar
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_storage.LoadData(openFileDialog.FileName))
+ try
{
+ _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
- "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат",
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
- ReloadObjects();
}
///
@@ -111,6 +120,7 @@ namespace AirplaneWithRadar
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
+ _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
///
/// Выбор набора
@@ -121,7 +131,6 @@ namespace AirplaneWithRadar
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowAirplanes();
-
}
///
/// Удаление набора
@@ -134,12 +143,13 @@ namespace AirplaneWithRadar
{
return;
}
- if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?",
- "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
+ string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
+ if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
+ MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
- _storage.DelSet(listBoxStorages.SelectedItem.ToString()
- ?? string.Empty);
+ _storage.DelSet(name);
ReloadObjects();
+ _logger.LogInformation($"Удален набор: {name}");
}
}
///
@@ -202,15 +212,23 @@ namespace AirplaneWithRadar
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
- if (obj - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBoxCollection.Image = obj.ShowAirplanes();
+ if (obj - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ pictureBoxCollection.Image = obj.ShowAirplanes();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (AirplaneNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ MessageBox.Show(ex.Message);
}
+
}
///
/// Обновление рисунка по набору
diff --git a/AirplaneWithRadar/AirplaneWithRadar/Program.cs b/AirplaneWithRadar/AirplaneWithRadar/Program.cs
index ec2131f..6d0e5fb 100644
--- a/AirplaneWithRadar/AirplaneWithRadar/Program.cs
+++ b/AirplaneWithRadar/AirplaneWithRadar/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using NLog.Extensions.Logging;
+using System;
+
namespace AirplaneWithRadar
{
internal static class Program
@@ -11,7 +16,21 @@ namespace AirplaneWithRadar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormAirplaneCollection());
+ 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 =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddNLog("nlog.config");
+ });
}
}
}
\ No newline at end of file
diff --git a/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs b/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs
new file mode 100644
index 0000000..2baf541
--- /dev/null
+++ b/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Runtime.Serialization;
+
+
+namespace AirplaneWithRadar.Exceptoins
+{
+ [Serializable]
+ internal class StorageOverflowException : ApplicationException
+ {
+ public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
+ public StorageOverflowException() : base() { }
+ public StorageOverflowException(string message) : base(message) { }
+ public StorageOverflowException(string message, Exception exception)
+ : base(message, exception) { }
+ protected StorageOverflowException(SerializationInfo info,
+ StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/AirplaneWithRadar/AirplaneWithRadar/nlog.config b/AirplaneWithRadar/AirplaneWithRadar/nlog.config
new file mode 100644
index 0000000..9d784f9
--- /dev/null
+++ b/AirplaneWithRadar/AirplaneWithRadar/nlog.config
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+