From 650d8d25636be3c1a368b36b8190be4ca1dc429b Mon Sep 17 00:00:00 2001 From: marusya Date: Tue, 28 Nov 2023 22:27:59 +0400 Subject: [PATCH] lab7 --- ...ormSelfPropelledArtilleryUnitCollection.cs | 73 ++++++++++++------- .../SelfPropelledArtilleryUnit/Program.cs | 31 ++++++-- .../SelfPropelledArtilleryUnit.csproj | 5 ++ .../StorageOverflowException.cs | 18 +++++ .../UstaGenericStorage.cs | 32 ++++---- .../UstaNotFoundException.cs | 19 +++++ 6 files changed, 133 insertions(+), 45 deletions(-) create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs create mode 100644 SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.cs diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs index 8858335..ca25c3b 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs @@ -3,6 +3,7 @@ using SelfPropelledArtilleryUnit.DrawningObjects; using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Generics; using SelfPropelledArtilleryUnit.MovementStrategy; +using Microsoft.Extensions.Logging; @@ -18,9 +19,13 @@ namespace SelfPropelledArtilleryUnit /// private readonly UstaGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormSelfPropelledArtilleryUnitCollection() + public FormSelfPropelledArtilleryUnitCollection(ILogger logger) { InitializeComponent(); _storage = new UstaGenericStorage(pictureBoxCollection.Width, @@ -59,10 +64,13 @@ namespace SelfPropelledArtilleryUnit { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}"); + } /// /// Выбор набора @@ -84,14 +92,18 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); + } } /// @@ -110,21 +122,24 @@ namespace SelfPropelledArtilleryUnit formSelfPropelledArtilleryUnitConfig.AddEvent(usta => { - if (listBoxStorage.SelectedIndex != -1) + var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { - var obj = _storage[listBoxStorage.SelectedItem?.ToString() ?? string.Empty]; - if (obj != null) - { - if (obj + usta != 1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowUsta(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + usta; + + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowUsta(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorage.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorage.SelectedItem.ToString()}"); } }); @@ -141,6 +156,7 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? @@ -159,10 +175,13 @@ namespace SelfPropelledArtilleryUnit { MessageBox.Show("Объект удален"); pictureBoxCollection.Image = obj.ShowUsta(); + _logger.LogInformation($"Удален объект из набора {listBoxStorage.SelectedItem.ToString()}"); } else { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}"); + } } /// @@ -195,15 +214,16 @@ namespace SelfPropelledArtilleryUnit { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.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}"); } } } @@ -216,14 +236,17 @@ namespace SelfPropelledArtilleryUnit { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Данные успешно загружены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs index 6bdd353..7c7cde6 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs @@ -1,19 +1,38 @@ using SelfPropelledArtilleryUnit; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; namespace ProjectUsta { + internal static class Program { - /// - /// The main entry point for the application. - /// [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); - Application.Run(new FormSelfPropelledArtilleryUnitCollection()); + 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); + option.AddNLog("nlog.config"); + }); + + } } } \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj index b57c89e..cee80ce 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj @@ -8,4 +8,9 @@ enable + + + + + \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs new file mode 100644 index 0000000..d301e34 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.Exceptions +{ + [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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs index 1844c98..a9b4140 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs @@ -6,6 +6,8 @@ using System.Text; using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.MovementStrategy; using SelfPropelledArtilleryUnit.DrawningObjects; +using SelfPropelledArtilleryUnit.Exceptions; + namespace SelfPropelledArtilleryUnit.Generics { @@ -100,7 +102,7 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -118,15 +120,14 @@ namespace SelfPropelledArtilleryUnit.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.Write($"UstaStorage{Environment.NewLine}{data}"); + writer.Write(data.ToString()); } - - return true; } /// @@ -134,11 +135,11 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) @@ -146,11 +147,11 @@ namespace SelfPropelledArtilleryUnit.Generics string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!cheker.StartsWith("UstaStorage")) { - return false; + throw new Exception("Неверный формат ввода"); } _ustaStorages.Clear(); string strs; @@ -159,11 +160,11 @@ namespace SelfPropelledArtilleryUnit.Generics { if (strs == null && firstinit) { - return false; + throw new Exception("Нет данных для загрузки"); } if (strs == null) { - return false; + break; } firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; @@ -174,16 +175,19 @@ namespace SelfPropelledArtilleryUnit.Generics data?.CreateDrawningUsta(_separatorForObject, _pictureWidth, _pictureHeight); if (usta != null) { - int? result = collection + usta; - if (result == null || result.Value == -1) + try { _ = collection + usta; } + catch (UstaNotFoundException e) { - return false; + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } _ustaStorages.Add(name, collection); } - return true; } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.cs new file mode 100644 index 0000000..534e3a7 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.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 SelfPropelledArtilleryUnit.Exceptions +{ + [Serializable] internal class UstaNotFoundException : ApplicationException + { + public UstaNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public UstaNotFoundException() : base() { } + public UstaNotFoundException(string message) : base(message) { } + public UstaNotFoundException(string message, Exception exception) : base(message, exception) { } + protected UstaNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} +