diff --git a/Airbus/Airbus/Airbus.csproj b/Airbus/Airbus/Airbus.csproj index 3ec74d3..8ea4f98 100644 --- a/Airbus/Airbus/Airbus.csproj +++ b/Airbus/Airbus/Airbus.csproj @@ -28,4 +28,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index 14d8c07..18f4ffd 100644 --- a/Airbus/Airbus/FormMapWithSetPlanes.cs +++ b/Airbus/Airbus/FormMapWithSetPlanes.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -24,10 +25,14 @@ namespace Airbus //объект от коллекции карт private readonly MapsCollection _mapsCollection; + //логер + private readonly ILogger _logger; + //конструктор - public FormMapWithSetPlanes() + public FormMapWithSetPlanes(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var element in _mapsDict) @@ -64,6 +69,7 @@ namespace Airbus if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } @@ -71,12 +77,14 @@ namespace Airbus if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Отсутствует карта с названием {0}", textBoxNewMapName.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); + _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text); ReloadMaps(); } @@ -84,6 +92,7 @@ namespace Airbus 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); } // Удаление карты @@ -97,6 +106,7 @@ namespace Airbus { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } } @@ -104,20 +114,34 @@ namespace Airbus //отрисовка добавленного объекта в хранилище private void AddPlane(DrawningAirbus plane) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Airbus}", plane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1) + catch(StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка, переполнение хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch(ArgumentException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Airbus}", ex.Message, plane); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - } //добавление объекта @@ -132,7 +156,7 @@ namespace Airbus //удаление объекта private void ButtonRemovePlane_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)) + if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text)) { return; } @@ -145,14 +169,31 @@ namespace Airbus 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 deletedPlane = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + + if (deletedPlane != null) + { + MessageBox.Show("Объект удалён"); + _logger.LogInformation("Из текущей карты удалён объект {@Airbus}", deletedPlane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (PlaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -214,15 +255,18 @@ namespace Airbus { 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("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -232,16 +276,19 @@ namespace Airbus { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { - ReloadMaps(); + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); MessageBox.Show("Загрузка данных прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); } - else + catch(Exception ex) { - MessageBox.Show("Ошибка загрузки данных", "Результат", + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); } } } diff --git a/Airbus/Airbus/MapWithSetPlanesGeneric.cs b/Airbus/Airbus/MapWithSetPlanesGeneric.cs index 485747c..4917a05 100644 --- a/Airbus/Airbus/MapWithSetPlanesGeneric.cs +++ b/Airbus/Airbus/MapWithSetPlanesGeneric.cs @@ -34,9 +34,7 @@ namespace Airbus //конструктор public MapWithSetPlanesGeneric(int picWidth, int picHeight, U map) { - int width = picWidth / _placeSizeWidth; - int height = picHeight / _placeSizeHeight; - _setPlanes = new SetPlanesGeneric(width * height); + _setPlanes = new SetPlanesGeneric(18); _pictureWidth = picWidth; _pictureHeight = picHeight; _map = map; diff --git a/Airbus/Airbus/MapsCollection.cs b/Airbus/Airbus/MapsCollection.cs index a47df27..9cc94ff 100644 --- a/Airbus/Airbus/MapsCollection.cs +++ b/Airbus/Airbus/MapsCollection.cs @@ -54,7 +54,7 @@ namespace Airbus } //сохранение информации по самолётам в ангарах в файл - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -67,21 +67,18 @@ namespace Airbus foreach (var storage in _mapStorage) { - sw.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 sr = new(filename)) @@ -91,7 +88,7 @@ namespace Airbus //если не содержит такую запись или пустой файл if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Формат данных в файле неправильный"); } _mapStorage.Clear(); @@ -115,16 +112,13 @@ namespace Airbus } _mapStorage.Add(element[0], new MapWithSetPlanesGeneric(_pictureWidth, _pictureHeight, - map)); + map)); _mapStorage[element[0]].LoadData(element[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - - return true; } - //доступ к аэродрому public MapWithSetPlanesGeneric this[string ind] { diff --git a/Airbus/Airbus/PlaneNotFoundException.cs b/Airbus/Airbus/PlaneNotFoundException.cs new file mode 100644 index 0000000..69a851a --- /dev/null +++ b/Airbus/Airbus/PlaneNotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Airbus +{ + [Serializable] + + //класс собственных исключений + internal class PlaneNotFoundException : ApplicationException + { + public PlaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + + public PlaneNotFoundException() : base() { } + + public PlaneNotFoundException(string message) : base(message) { } + + public PlaneNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected PlaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Airbus/Airbus/Program.cs b/Airbus/Airbus/Program.cs index 5166800..960b56d 100644 --- a/Airbus/Airbus/Program.cs +++ b/Airbus/Airbus/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 Airbus { internal static class Program @@ -11,7 +18,30 @@ namespace Airbus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetPlanes()); + + var services = new ServiceCollection(); + ConfigureServices(services); + + using(ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton(); + + var serilogLogger = new LoggerConfiguration() + .WriteTo.RollingFile("Logs\\log.txt") + .CreateLogger(); + + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger: serilogLogger, dispose: true); + }); + } } } \ No newline at end of file diff --git a/Airbus/Airbus/SaveData.txt b/Airbus/Airbus/SaveData.txt index 8b13789..c96b589 100644 --- a/Airbus/Airbus/SaveData.txt +++ b/Airbus/Airbus/SaveData.txt @@ -1 +1,2 @@ - +MapsCollection +123|StarWarsMap|1000:750:Red;1000:750:DeepPink:Control:False:False; diff --git a/Airbus/Airbus/SetPlanesGeneric.cs b/Airbus/Airbus/SetPlanesGeneric.cs index aa457ec..70d5559 100644 --- a/Airbus/Airbus/SetPlanesGeneric.cs +++ b/Airbus/Airbus/SetPlanesGeneric.cs @@ -29,18 +29,29 @@ namespace Airbus //добавление объекта в набор public int Insert(T plane) { + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } + if (Count + 1 <= _maxCount) return Insert(plane, 0); + else return -1; } //добавление объекта в набор на конкретную позицию public int Insert(T plane, int position) { - if (position >= _maxCount && position < 0) + if (position > _maxCount && position < 0) { return -1; } + if (_places.Contains(plane)) + { + throw new ArgumentException($"Объект {plane} уже есть в наборе"); + } + _places.Insert(position, plane); return position; @@ -49,22 +60,15 @@ namespace Airbus //удаление объекта из набора с конкретной позиции public T Remove(int position) { - if (position < _maxCount && position >= 0) + if (position >= Count || position < 0) { - - if (_places.ElementAt(position) != null) - { - T result = _places.ElementAt(position); - - _places.RemoveAt(position); - - return result; - } - - return null; + throw new PlaneNotFoundException(position); } - return null; + T result = _places[position]; + _places.RemoveAt(position); + + return result; } //получение объекта из набора по позиции diff --git a/Airbus/Airbus/StorageOverflowException.cs b/Airbus/Airbus/StorageOverflowException.cs new file mode 100644 index 0000000..3a95d3c --- /dev/null +++ b/Airbus/Airbus/StorageOverflowException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Airbus +{ + [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) { } + } +}