diff --git a/AirBomber/AirBomber/AirBomber.csproj b/AirBomber/AirBomber/AirBomber.csproj
index 13ee123..fdb06ac 100644
--- a/AirBomber/AirBomber/AirBomber.csproj
+++ b/AirBomber/AirBomber/AirBomber.csproj
@@ -8,6 +8,36 @@
enable
+
+
+
+
+
+
+ Always
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
True
diff --git a/AirBomber/AirBomber/FormMapWithSetJets.cs b/AirBomber/AirBomber/FormMapWithSetJets.cs
index 51322a9..ec347c4 100644
--- a/AirBomber/AirBomber/FormMapWithSetJets.cs
+++ b/AirBomber/AirBomber/FormMapWithSetJets.cs
@@ -1,4 +1,5 @@
-using System;
+using Microsoft.Extensions.Logging;
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -25,19 +26,18 @@ namespace AirBomber
/// Объект от коллекции карт
///
private readonly MapsCollection _mapsCollection;
-
+ private readonly ILogger _logger;
///
/// Объект от класса карты с набором объектов
///
private MapWithSetJetsGeneric _mapJetsCollectionGeneric;
-
-
///
/// Конструктор
///
- public FormMapWithSetJets()
+ public FormMapWithSetJets(ILogger logger)
{
InitializeComponent();
+ _logger = logger;
_mapsCollection = new MapsCollection(pictureBoxJet.Width, pictureBoxJet.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -75,15 +75,18 @@ namespace AirBomber
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
+ _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
///
/// Выбор карты
@@ -93,6 +96,7 @@ namespace AirBomber
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ _logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
///
/// Удаление карты
@@ -109,6 +113,7 @@ namespace AirBomber
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
+ _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
///
@@ -116,34 +121,37 @@ namespace AirBomber
///
///
///
- private void ButtonAddJet_Click(object sender, EventArgs e)
+ private void ButtonAddJet_Click(DrawningJet jet)
{
- if (listBoxMaps.SelectedIndex == -1)
+ try
{
- return;
- }
- var formJetConfig = new FormJetConfig();
- // использование лямбда функции для добавления самолета подписываемся на событие EventAddJet
- // указываем лямбда функцию - будет добавлять новый самолет, который передала форма добавления
- formJetConfig.EventAddJet += (DrawningJet djet) =>
- {
- if (djet == null)
+ if (listBoxMaps.SelectedIndex == -1)
{
- MessageBox.Show("Сначала создайте объект");
return;
}
- DrawningObjectJet jet = new(djet);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + jet != -1)
+ DrawningObjectJet boat = new(jet);
+ if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
{
MessageBox.Show("Объект добавлен");
+ _logger.LogInformation("Объект добавлен");
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
+ _logger.LogInformation("Не удалось добавить объект");
}
- };
- formJetConfig.Show();
+ }
+ catch (StorageOverflowException ex)
+ {
+ _logger.LogWarning($"Ошибка, переполнение хранилища: {0}", ex.Message);
+ MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ catch (ArgumentException ex)
+ {
+ _logger.LogWarning("Ошибка добавления");
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
}
///
/// Удаление объекта
@@ -167,14 +175,25 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ var deletedJet = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
+ if (deletedJet != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation("Из текущей карты удален объект {@ship}", deletedJet);
+ pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
}
///
@@ -239,13 +258,16 @@ namespace AirBomber
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _mapsCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.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);
+ _logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
@@ -254,14 +276,17 @@ namespace AirBomber
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _mapsCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Загрузка данных прошла успешно", "Результат",
+ MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
diff --git a/AirBomber/AirBomber/JetNotFoundException.cs b/AirBomber/AirBomber/JetNotFoundException.cs
new file mode 100644
index 0000000..1126c93
--- /dev/null
+++ b/AirBomber/AirBomber/JetNotFoundException.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace AirBomber
+{
+ internal class JetNotFoundException : ApplicationException
+ {
+ public JetNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+
+ public JetNotFoundException() : base() { }
+
+ public JetNotFoundException(string message) : base(message) { }
+
+ public JetNotFoundException(string message, Exception exception) : base(message, exception) { }
+
+ protected JetNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs
index d34c6f9..89326cc 100644
--- a/AirBomber/AirBomber/MapsCollection.cs
+++ b/AirBomber/AirBomber/MapsCollection.cs
@@ -129,7 +129,7 @@ namespace AirBomber
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -137,7 +137,7 @@ namespace AirBomber
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Формат данных в файле неправильный");
}
//очищаем записи
_mapStorages.Clear();
diff --git a/AirBomber/AirBomber/Program.cs b/AirBomber/AirBomber/Program.cs
index 19f609b..fdb72f0 100644
--- a/AirBomber/AirBomber/Program.cs
+++ b/AirBomber/AirBomber/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+
namespace AirBomber
{
internal static class Program
@@ -11,7 +16,27 @@ namespace AirBomber
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormMapWithSetJets());
+ 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 =>
+ {
+ var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: "serilog.json").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/AirBomber/AirBomber/SetJetGeneric.cs b/AirBomber/AirBomber/SetJetGeneric.cs
index a3edbba..2169c31 100644
--- a/AirBomber/AirBomber/SetJetGeneric.cs
+++ b/AirBomber/AirBomber/SetJetGeneric.cs
@@ -47,10 +47,15 @@ namespace AirBomber
{
return -1;
}
+ if (_places.Contains(jet))
+ {
+ throw new ArgumentException($"Объект {jet} уже есть в наборе");
+ }
+ if (Count == _maxCount)
+ {
+ throw new StorageOverflowException(_maxCount);
+ }
_places.Insert(position, jet);
-
- _places.Remove(null);
-
return position;
}
///
@@ -61,13 +66,9 @@ namespace AirBomber
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
-
- T savedJet = _places[position];
-
- _places[position] = null;
-
-
- return savedJet;
+ var result = _places[position];
+ _places.RemoveAt(position);
+ return result;
}
///
diff --git a/AirBomber/AirBomber/StorageOverflowException.cs b/AirBomber/AirBomber/StorageOverflowException.cs
new file mode 100644
index 0000000..04b4782
--- /dev/null
+++ b/AirBomber/AirBomber/StorageOverflowException.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace AirBomber
+{
+ 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/AirBomber/AirBomber/nlog.config b/AirBomber/AirBomber/nlog.config
new file mode 100644
index 0000000..8023ecf
--- /dev/null
+++ b/AirBomber/AirBomber/nlog.config
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file