From e1baef291cd8c6c44eb6594a37aab028fd76443b Mon Sep 17 00:00:00 2001 From: Kirill <117719052+KirillFirsof@users.noreply.github.com> Date: Mon, 25 Dec 2023 23:41:28 +0400 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=BA=D0=BE=D0=BD=D1=87=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D1=83=20=D1=81=20=D0=BB?= =?UTF-8?q?=D0=BE=D0=B3=D0=B3=D0=B5=D1=80=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormTractorCollection.cs | 60 +++++++++++++------ .../RPP_FirstLaba_Tractor/Program.cs | 24 +++++++- .../ProjectTractor.csproj | 5 ++ .../Properties/Resources.resx | 1 + .../StorageOverflowException.cs | 22 +++++++ .../TractorNotFoundException.cs | 23 +++++++ .../TractorsGenericStorage.cs | 11 ++-- .../RPP_FirstLaba_Tractor/nlog.config | 14 +++++ 8 files changed, 136 insertions(+), 24 deletions(-) create mode 100644 RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/StorageOverflowException.cs create mode 100644 RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorNotFoundException.cs create mode 100644 RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/nlog.config diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs index 2a60f57..9a82ed0 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/FormTractorCollection.cs @@ -7,9 +7,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using ProjectTractor.DrawningObjects; using ProjectTractor.Generics; using ProjectTractor.MovementStrategy; +using ProjectTractor.Exceptions; namespace ProjectTractor { @@ -19,15 +21,22 @@ namespace ProjectTractor /// /// Набор объектов /// + /// private readonly TractorsGenericStorage _storage; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormTractorCollection() + public FormTractorCollection(ILogger logger) { InitializeComponent(); _storage = new TractorsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -67,6 +76,7 @@ namespace ProjectTractor } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text}"); } /// /// Выбор набора @@ -90,11 +100,14 @@ namespace ProjectTractor { return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? + string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); - listBoxStorages.SelectedItems.Clear(); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -157,15 +170,23 @@ namespace ProjectTractor return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowTractors(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowTractors(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (TractorNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); } + } /// /// Обновление рисунка по набору @@ -195,16 +216,18 @@ namespace ProjectTractor { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } + } } /// @@ -216,19 +239,22 @@ namespace ProjectTractor { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка прошла успешно:"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } + ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось загрузить", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Program.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Program.cs index 56558ed..95fe589 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Program.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Program.cs @@ -1,9 +1,13 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace ProjectTractor { internal static class Program { /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] static void Main() @@ -11,7 +15,23 @@ namespace ProjectTractor // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTractorCollection()); + 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/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/ProjectTractor.csproj b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/ProjectTractor.csproj index 13ee123..028d1c0 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/ProjectTractor.csproj +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/ProjectTractor.csproj @@ -8,6 +8,11 @@ enable + + + + + True diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Properties/Resources.resx b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Properties/Resources.resx index 55894d3..d006c3d 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Properties/Resources.resx +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/Properties/Resources.resx @@ -59,6 +59,7 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> + diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/StorageOverflowException.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/StorageOverflowException.cs new file mode 100644 index 0000000..73304c6 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/StorageOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace ProjectTractor.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/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorNotFoundException.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorNotFoundException.cs new file mode 100644 index 0000000..e8250f4 --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorNotFoundException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace ProjectTractor.Exceptions +{ + [Serializable] + internal class TractorNotFoundException : ApplicationException + { + public TractorNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public TractorNotFoundException() : base() { } + public TractorNotFoundException(string message) : base(message) { } + public TractorNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected TractorNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } + +} diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs index d71695f..778563b 100644 --- a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/TractorsGenericStorage.cs @@ -114,7 +114,7 @@ namespace ProjectTractor } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter streamWriter = new(filename)) { @@ -131,7 +131,7 @@ namespace ProjectTractor { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader streamReader = new(filename)) { @@ -139,11 +139,12 @@ namespace ProjectTractor string[] strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strings == null || strings.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!strings[0].StartsWith("TractorStorage")) { - return false; + //если нет такой записи, то это не те данные + throw new Exception("Неверный формат данных"); } _tractorStorages.Clear(); do @@ -163,7 +164,7 @@ namespace ProjectTractor { if (!(collection + tractor)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } diff --git a/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/nlog.config b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/nlog.config new file mode 100644 index 0000000..249507c --- /dev/null +++ b/RPP_FirstLaba_Tractor/RPP_FirstLaba_Tractor/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file