diff --git a/Stormtrooper/Stormtrooper/FormMapWithSetStormtroopers.cs b/Stormtrooper/Stormtrooper/FormMapWithSetStormtroopers.cs index 6f89c82..d362c82 100644 --- a/Stormtrooper/Stormtrooper/FormMapWithSetStormtroopers.cs +++ b/Stormtrooper/Stormtrooper/FormMapWithSetStormtroopers.cs @@ -1,4 +1,6 @@ -using System; +using Microsoft.Extensions.Logging; +using Serilog.Core; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -25,13 +27,17 @@ namespace Stormtrooper /// Объект от коллекции карт /// private readonly MapsCollection _mapsCollection; - + /// + /// Логер + /// + private readonly ILogger _logger; /// /// Конструктор /// - public FormMapWithSetStormtroopers() + public FormMapWithSetStormtroopers(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -46,28 +52,37 @@ namespace Stormtrooper /// private void ButtonAddStorm_Click(object sender, EventArgs e) { + if (listBoxMaps.SelectedIndex == -1) + { + return; + } var formStormConfig = new FormStormtrooperConfig(); formStormConfig.AddEvent(AddStormtrooper); formStormConfig.Show(); } - private void AddStormtrooper (Drawning storm) + private void AddStormtrooper(Drawning storm) { if (listBoxMaps.SelectedIndex == -1) { return; } - DrawningObjectStorm st = new(storm); + try { - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + st != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } + int res = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectStorm(storm); + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавление объекта: {storm.ToString()}"); + } + catch (StorageOverflowException ex) + { + MessageBox.Show($"Не удалось добавить объект: {ex.Message}"); + _logger.LogWarning($"Ошибка добавления объекта: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Ошибка добавления объекта: {ex.Message}"); } } /// @@ -89,16 +104,26 @@ namespace Stormtrooper { return; } + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { + IDrawningObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; MessageBox.Show("Объект удален"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удаление объекта: {drawingObject.ToString()}"); } - else + catch (StormtrooperNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.LogWarning($"Ошибка удаления объекта: {ex.Message}"); } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Ошибка удаления объекта: {ex.Message}"); + } + } /// /// Вывод набора @@ -188,11 +213,13 @@ namespace Stormtrooper } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } private void ButtonDeleteMap_Click(object sender, EventArgs e) @@ -206,6 +233,7 @@ namespace Stormtrooper _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}"); } /// /// Обработка нажатия "Сохранение" @@ -216,13 +244,16 @@ namespace Stormtrooper { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Information); + _mapsCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение данных в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка сохранения данных: {ex.Message}"); } } } @@ -235,14 +266,17 @@ namespace Stormtrooper { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); + _logger.LogInformation($"Загрузка данных из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка загрузки данных: {ex.Message}"); } } } diff --git a/Stormtrooper/Stormtrooper/MapsCollection.cs b/Stormtrooper/Stormtrooper/MapsCollection.cs index 6a9cc63..a8199c5 100644 --- a/Stormtrooper/Stormtrooper/MapsCollection.cs +++ b/Stormtrooper/Stormtrooper/MapsCollection.cs @@ -83,7 +83,7 @@ namespace Stormtrooper /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -98,18 +98,17 @@ namespace Stormtrooper sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"); } } - return true; } /// /// Загрузка информации по самолётам в ангаре из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } string line; using (StreamReader sw = new(filename)) @@ -117,7 +116,7 @@ namespace Stormtrooper line = sw.ReadLine(); if (line == null || !line.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Неверный формат файла"); } _mapStorages.Clear(); @@ -142,8 +141,6 @@ namespace Stormtrooper _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); line = sw.ReadLine(); } - - return true; } } diff --git a/Stormtrooper/Stormtrooper/Program.cs b/Stormtrooper/Stormtrooper/Program.cs index f31027b..8d9c9b1 100644 --- a/Stormtrooper/Stormtrooper/Program.cs +++ b/Stormtrooper/Stormtrooper/Program.cs @@ -1,3 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.VisualBasic.Logging; +using Serilog; +using System; + namespace Stormtrooper { internal static class Program @@ -11,7 +18,27 @@ namespace Stormtrooper // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetStormtroopers()); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilog.json") + .Build(); + Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + option.AddSerilog(); + }); } } } \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/SetStormtroopersGeneric.cs b/Stormtrooper/Stormtrooper/SetStormtroopersGeneric.cs index 54ee076..35dc27a 100644 --- a/Stormtrooper/Stormtrooper/SetStormtroopersGeneric.cs +++ b/Stormtrooper/Stormtrooper/SetStormtroopersGeneric.cs @@ -39,7 +39,6 @@ namespace Stormtrooper /// public int Insert(T stormtrooper) { - if (_places.Count + 1 >= _maxCount) return -1; return Insert(stormtrooper, 0); } /// @@ -50,8 +49,9 @@ namespace Stormtrooper /// public int Insert(T stormtrooper, int position) { - if (position < 0 || position >= _maxCount) return -1; - if (_places.Count + 1 >= _maxCount) return -1; + if (position < 0 || position >= _maxCount) + throw new StorageOverflowException(_maxCount); + if (_places.Count >= _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, stormtrooper); return position; } @@ -62,7 +62,9 @@ namespace Stormtrooper /// public T Remove(int position) { - if (position < 0 || position >= _maxCount) return null; + if (position < 0 || position >= _maxCount) + throw new StormtrooperNotFoundException(); + if (position >= _places.Count) throw new StormtrooperNotFoundException(position); T saveStorm = _places[position]; _places.RemoveAt(position); return saveStorm; diff --git a/Stormtrooper/Stormtrooper/StorageOverflowException.cs b/Stormtrooper/Stormtrooper/StorageOverflowException.cs new file mode 100644 index 0000000..0caf0f3 --- /dev/null +++ b/Stormtrooper/Stormtrooper/StorageOverflowException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Stormtrooper +{ + [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/Stormtrooper/Stormtrooper/Stormtrooper.csproj b/Stormtrooper/Stormtrooper/Stormtrooper.csproj index 13ee123..a306c1b 100644 --- a/Stormtrooper/Stormtrooper/Stormtrooper.csproj +++ b/Stormtrooper/Stormtrooper/Stormtrooper.csproj @@ -8,6 +8,28 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + True diff --git a/Stormtrooper/Stormtrooper/StormtrooperNotFoundException.cs b/Stormtrooper/Stormtrooper/StormtrooperNotFoundException.cs new file mode 100644 index 0000000..240c002 --- /dev/null +++ b/Stormtrooper/Stormtrooper/StormtrooperNotFoundException.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 Stormtrooper +{ + [Serializable] + internal class StormtrooperNotFoundException : ApplicationException + { + public StormtrooperNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public StormtrooperNotFoundException() : base("Выход за границы") { } + public StormtrooperNotFoundException(string message) : base(message) { } + public StormtrooperNotFoundException(string message, Exception exception) : base(message, exception) { } + protected StormtrooperNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Stormtrooper/Stormtrooper/serilog.json b/Stormtrooper/Stormtrooper/serilog.json new file mode 100644 index 0000000..d2acb30 --- /dev/null +++ b/Stormtrooper/Stormtrooper/serilog.json @@ -0,0 +1,24 @@ +{ + "exclude": [ + "**/bin", + "**/bower_components", + "**/jspm_packages", + "**/node_modules", + "**/obj", + "**/platforms" + ], + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "Logs/log.log" } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file