diff --git a/WarPlanes/WarPlanes/AirFighter.csproj b/WarPlanes/WarPlanes/AirFighter.csproj
index 13ee123..16042c7 100644
--- a/WarPlanes/WarPlanes/AirFighter.csproj
+++ b/WarPlanes/WarPlanes/AirFighter.csproj
@@ -23,4 +23,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Always
+
+
+
\ No newline at end of file
diff --git a/WarPlanes/WarPlanes/EntityFighter.cs b/WarPlanes/WarPlanes/EntityFighter.cs
index 0e5b923..2f18ac1 100644
--- a/WarPlanes/WarPlanes/EntityFighter.cs
+++ b/WarPlanes/WarPlanes/EntityFighter.cs
@@ -3,7 +3,7 @@
///
/// Класс-сущность "Истрибитель"
///
- internal class EntityFighter : EntityWarPlane
+ public class EntityFighter : EntityWarPlane
{
///
/// Дополнительный цвет
diff --git a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs
index 13456c0..cecd7a8 100644
--- a/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs
+++ b/WarPlanes/WarPlanes/FormMapWithSetWarPlanes.cs
@@ -1,4 +1,7 @@
-namespace AirFighter
+using Microsoft.Extensions.Logging;
+using System.Windows.Forms;
+
+namespace AirFighter
{
public partial class FormMapWithSetWarPlanes : Form
{
@@ -14,13 +17,18 @@
/// Объект от коллекции карт
///
private readonly MapsCollection _mapsCollection;
+ ///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
///
/// Конструктор
///
- public FormMapWithSetWarPlanes()
+ public FormMapWithSetWarPlanes(ILogger logger)
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
+ _logger = logger;
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
@@ -59,15 +67,18 @@
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.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
+ _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
}
///
/// Выбор карты
@@ -77,6 +88,7 @@
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ _logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
///
/// Удаление карты
@@ -93,6 +105,7 @@
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
+ _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@@ -113,18 +126,28 @@
///
private void AddWarPlane(DrawningWarPlane warplane)
{
- if (listBoxMaps.SelectedIndex == -1)
+ try
{
- MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ if (listBoxMaps.SelectedIndex == -1)
+ {
+ MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ }
+ else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectWarPlane(warplane) != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ _logger.LogInformation("Добавлен объект {@Airplane}", warplane);
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ _logger.LogInformation("Не удалось добавить объект");
+ }
}
- else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectWarPlane(warplane) != -1)
+ catch (StorageOverflowException ex)
{
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
- }
- else
- {
- MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
+ MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
///
@@ -147,15 +170,31 @@
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ var deletedAirplane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
+ if (deletedAirplane != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation("Из текущей карты удален объект {@Airplane}", deletedAirplane);
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (WarPlaneNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
+ catch (Exception ex)
+ {
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
+ }
+
}
///
/// Вывод набора
@@ -219,13 +258,16 @@
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _mapsCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", 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);
+ _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
@@ -234,14 +276,17 @@
{
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);
+ _logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
ReloadMaps();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
}
}
}
diff --git a/WarPlanes/WarPlanes/MapsCollection.cs b/WarPlanes/WarPlanes/MapsCollection.cs
index ba6ea8a..7927455 100644
--- a/WarPlanes/WarPlanes/MapsCollection.cs
+++ b/WarPlanes/WarPlanes/MapsCollection.cs
@@ -68,7 +68,7 @@ namespace AirFighter
///
/// Путь и имя файла
///
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -82,25 +82,24 @@ namespace AirFighter
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
- return true;
}
///
/// Загрузка нформации по самолётам на парковках из файла
///
///
///
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = new(filename))
{
if (!fs.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
@@ -121,7 +120,6 @@ namespace AirFighter
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
- return true;
}
///
/// Доступ к парковке
diff --git a/WarPlanes/WarPlanes/Program.cs b/WarPlanes/WarPlanes/Program.cs
index 70f3587..5ce1d48 100644
--- a/WarPlanes/WarPlanes/Program.cs
+++ b/WarPlanes/WarPlanes/Program.cs
@@ -1,3 +1,8 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+
namespace AirFighter
{
internal static class Program
@@ -11,7 +16,30 @@ namespace AirFighter
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormMapWithSetWarPlanes());
+ 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: "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/WarPlanes/WarPlanes/SetWarPlanesGeneric.cs b/WarPlanes/WarPlanes/SetWarPlanesGeneric.cs
index 1dfd5f2..c76e648 100644
--- a/WarPlanes/WarPlanes/SetWarPlanesGeneric.cs
+++ b/WarPlanes/WarPlanes/SetWarPlanesGeneric.cs
@@ -46,6 +46,8 @@
///
public int Insert(T warplane, int position)
{
+ if (Count == _maxcount)
+ throw new StorageOverflowException(_maxcount);
if (!isCorrectPosition(position))
{
return -1;
@@ -60,8 +62,11 @@
///
public T Remove(int position)
{
- if (!isCorrectPosition(position)) return null;
- var result = _places[position];
+ if (!isCorrectPosition(position))
+ return null;
+ var result = this[position];
+ if (result == null)
+ throw new WarPlaneNotFoundException(position);
_places.RemoveAt(position);
return result;
}
diff --git a/WarPlanes/WarPlanes/StorageOverflowException.cs b/WarPlanes/WarPlanes/StorageOverflowException.cs
new file mode 100644
index 0000000..6a1cd9e
--- /dev/null
+++ b/WarPlanes/WarPlanes/StorageOverflowException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace AirFighter
+{
+ [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) { }
+ }
+}
\ No newline at end of file
diff --git a/WarPlanes/WarPlanes/WarPlaneNotFoundException.cs b/WarPlanes/WarPlanes/WarPlaneNotFoundException.cs
new file mode 100644
index 0000000..a74b50f
--- /dev/null
+++ b/WarPlanes/WarPlanes/WarPlaneNotFoundException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace AirFighter
+{
+ [Serializable]
+ internal class WarPlaneNotFoundException : ApplicationException
+ {
+ public WarPlaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+ public WarPlaneNotFoundException() : base() { }
+ public WarPlaneNotFoundException(string message) : base(message) { }
+ public WarPlaneNotFoundException(string message, Exception exception) : base(message, exception) { }
+ protected WarPlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/WarPlanes/WarPlanes/appsettings.json b/WarPlanes/WarPlanes/appsettings.json
new file mode 100644
index 0000000..3825ce1
--- /dev/null
+++ b/WarPlanes/WarPlanes/appsettings.json
@@ -0,0 +1,16 @@
+{
+ "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}"
+ }
+ }
+ ]
+ }
+}
\ No newline at end of file