diff --git a/AirBomber/AirBomber/AirBomber.csproj b/AirBomber/AirBomber/AirBomber.csproj
index b57c89e..689a0f8 100644
--- a/AirBomber/AirBomber/AirBomber.csproj
+++ b/AirBomber/AirBomber/AirBomber.csproj
@@ -8,4 +8,27 @@
enable
+
+
+
+
+
+
+ Always
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/AirBomber/AirBomber/AirplaneNotFoundException.cs b/AirBomber/AirBomber/AirplaneNotFoundException.cs
new file mode 100644
index 0000000..727b520
--- /dev/null
+++ b/AirBomber/AirBomber/AirplaneNotFoundException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace AirBomber
+{
+ [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/AirBomber/AirBomber/EntityAirBomber.cs b/AirBomber/AirBomber/EntityAirBomber.cs
index 727d7ff..371238d 100644
--- a/AirBomber/AirBomber/EntityAirBomber.cs
+++ b/AirBomber/AirBomber/EntityAirBomber.cs
@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace AirBomber
{
- internal class EntityAirBomber : EntityAirplane
+ public class EntityAirBomber : EntityAirplane
{
///
/// Дополнительный цвет
diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
index fb182f6..2ffcf8f 100644
--- a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
+++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
@@ -1,4 +1,5 @@
-using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
+using System.Windows.Forms;
namespace AirBomber
{
@@ -22,13 +23,18 @@ namespace AirBomber
///
private LinkedList _deletedObjects;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormMapWithSetAirplanes()
+ public FormMapWithSetAirplanes(ILogger logger)
{
InitializeComponent();
_generatorAirplane = new(100, 100);
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
+ _logger = logger;
_deletedObjects = new();
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -70,15 +76,18 @@ namespace AirBomber
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("При добавлении карты {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);
}
///
/// Выбор карты
@@ -88,6 +97,7 @@ namespace AirBomber
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[NameMap].ShowSet();
+ _logger.LogInformation("Был осуществлен переход на карту под названием: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
///
/// Удаление карты
@@ -104,6 +114,7 @@ namespace AirBomber
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(NameMap);
+ _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@@ -113,22 +124,32 @@ namespace AirBomber
/// Заголовок MessageBox если самолета нет
private void AddAirplaneInMap(DrawningObject? airplane, string? text = null, string? caption = null)
{
- if (listBoxMaps.SelectedIndex == -1)
+ try
{
- MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ if (listBoxMaps.SelectedIndex == -1)
+ {
+ MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ }
+ else if (airplane == null)
+ {
+ MessageBox.Show(text, caption);
+ }
+ else if ((_mapsCollection[NameMap] + airplane) == -1)
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning("Не удалось добавить объект");
+ }
+ else
+ {
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _mapsCollection[NameMap].ShowSet();
+ _logger.LogInformation("Добавлен объект {@Airplane}", (DrawningAirplane)airplane);
+ }
}
- else if (airplane == null)
+ catch (StorageOverflowException ex)
{
- MessageBox.Show(text, caption);
- }
- else if ((_mapsCollection[NameMap] + airplane) == -1)
- {
- MessageBox.Show("Не удалось добавить объект");
- }
- else
- {
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _mapsCollection[NameMap].ShowSet();
+ _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
+ MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
///
@@ -247,16 +268,26 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- var deletedObject = _mapsCollection[NameMap, pos];
- if (_mapsCollection[NameMap] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- _deletedObjects.AddLast(deletedObject);
- pictureBox.Image = _mapsCollection[NameMap].ShowSet();
+ var deletedObject = _mapsCollection[NameMap] - pos;
+ if (deletedObject != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation("Из текущей карты удален объект {@Airplane}", deletedObject);
+ _deletedObjects.AddLast(deletedObject);
+ pictureBox.Image = _mapsCollection[NameMap].ShowSet();
+ }
+ else
+ {
+ _logger.LogWarning("Не удалось добавить объект по позиции {0} равен null", pos);
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (AirplaneNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
}
///
@@ -304,21 +335,6 @@ namespace AirBomber
AddAirplaneInMap(form.SelectedAirplane);
}
}
- ///
- /// В зависимости от успешности сохранения показывает разные всплывающие окна
- ///
- private void ShowStatusSaveFile(bool succesfullSave)
- {
- if (succesfullSave)
- {
- MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
- {
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
-
///
/// Обработка нажатия "Сохранение"
///
@@ -328,7 +344,18 @@ namespace AirBomber
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- ShowStatusSaveFile(_mapsCollection.SaveData(saveFileDialog.FileName));
+ try
+ {
+ _mapsCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation("Сохранение прошло успешно. Файл находится: {0}", saveFileDialog.FileName);
+ MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
+ }
+
}
}
///
@@ -340,13 +367,15 @@ namespace AirBomber
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
- else
+ catch (Exception ex)
{
+ _logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@@ -357,7 +386,19 @@ namespace AirBomber
saveFileDialog.FileName = NameMap;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- ShowStatusSaveFile(_mapsCollection.SaveMap(saveFileDialog.FileName, NameMap));
+ try
+ {
+ _mapsCollection.LoadData(openFileDialog.FileName);
+ MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _logger.LogInformation("Открытие файла '{0}' прошло успешно", openFileDialog.FileName);
+ ReloadMaps();
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show($"Не удалось открыть: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не удалось открыть файл {0}. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
+ }
+
}
}
}
diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs
index 1959822..5b23807 100644
--- a/AirBomber/AirBomber/MapsCollection.cs
+++ b/AirBomber/AirBomber/MapsCollection.cs
@@ -93,8 +93,7 @@ namespace AirBomber
/// Сохранение информации по самолетам в хранилище в файл
///
/// Путь и имя файла
- ///
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -108,7 +107,6 @@ namespace AirBomber
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
- return true;
}
public bool SaveMap(string filename, string nameMap)
@@ -130,7 +128,7 @@ namespace AirBomber
return true;
}
- private bool LoadMap(string nameMapStorage, string nameMap, string lineData)
+ private void LoadMap(string nameMapStorage, string nameMap, string lineData)
{
AbstractMap map = null;
switch (nameMap)
@@ -144,19 +142,17 @@ namespace AirBomber
}
_mapStorages[nameMapStorage] = new(_pictureWidth, _pictureHeight, map);
_mapStorages[nameMapStorage].LoadData(lineData.Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
- return true;
}
///
/// Загрузка информации по самолетам в ангарах из файла
///
///
- ///
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
List strs = new List();
using (StreamReader fs = new(filename))
@@ -170,12 +166,12 @@ namespace AirBomber
if (strs[0].Contains("Map") && isNotMapsCollection)
{
var elem = strs[2].Split(separatorDict);
- return LoadMap(strs[1].Replace("Name: ", ""), elem[0], elem[1]);
+ LoadMap(strs[1].Replace("Name: ", ""), elem[0], elem[1]);
}
else if (isNotMapsCollection)
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
@@ -184,7 +180,6 @@ namespace AirBomber
var elem = strs[i].Split(separatorDict);
LoadMap(elem[0], elem[1], elem[2]);
}
- return true;
}
}
}
diff --git a/AirBomber/AirBomber/Program.cs b/AirBomber/AirBomber/Program.cs
index 5325330..f0821c2 100644
--- a/AirBomber/AirBomber/Program.cs
+++ b/AirBomber/AirBomber/Program.cs
@@ -1,3 +1,10 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using Serilog.Extensions.Logging;
+using System;
+
namespace AirBomber
{
internal static class Program
@@ -11,7 +18,30 @@ 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 FormMapWithSetAirplanes());
+ 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/AirBomber/AirBomber/SetAirplanesGeneric.cs b/AirBomber/AirBomber/SetAirplanesGeneric.cs
index fffa285..862d620 100644
--- a/AirBomber/AirBomber/SetAirplanesGeneric.cs
+++ b/AirBomber/AirBomber/SetAirplanesGeneric.cs
@@ -54,6 +54,8 @@ namespace AirBomber
/// Возвращает позицию вставленого объекта либо -1, если не получилось его добавить
public int Insert(T airplane, int position)
{
+ if (Count == _maxcount)
+ throw new StorageOverflowException(_maxcount);
if (!isCorrectPosition(position))
{
return -1;
@@ -70,6 +72,9 @@ namespace AirBomber
{
if (!isCorrectPosition(position) || position >= Count)
return null;
+ var result = this[position];
+ if (result == null)
+ throw new AirplaneNotFoundException(position);
var deletedObj = _places[position];
_places.RemoveAt(position);
return deletedObj;
diff --git a/AirBomber/AirBomber/StorageOverflowException.cs b/AirBomber/AirBomber/StorageOverflowException.cs
new file mode 100644
index 0000000..1701690
--- /dev/null
+++ b/AirBomber/AirBomber/StorageOverflowException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace AirBomber
+{
+ [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/AirBomber/AirBomber/appsettings.json b/AirBomber/AirBomber/appsettings.json
new file mode 100644
index 0000000..94031e0
--- /dev/null
+++ b/AirBomber/AirBomber/appsettings.json
@@ -0,0 +1,48 @@
+{
+ "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" ],
+ "Destructure": [
+ {
+ "Name": "ByTransforming",
+ "Args": {
+ "returnType": "AirBomber.EntityAirplane",
+ "transformation": "r => new { BodyColor = r.BodyColor.Name, r.Speed, r.Weight }"
+ }
+ },
+ {
+ "Name": "ByTransforming",
+ "Args": {
+ "returnType": "AirBomber.EntityAirBomber",
+ "transformation": "r => new { BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.HasBombs, r.HasFuelTanks, r.Speed, r.Weight }"
+ }
+ },
+ {
+ "Name": "ToMaximumDepth",
+ "Args": { "maximumDestructuringDepth": 4 }
+ },
+ {
+ "Name": "ToMaximumStringLength",
+ "Args": { "maximumStringLength": 100 }
+ },
+ {
+ "Name": "ToMaximumCollectionCount",
+ "Args": { "maximumCollectionCount": 10 }
+ }
+ ],
+ "Properties": {
+ "Application": "AirBomber"
+ }
+ }
+}
\ No newline at end of file