diff --git a/AirBomber/AirBomber/AirBomber.csproj b/AirBomber/AirBomber/AirBomber.csproj
index b57c89e..fb66889 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/DrawningObject.cs b/AirBomber/AirBomber/DrawningObject.cs
index 5751bfc..4bb3594 100644
--- a/AirBomber/AirBomber/DrawningObject.cs
+++ b/AirBomber/AirBomber/DrawningObject.cs
@@ -36,5 +36,9 @@ namespace AirBomber
{
_airplane?.DrawTransport(g);
}
+
+ public string GetInfo() => _airplane?.GetDataForSave();
+
+ public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningAirplane());
}
}
diff --git a/AirBomber/AirBomber/EntityAirBomber.cs b/AirBomber/AirBomber/EntityAirBomber.cs
index 6d5b03f..c52259a 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/ExtentionAirplane.cs b/AirBomber/AirBomber/ExtentionAirplane.cs
new file mode 100644
index 0000000..c39eaaf
--- /dev/null
+++ b/AirBomber/AirBomber/ExtentionAirplane.cs
@@ -0,0 +1,50 @@
+namespace AirBomber
+{
+ ///
+ /// Расширение для класса DrawningAirplane
+ ///
+ internal static class ExtentionAirplane
+ {
+ ///
+ /// Разделитель для записи информации по объекту в файл
+ ///
+ private static readonly char _separatorForObject = ':';
+ ///
+ /// Создание объекта из строки
+ ///
+ ///
+ ///
+ public static DrawningAirplane CreateDrawningAirplane(this string info)
+ {
+ string[] strs = info.Split(_separatorForObject);
+ if (strs.Length == 3)
+ {
+ return new DrawningAirplane(Convert.ToInt32(strs[0]),
+ Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
+ }
+ if (strs.Length == 6)
+ {
+ return new DrawningAirBomber(Convert.ToInt32(strs[0]),
+ Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
+ Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
+ Convert.ToBoolean(strs[5]));
+ }
+ return null;
+ }
+ ///
+ /// Получение данных для сохранения в файл
+ ///
+ ///
+ ///
+ public static string GetDataForSave(this DrawningAirplane drawningAirplane)
+ {
+ var Airplane = drawningAirplane.Airplane;
+ var str = $"{Airplane.Speed}{_separatorForObject}{Airplane.Weight}{_separatorForObject}{Airplane.BodyColor.Name}";
+ if (Airplane is not EntityAirBomber AirBomber)
+ {
+ return str;
+ }
+ return $"{str}{_separatorForObject}{AirBomber.DopColor.Name}{_separatorForObject}{AirBomber.HasBombs}{_separatorForObject}{AirBomber.HasFuelTanks}";
+ }
+ }
+}
\ No newline at end of file
diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs
index 0cdc893..9bd368d 100644
--- a/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs
+++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.Designer.cs
@@ -45,6 +45,12 @@
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonAddAirplane = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
+ this.menuStrip = new System.Windows.Forms.MenuStrip();
+ this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
+ this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
@@ -238,6 +244,46 @@
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
+ // menuStrip
+ //
+ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.файлToolStripMenuItem});
+ this.menuStrip.Location = new System.Drawing.Point(0, 0);
+ this.menuStrip.Name = "menuStrip";
+ this.menuStrip.Size = new System.Drawing.Size(1015, 24);
+ this.menuStrip.TabIndex = 2;
+ //
+ // файлToolStripMenuItem
+ //
+ this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.SaveToolStripMenuItem,
+ this.LoadToolStripMenuItem});
+ this.файлToolStripMenuItem.Name = "файлToolStripMenuItem";
+ this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
+ this.файлToolStripMenuItem.Text = "Файл";
+ //
+ // SaveToolStripMenuItem
+ //
+ this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
+ this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
+ this.SaveToolStripMenuItem.Text = "Сохранение";
+ this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
+ //
+ // LoadToolStripMenuItem
+ //
+ this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
+ this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
+ this.LoadToolStripMenuItem.Text = "Загрузка";
+ this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
+ //
+ // openFileDialog
+ //
+ this.openFileDialog.Filter = "txt file | *.txt";
+ //
+ // saveFileDialog
+ //
+ this.saveFileDialog.Filter = "txt file | *.txt";
+ //
// FormMapWithSetAirplanes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -245,6 +291,8 @@
this.ClientSize = new System.Drawing.Size(1015, 632);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
+ this.Controls.Add(this.menuStrip);
+ this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirplanes";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
@@ -252,6 +300,8 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
+ this.menuStrip.ResumeLayout(false);
+ this.menuStrip.PerformLayout();
this.ResumeLayout(false);
}
@@ -275,5 +325,11 @@
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private Button buttonAddMap;
+ private MenuStrip menuStrip;
+ private ToolStripMenuItem файлToolStripMenuItem;
+ private ToolStripMenuItem SaveToolStripMenuItem;
+ private ToolStripMenuItem LoadToolStripMenuItem;
+ private OpenFileDialog openFileDialog;
+ private SaveFileDialog saveFileDialog;
}
}
\ No newline at end of file
diff --git a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
index 0423e3f..c4f6072 100644
--- a/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
+++ b/AirBomber/AirBomber/FormMapWithSetAirplanes.cs
@@ -1,4 +1,7 @@
-namespace AirBomber
+using Microsoft.Extensions.Logging;
+using System.Windows.Forms;
+
+namespace AirBomber
{
public partial class FormMapWithSetAirplanes : Form
{
@@ -15,12 +18,17 @@
///
private readonly MapsCollection _mapsCollection;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Конструктор
///
- public FormMapWithSetAirplanes()
+ public FormMapWithSetAirplanes(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,19 +126,30 @@
///
private void AddAirplane(DrawningAirplane airplane)
{
- if (listBoxMaps.SelectedIndex == -1)
+ try
{
- MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ if (listBoxMaps.SelectedIndex == -1)
+ {
+ MessageBox.Show("Перед добавлением объекта необходимо создать карту");
+ }
+ else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(airplane) != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ _logger.LogInformation("Добавлен объект {@Airplane}", airplane);
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ _logger.LogInformation("Не удалось добавить объект");
+ }
}
- else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(airplane) != -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);
}
+
}
///
/// Удаление объекта
@@ -140,15 +164,27 @@
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 (AirplaneNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
+
}
///
/// Вывод набора
@@ -207,5 +243,51 @@
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ 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);
+ }
+ }
+ }
+ ///
+ /// Обработка нажатия "Загрузка"
+ ///
+ ///
+ ///
+ private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ 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);
+ }
+ }
+ }
}
}
\ No newline at end of file
diff --git a/AirBomber/AirBomber/IDrawningObject.cs b/AirBomber/AirBomber/IDrawningObject.cs
index a2afce7..87584d8 100644
--- a/AirBomber/AirBomber/IDrawningObject.cs
+++ b/AirBomber/AirBomber/IDrawningObject.cs
@@ -39,5 +39,11 @@ namespace AirBomber
///
///
RectangleF GetCurrentPosition();
+
+ ///
+ /// Получение информации по объекту
+ ///
+ ///
+ string GetInfo();
}
}
diff --git a/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs b/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs
index 291cff0..6a18d52 100644
--- a/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs
+++ b/AirBomber/AirBomber/MapWithSetAirplanesGeneric.cs
@@ -182,5 +182,31 @@ namespace AirBomber
airplane?.DrawObject(g);
}
}
+
+ ///
+ /// Получение данных в виде строки
+ ///
+ ///
+ ///
+ public string GetData(char separatorType, char separatorData)
+ {
+ string data = $"{_map.GetType().Name}{separatorType}";
+ foreach (var car in _setAirplanes.GetAirplanes())
+ {
+ data += $"{car.GetInfo()}{separatorData}";
+ }
+ return data;
+ }
+ ///
+ /// Загрузка списка из массива строк
+ ///
+ ///
+ public void LoadData(string[] records)
+ {
+ foreach (var rec in records)
+ {
+ _setAirplanes.Insert(DrawningObject.Create(rec) as T);
+ }
+ }
}
}
diff --git a/AirBomber/AirBomber/MapsCollection.cs b/AirBomber/AirBomber/MapsCollection.cs
index f986a06..c9aaea7 100644
--- a/AirBomber/AirBomber/MapsCollection.cs
+++ b/AirBomber/AirBomber/MapsCollection.cs
@@ -15,7 +15,7 @@ namespace AirBomber
///
/// Словарь (хранилище) с картами
///
- readonly Dictionary> _mapStorages;
///
/// Возвращение списка названий карт
@@ -30,6 +30,14 @@ namespace AirBomber
///
private readonly int _pictureHeight;
///
+ /// Разделитель для записи информации по элементу словаря в файл
+ ///
+ private readonly char separatorDict = '|';
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly char separatorData = ';';
+ ///
/// Конструктор
///
///
@@ -37,7 +45,7 @@ namespace AirBomber
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary>();
+ MapWithSetAirplanesGeneric>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -63,7 +71,7 @@ namespace AirBomber
///
///
///
- public MapWithSetAirplanesGeneric this[string ind]
+ public MapWithSetAirplanesGeneric this[string ind]
{
get
{
@@ -71,5 +79,65 @@ namespace AirBomber
return mapWithSetAirplanesGeneric;
}
}
+
+ ///
+ /// Сохранение информации по самолетам в хранилище в файл
+ ///
+ /// Путь и имя файла
+ public void SaveData(string filename)
+ {
+ if (File.Exists(filename))
+ {
+ File.Delete(filename);
+ }
+ using (StreamWriter fs = new(filename))
+ {
+ fs.Write($"MapsCollection{Environment.NewLine}");
+ foreach (var storage in _mapStorages)
+ {
+ fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
+ }
+ }
+ }
+ ///
+ /// Загрузка информации по самолетам в ангарах из файла
+ ///
+ ///
+ ///
+ public void LoadData(string filename)
+ {
+ if (!File.Exists(filename))
+ {
+ throw new FileNotFoundException("Файл не найден");
+ }
+ using (StreamReader fs = new(filename))
+ {
+ if (!fs.ReadLine().Contains("MapsCollection"))
+ {
+ //если нет такой записи, то это не те данные
+ throw new FileFormatException("Формат данных в файле не правильный");
+ }
+ //очищаем записи
+ _mapStorages.Clear();
+ while (!fs.EndOfStream)
+ {
+ var elem = fs.ReadLine().Split(separatorDict);
+ AbstractMap map = null;
+ switch (elem[1])
+ {
+ case "SimpleMap":
+ map = new SimpleMap();
+ break;
+ case "WallMap":
+ map = new WallMap();
+ break;
+ }
+ _mapStorages.Add(elem[0], new
+ MapWithSetAirplanesGeneric(_pictureWidth, _pictureHeight, map));
+ _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData,
+ StringSplitOptions.RemoveEmptyEntries));
+ }
+ }
+ }
}
}
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 c3a054a..986ccf7 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,7 +72,9 @@ namespace AirBomber
{
if (!isCorrectPosition(position))
return null;
- var result = _places[position];
+ var result = this[position];
+ if (result == null)
+ throw new AirplaneNotFoundException(position);
_places.RemoveAt(position);
return result;
}
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