From 4b736d32334c5711eda4e6cf3c0099c1581ff9eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=AF=D0=BA=D0=BE?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=B2?= Date: Wed, 6 Dec 2023 22:19:11 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=207=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Exceptions/BoatNotFoundException.cs | 23 ++++++ .../Exceptions/StorageOverflowException.cs | 23 ++++++ SailBoat/SailBoat/FormBoatCollection.cs | 76 ++++++++++++++----- .../Generics/BoatsGenericCollection.cs | 9 +-- .../SailBoat/Generics/BoatsGenericStorage.cs | 20 ++--- SailBoat/SailBoat/Generics/SetGeneric.cs | 18 +++-- SailBoat/SailBoat/Program.cs | 32 +++++++- SailBoat/SailBoat/SailBoat.csproj | 28 +++++++ SailBoat/SailBoat/appsettings.json | 20 +++++ 9 files changed, 205 insertions(+), 44 deletions(-) create mode 100644 SailBoat/SailBoat/Exceptions/BoatNotFoundException.cs create mode 100644 SailBoat/SailBoat/Exceptions/StorageOverflowException.cs create mode 100644 SailBoat/SailBoat/appsettings.json diff --git a/SailBoat/SailBoat/Exceptions/BoatNotFoundException.cs b/SailBoat/SailBoat/Exceptions/BoatNotFoundException.cs new file mode 100644 index 0000000..908c312 --- /dev/null +++ b/SailBoat/SailBoat/Exceptions/BoatNotFoundException.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 SailBoat.Exceptions +{ + [Serializable] + internal class BoatNotFoundException : ApplicationException + { + public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + + public BoatNotFoundException() : base() { } + + public BoatNotFoundException(string message) : base(message) { } + + public BoatNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected BoatNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/SailBoat/SailBoat/Exceptions/StorageOverflowException.cs b/SailBoat/SailBoat/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..ba9f991 --- /dev/null +++ b/SailBoat/SailBoat/Exceptions/StorageOverflowException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace SailBoat.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 context) : base(info, context) { } + } +} diff --git a/SailBoat/SailBoat/FormBoatCollection.cs b/SailBoat/SailBoat/FormBoatCollection.cs index 64ee472..e7f3c3a 100644 --- a/SailBoat/SailBoat/FormBoatCollection.cs +++ b/SailBoat/SailBoat/FormBoatCollection.cs @@ -10,6 +10,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using SailBoat.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace SailBoat { @@ -17,10 +20,13 @@ namespace SailBoat { private readonly BoatsGenericStorage _storage; - public FormBoatCollection() + private readonly ILogger _logger; + + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() @@ -48,10 +54,12 @@ namespace SailBoat if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"!!Ошибка!! Не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e) @@ -63,12 +71,15 @@ namespace SailBoat { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Удаление не выбранного набора"); return; } + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -78,16 +89,27 @@ namespace SailBoat boat._pictureHeight = pictureBoxCollection.Height; if (listBoxStorages.SelectedIndex == -1) return; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (obj == null) return; - if (obj + boat) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowBoats(); + + if (obj + boat) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"В набор {name} добавлен объект"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - else - { - MessageBox.Show("Не удалось добавить объект"); + catch(StorageOverflowException ex) { + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось добавить объект"); } } @@ -106,6 +128,7 @@ namespace SailBoat { if (listBoxStorages.SelectedIndex == -1) return; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (obj == null) return; if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) @@ -114,14 +137,23 @@ namespace SailBoat } if (maskedTextBoxNumber.Text == "") { return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBoats(); - } - else + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"Из набора {name} удален объект"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Не удалось удалить объект"); + } + } catch(BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message}. Не удалось удалить объект"); } } @@ -137,13 +169,16 @@ namespace SailBoat { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение"); } - else + catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка сохранения"); } } } @@ -152,14 +187,17 @@ namespace SailBoat { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка"); } - else + catch(Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка загрузки"); } } } diff --git a/SailBoat/SailBoat/Generics/BoatsGenericCollection.cs b/SailBoat/SailBoat/Generics/BoatsGenericCollection.cs index 11462d0..0d56e6a 100644 --- a/SailBoat/SailBoat/Generics/BoatsGenericCollection.cs +++ b/SailBoat/SailBoat/Generics/BoatsGenericCollection.cs @@ -38,16 +38,13 @@ namespace SailBoat.Generics return collect._collection.Insert(obj); } - public static bool operator -(BoatsGenericCollection collect, int pos) + public static T? operator -(BoatsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if(obj == null) - { - return false; - } + collect._collection.Remove(pos); - return true; + return obj; } public U? GetU(int pos) { diff --git a/SailBoat/SailBoat/Generics/BoatsGenericStorage.cs b/SailBoat/SailBoat/Generics/BoatsGenericStorage.cs index 0eac25c..35f5575 100644 --- a/SailBoat/SailBoat/Generics/BoatsGenericStorage.cs +++ b/SailBoat/SailBoat/Generics/BoatsGenericStorage.cs @@ -75,7 +75,7 @@ namespace SailBoat.Generics if (data.Length == 0) { - return false; + throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения"); } using StreamWriter fs = new StreamWriter(filename); @@ -88,25 +88,25 @@ namespace SailBoat.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader fs = new StreamReader(filename)) { string str = fs.ReadLine(); + + if(str == null || str.Length == 0) + { + throw new NullReferenceException("Нет данных для загрузки"); + } + if (!str.StartsWith("BoatStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _boatStorages.Clear(); while ((str = fs.ReadLine()) != null) { - if (str.Length == 0) - { - return false; - } - - string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { @@ -122,7 +122,7 @@ namespace SailBoat.Generics { if (!(collection + boat)) { - return false; + throw new ApplicationException("Ошибка добавления в коллекцию"); } } } diff --git a/SailBoat/SailBoat/Generics/SetGeneric.cs b/SailBoat/SailBoat/Generics/SetGeneric.cs index 342a315..8a3deaf 100644 --- a/SailBoat/SailBoat/Generics/SetGeneric.cs +++ b/SailBoat/SailBoat/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using SailBoat.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -30,11 +31,11 @@ namespace SailBoat.Generics { if (position < 0 || position >= _maxCount) { - return false; + throw new BoatNotFoundException(position); } if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } _places.Insert(position, boat); return true; @@ -46,11 +47,12 @@ namespace SailBoat.Generics { return false; } - if (Count >= _maxCount) + if (_places[position] == null) { - return false; + throw new BoatNotFoundException(position); } - _places.RemoveAt(position); + + _places[position] = null; return true; } @@ -58,12 +60,12 @@ namespace SailBoat.Generics { get { - if (position < 0 || position > _maxCount) { return null; } + if (position < 0 || position >= Count) { return null; } return _places[position]; } set { - if (position < 0 || position > _maxCount) { return; } + if (position < 0 || position >= Count) { return; } _places[position] = value; } } diff --git a/SailBoat/SailBoat/Program.cs b/SailBoat/SailBoat/Program.cs index 00690c9..118c2a8 100644 --- a/SailBoat/SailBoat/Program.cs +++ b/SailBoat/SailBoat/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; +using System.IO; +using System.Windows.Forms; + namespace SailBoat { internal static class Program @@ -11,7 +19,29 @@ namespace SailBoat // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(IServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string appPath = ""; + for (int i = 0; i < path.Length - 3; i++) + { + appPath += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.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/SailBoat/SailBoat/SailBoat.csproj b/SailBoat/SailBoat/SailBoat.csproj index 13ee123..bc59893 100644 --- a/SailBoat/SailBoat/SailBoat.csproj +++ b/SailBoat/SailBoat/SailBoat.csproj @@ -8,6 +8,34 @@ enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + True diff --git a/SailBoat/SailBoat/appsettings.json b/SailBoat/SailBoat/appsettings.json new file mode 100644 index 0000000..e7c5a5b --- /dev/null +++ b/SailBoat/SailBoat/appsettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "logs/boatlog-.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Loco" + } + } +} \ No newline at end of file