diff --git a/Airbus/Airbus/Airbus.csproj b/Airbus/Airbus/Airbus.csproj index 13ee123..f8653ab 100644 --- a/Airbus/Airbus/Airbus.csproj +++ b/Airbus/Airbus/Airbus.csproj @@ -8,6 +8,20 @@ enable + + + + + + + + + + + + + + True diff --git a/Airbus/Airbus/FormMapWithSetPlanes.cs b/Airbus/Airbus/FormMapWithSetPlanes.cs index b51ea65..6b0c7bd 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; @@ -28,9 +29,11 @@ namespace Airbus /// /// Конструктор /// - public FormMapWithSetPlanes() + private readonly ILogger _logger; + public FormMapWithSetPlanes(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -68,16 +71,19 @@ namespace Airbus 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}", comboBoxSelectorMap.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -87,6 +93,7 @@ namespace Airbus private void listBoxMaps_SelectedIndexChanged_1(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } /// /// Удаление карты @@ -101,6 +108,7 @@ namespace Airbus } if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } @@ -114,25 +122,35 @@ namespace Airbus { var formPlaneConfig = new FormPlaneConfig(); formPlaneConfig.AddEvent(AddPlane); - // TODO formPlaneConfig.Show(); } private void AddPlane(DrawningPlane plane) { - if (listBoxMaps.SelectedIndex == -1) + try { - MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + if (listBoxMaps.SelectedIndex == -1) + { + MessageBox.Show("Перед добавлением объекта необходимо создать карту"); + } + else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectPlane(plane) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Plane}", plane); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - else 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(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } + } /// /// Удаление объекта @@ -154,14 +172,28 @@ namespace Airbus return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + try{ + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning("Не удалось удалить объект по позиции {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}"); } } /// @@ -230,15 +262,16 @@ namespace Airbus { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -248,14 +281,17 @@ namespace Airbus // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); + MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/Airbus/Airbus/MapWithSetPlanesGeneric.cs b/Airbus/Airbus/MapWithSetPlanesGeneric.cs index c900b75..ebaf55b 100644 --- a/Airbus/Airbus/MapWithSetPlanesGeneric.cs +++ b/Airbus/Airbus/MapWithSetPlanesGeneric.cs @@ -169,8 +169,6 @@ namespace Airbus g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight); } - - } /// /// Метод прорисовки объектов @@ -214,7 +212,5 @@ namespace Airbus _setPlanes.Insert(DrawningObjectPlane.Create(rec) as T); } } - } - } diff --git a/Airbus/Airbus/MapsCollection.cs b/Airbus/Airbus/MapsCollection.cs index a1ecbed..dde5d2b 100644 --- a/Airbus/Airbus/MapsCollection.cs +++ b/Airbus/Airbus/MapsCollection.cs @@ -78,21 +78,11 @@ namespace Airbus } } /// - /// Метод записи информации в файл - /// - /// Строка, которую следует записать - /// Поток для записи - private static void WriteToFile(string text, FileStream stream) - { - byte[] info = new UTF8Encoding(true).GetBytes(text); - stream.Write(info, 0, info.Length); - } - /// /// Сохранение информации по самолетам в хранилище в файл /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -106,25 +96,24 @@ namespace Airbus 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)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -144,7 +133,6 @@ namespace Airbus _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/Airbus/Airbus/PlaneNotFoundException.cs b/Airbus/Airbus/PlaneNotFoundException.cs new file mode 100644 index 0000000..3aab506 --- /dev/null +++ b/Airbus/Airbus/PlaneNotFoundException.cs @@ -0,0 +1,19 @@ +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..8494375 100644 --- a/Airbus/Airbus/Program.cs +++ b/Airbus/Airbus/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Airbus { internal static class Program @@ -11,7 +16,29 @@ 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().AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilog.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/Airbus/Airbus/SetPlanesGeneric.cs b/Airbus/Airbus/SetPlanesGeneric.cs index f1a02ba..4036acb 100644 --- a/Airbus/Airbus/SetPlanesGeneric.cs +++ b/Airbus/Airbus/SetPlanesGeneric.cs @@ -34,10 +34,7 @@ namespace Airbus /// public int Insert(T plane) { - // TODO вставка в начало набора - // TODO проверка на _maxCount - if (_places.Count + 1 >= _maxCount) - return -1; + if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(0, plane); return 0; } @@ -51,12 +48,7 @@ namespace Airbus { // TODO проверка позиции // TODO вставка по позиции - if (position >= _maxCount || position < 0) - { - return -1; - } - if (_places.Count + 1 >= _maxCount) - return -1; + if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, plane); return position; } @@ -69,13 +61,13 @@ namespace Airbus { // TODO проверка позиции // TODO удаление объекта из массива, присовив элементу массива значение null - if (position >= _maxCount || position < 0) - { - return null; - } - T DeletePlane = _places[position]; - _places.RemoveAt(position); - return DeletePlane; + if (position >= _maxCount || position >= _places.Count) throw new PlaneNotFoundException(position); + + T res = _places[position]; + _places.Remove(res); + + if (res == null) throw new PlaneNotFoundException(position); + return res; } /// /// Получение объекта из набора по позиции diff --git a/Airbus/Airbus/StorageOverflowException.cs b/Airbus/Airbus/StorageOverflowException.cs new file mode 100644 index 0000000..bdd1ec7 --- /dev/null +++ b/Airbus/Airbus/StorageOverflowException.cs @@ -0,0 +1,19 @@ +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) { } + } +} diff --git a/Airbus/Airbus/serilog.json b/Airbus/Airbus/serilog.json new file mode 100644 index 0000000..5dd3d1b --- /dev/null +++ b/Airbus/Airbus/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } +} \ No newline at end of file