diff --git a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj index 13ee123..3483561 100644 --- a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj +++ b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True diff --git a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGunNotFoundException.cs b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGunNotFoundException.cs new file mode 100644 index 0000000..5e75f45 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGunNotFoundException.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 AntiAircraftGun +{ + [Serializable] + internal class AntiAircraftGunNotFoundException : ApplicationException + { + public AntiAircraftGunNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AntiAircraftGunNotFoundException() : base() { } + public AntiAircraftGunNotFoundException(string message) : base(message) { } + public AntiAircraftGunNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AntiAircraftGunNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AntiAircraftGun/AntiAircraftGun/FormMapWithSetAntiAircraftGuns.cs b/AntiAircraftGun/AntiAircraftGun/FormMapWithSetAntiAircraftGuns.cs index f8af888..dfd7d50 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormMapWithSetAntiAircraftGuns.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormMapWithSetAntiAircraftGuns.cs @@ -1,9 +1,12 @@ -using System; +using Microsoft.Extensions.Logging; +using Serilog.Filters; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; +using System.Reflection.PortableExecutable; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; @@ -24,11 +27,16 @@ namespace AntiAircraftGun /// Объект от коллекции карт /// private readonly MapsCollection _mapsCollection; + /// + /// Логер + /// + private readonly ILogger _logger; /// Конструктор /// - public FormMapWithSetAntiAircraftGuns() + public FormMapWithSetAntiAircraftGuns(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -66,15 +74,18 @@ namespace AntiAircraftGun 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.LogInformation($"Попытка добавить несуществующую карту: {textBoxNewMapName.Text}"); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -84,6 +95,7 @@ namespace AntiAircraftGun private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } /// /// Удаление карты @@ -94,12 +106,14 @@ namespace AntiAircraftGun { if (listBoxMaps.SelectedIndex == -1) { + _logger.LogInformation($"Попытка удалить несуществующую карту: {textBoxNewMapName.Text}"); return; } if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } } /// @@ -115,19 +129,36 @@ namespace AntiAircraftGun } private void AddAntiAircraftGun(DrawingAntiAircraftGun drawingAntiAircraftGuns) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + _logger.LogInformation($"Попытка добавления объекта на невыбранную карту"); + return; + } + if (drawingAntiAircraftGuns == null) + { + MessageBox.Show("Нужно выбрать объект перед добавлением"); + _logger.LogInformation($"Не выбран объект для добавления на карту"); + return; + } + DrawingObjectAntiAircraftGun antiAircraftGun = new DrawingObjectAntiAircraftGun(drawingAntiAircraftGuns); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + antiAircraftGun != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект {drawingAntiAircraftGuns} на карту "); + } + else + { + MessageBox.Show("Не получилось добавить объект"); + _logger.LogInformation($"Не получилось добавить объект {drawingAntiAircraftGuns} на карту "); + } } - DrawingObjectAntiAircraftGun antiAircraftGun = new DrawingObjectAntiAircraftGun(drawingAntiAircraftGuns); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + antiAircraftGun != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Object added"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else - { - MessageBox.Show("Cant add object"); + _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}"); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// @@ -150,14 +181,29 @@ namespace AntiAircraftGun 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(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удален объект {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Не удалось удалить объект {pos}"); + } } - else + catch (AntiAircraftGunNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Ошибка удаления: {ex.Message}"); + MessageBox.Show($"Ошибка удаления {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка {ex.Message}"); } } /// @@ -226,13 +272,16 @@ namespace AntiAircraftGun { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _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($"Ошибка сохранения в файл: {saveFileDialog.FileName}"); } } } @@ -245,14 +294,17 @@ namespace AntiAircraftGun { 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($"Ошибка загрузки из файла: {openFileDialog.FileName}"); } } } diff --git a/AntiAircraftGun/AntiAircraftGun/MapsCollection.cs b/AntiAircraftGun/AntiAircraftGun/MapsCollection.cs index 02de5e8..7db9e5c 100644 --- a/AntiAircraftGun/AntiAircraftGun/MapsCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/MapsCollection.cs @@ -78,7 +78,7 @@ namespace AntiAircraftGun /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -92,18 +92,17 @@ namespace AntiAircraftGun 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("Файл не найден"); } using (StreamReader sr = new StreamReader(filename)) { @@ -112,7 +111,7 @@ namespace AntiAircraftGun str = sr.ReadLine(); if (!str.Contains("MapsCollection")) { - return false; + throw new FileFormatException($"Неправильный формат данных в файле {filename}"); } while ((str = sr.ReadLine()) != null) { @@ -130,7 +129,6 @@ namespace AntiAircraftGun _mapStorages.Add(elem[0], new MapWithSetAntiAircraftGunsGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } - return true; } } } diff --git a/AntiAircraftGun/AntiAircraftGun/Program.cs b/AntiAircraftGun/AntiAircraftGun/Program.cs index ce76065..296ffa7 100644 --- a/AntiAircraftGun/AntiAircraftGun/Program.cs +++ b/AntiAircraftGun/AntiAircraftGun/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace AntiAircraftGun { internal static class Program @@ -11,7 +16,28 @@ namespace AntiAircraftGun // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetAntiAircraftGuns()); + 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() + .AddJsonFile("C:\\\\2 \\\\AntiAircraftGun\\AntiAircraftGun\\AntiAircraftGun\\seriLog.json") + .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/AntiAircraftGun/AntiAircraftGun/SetAntiAircraftGunsGeneric.cs b/AntiAircraftGun/AntiAircraftGun/SetAntiAircraftGunsGeneric.cs index 9807595..b5b0f68 100644 --- a/AntiAircraftGun/AntiAircraftGun/SetAntiAircraftGunsGeneric.cs +++ b/AntiAircraftGun/AntiAircraftGun/SetAntiAircraftGunsGeneric.cs @@ -1,6 +1,8 @@ -using System; +using Serilog.Filters; +using System; using System.Collections.Generic; using System.Linq; +using System.Reflection.PortableExecutable; using System.Text; using System.Threading.Tasks; @@ -38,15 +40,8 @@ namespace AntiAircraftGun /// public int Insert(T antiAircraftGun) { - if (_places.Count < _maxCount) - { - _places.Add(antiAircraftGun); - for (int i = 0; i < _places.Count; i++) - { - if (_places[i] == antiAircraftGun) return i; - } - } - return -1; + if (_places.Count < _maxCount) return Insert(antiAircraftGun, 0); + else throw new StorageOverflowException(_maxCount); } /// /// Добавление объекта в набор на конкретную позицию @@ -56,7 +51,7 @@ namespace AntiAircraftGun /// public int Insert(T antiAircraftGun, int position) { - if (position < 0 || position >= _places.Count) return -1; + if (position >= _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, antiAircraftGun); return position; } @@ -67,8 +62,8 @@ namespace AntiAircraftGun /// public T Remove(int position) { - if (position < 0 || position >= _places.Count) return null; - if (_places[position] == null) return null; + if (position >= _places.Count) throw new AntiAircraftGunNotFoundException(position); + if (_places[position] == null) throw new AntiAircraftGunNotFoundException(position); T removed = _places[position]; _places.RemoveAt(position); return removed; diff --git a/AntiAircraftGun/AntiAircraftGun/StorageOverflowException.cs b/AntiAircraftGun/AntiAircraftGun/StorageOverflowException.cs new file mode 100644 index 0000000..ebeb2d7 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/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 AntiAircraftGun +{ + [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/AntiAircraftGun/AntiAircraftGun/seriLog.json b/AntiAircraftGun/AntiAircraftGun/seriLog.json new file mode 100644 index 0000000..15f0b39 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/seriLog.json @@ -0,0 +1,12 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "C:\\Университет\\2 курс\\РПП\\AntiAircraftGun\\AntiAircraftGun\\AntiAircraftGun\\bin\\Debug\\net6.0-windows\\Log.txt" } + } + ] + } +}