diff --git a/speed_Boat/speed_Boat/BoatNotFoundException.cs b/speed_Boat/speed_Boat/BoatNotFoundException.cs new file mode 100644 index 0000000..93c0228 --- /dev/null +++ b/speed_Boat/speed_Boat/BoatNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace speed_Boat.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 contex) : base(info, contex) { } + } +} diff --git a/speed_Boat/speed_Boat/BoatsGenericCollection.cs b/speed_Boat/speed_Boat/BoatsGenericCollection.cs index 6ad0924..e1b1730 100644 --- a/speed_Boat/speed_Boat/BoatsGenericCollection.cs +++ b/speed_Boat/speed_Boat/BoatsGenericCollection.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using SpeedBoatLab.Drawings; using speed_Boat.MovementStrategy; using System.Drawing; -using System.IO; namespace speed_Boat.Generics { @@ -53,13 +52,13 @@ namespace speed_Boat.Generics /// Перегрузка оператора сложения /// /// - public static bool operator + (BoatsGenericCollection collect, T? obj) + public static int operator + (BoatsGenericCollection collect, T? obj) { - if (obj == null) + if (obj != null) { - return false; + return collect?._collection.Insert(obj) ?? -1; } - return collect?._collection.Insert(obj) ?? false; + return 0; } /// /// Перегрузка оператора вычитания diff --git a/speed_Boat/speed_Boat/BoatsGenericStorage.cs b/speed_Boat/speed_Boat/BoatsGenericStorage.cs index f0d7b88..0bf67c2 100644 --- a/speed_Boat/speed_Boat/BoatsGenericStorage.cs +++ b/speed_Boat/speed_Boat/BoatsGenericStorage.cs @@ -1,4 +1,5 @@ -using speed_Boat.MovementStrategy; +using speed_Boat.Exceptions; +using speed_Boat.MovementStrategy; using SpeedBoatLab.Drawings; using System; using System.Collections.Generic; @@ -52,7 +53,7 @@ namespace speed_Boat.Generics { _boatStorages = new Dictionary>(); _pictureWidth = pictureWidth; - _pictureHeight = pictureHeight; + _pictureHeight = pictureHeight; } /// @@ -60,8 +61,11 @@ namespace speed_Boat.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { + if (_boatStorages.Count == 0) + throw new InvalidOperationException("Невалидная операция: нет данных для сохранения"); + if (File.Exists(filename)) { File.Delete(filename); @@ -76,41 +80,35 @@ namespace speed_Boat.Generics } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } - if (data.Length == 0) + if(data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } - - using (StreamWriter sw = new (filename)) + using (StreamWriter sw = new(filename)) { sw.WriteLine($"BoatStorage{Environment.NewLine}{data}"); } - return true; } /// /// Загрузка информации по катерам в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) - { - return false; - } - string bufferTextFromFile = ""; + throw new FileNotFoundException("Файл не найден"); + using (StreamReader sr = new(filename)) { + if (sr.ReadLine() != "BoatStorage") + throw new FormatException("Неверный формат данных"); + string str = sr.ReadLine(); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; - } - if (!strs[0].StartsWith("BoatStorage")) - { - //если нет такой записи, то это не те данные - return false; + throw new Exception("Нет данных для загрузки"); } _boatStorages.Clear(); do @@ -130,9 +128,14 @@ namespace speed_Boat.Generics DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight); if (boat != null) { - if (!(collection + boat)) + try { _ = collection + boat; } + catch (BoatNotFoundException e) { - return false; + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } @@ -140,7 +143,6 @@ namespace speed_Boat.Generics str = sr.ReadLine(); } while (str != null); } - return true; } @@ -176,15 +178,15 @@ namespace speed_Boat.Generics /// /// /// - public BoatsGenericCollection?this[string ind] + public BoatsGenericCollection? this[string ind] { get { BoatsGenericCollection boat; //проверка есть ли в словаре обьект с ключом ind if (_boatStorages.TryGetValue(ind, out boat)) - { - return boat; + { + return boat; } return null; } diff --git a/speed_Boat/speed_Boat/FormBoatCollection.cs b/speed_Boat/speed_Boat/FormBoatCollection.cs index 3feaea5..a00d935 100644 --- a/speed_Boat/speed_Boat/FormBoatCollection.cs +++ b/speed_Boat/speed_Boat/FormBoatCollection.cs @@ -11,6 +11,8 @@ using SpeedBoatLab.Drawings; using speed_Boat.Generics; using speed_Boat.MovementStrategy; using speed_Boat; +using Microsoft.Extensions.Logging; +using speed_Boat.Exceptions; namespace SpeedBoatLab { @@ -20,13 +22,21 @@ namespace SpeedBoatLab /// Набор объектов /// private readonly BoatsGenericStorage _storage; + + /// + /// Логгер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBoatCollection() + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; + } /// /// Заполнение collectionsListBox @@ -64,10 +74,13 @@ namespace SpeedBoatLab { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(nameStorageTextBox.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{nameStorageTextBox.Text}"); + } /// /// Выбор набора @@ -84,13 +97,18 @@ namespace SpeedBoatLab { if (storagesListBox.SelectedIndex == -1) { + _logger.LogWarning("Набор для удаления не выбран"); return; } + string name = storagesListBox.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {storagesListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(storagesListBox.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); + } } @@ -102,6 +120,11 @@ namespace SpeedBoatLab /// private void ButtonAddBoat_Click(object sender, EventArgs e) { + if (storagesListBox.SelectedIndex == -1) + { + _logger.LogWarning("Набор для добавления обьекта не выбран"); + return; + } var FormBoatConfig = new FormBoatConfig(); FormBoatConfig.AddEvent(new(AddBoat)); FormBoatConfig.Show(); @@ -111,23 +134,29 @@ namespace SpeedBoatLab { if (storagesListBox.SelectedIndex == -1) { + _logger.LogWarning("Набор для удаления не выбран"); return; } var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning("Добавление пустого обьекта"); return; } - if (obj + boat) + try { + _ = obj + boat; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект в набор {storagesListBox.SelectedItem.ToString()}"); pictureBoxCollection.Image = obj.ShowBoats(); } - else + catch(StorageOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {storagesListBox.SelectedItem.ToString()}"); } } + /// /// Удаление объекта из набора /// @@ -137,6 +166,7 @@ namespace SpeedBoatLab { if (storagesListBox.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty]; @@ -155,21 +185,34 @@ namespace SpeedBoatLab { int.TryParse(insertPosition, out pos); if (pos < 0 || pos > obj._collection.Count - 1) - MessageBox.Show("Неверный формат позиции"); - - if (obj - pos != null) { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBoats(); + MessageBox.Show("Неверный формат позиции"); + _logger.LogWarning($"Неверный формат позиции:{pos}"); + } + try + { + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBoats(); + _logger.LogInformation($"Удален объект из набора {storagesListBox.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Не удалось удалить объект из набора {storagesListBox.SelectedItem.ToString()}"); + } + } + catch(BoatNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {storagesListBox.SelectedItem.ToString()}"); } } - else if (insertPosition == string.Empty) + else if(insertPosition == string.Empty) { MessageBox.Show("Неверный формат позиции"); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Неверный формат позиции:{insertPosition}"); } } /// @@ -201,16 +244,21 @@ namespace SpeedBoatLab { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _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}"); } + } } @@ -219,16 +267,19 @@ namespace SpeedBoatLab { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(saveFileDialog.FileName)) + try { + _storage.LoadData(saveFileDialog.FileName); ReloadObjects(); - MessageBox.Show("Сохранение прошло успешно", + 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/speed_Boat/speed_Boat/GenericClass.cs b/speed_Boat/speed_Boat/GenericClass.cs index 9eea6b2..2a71f6a 100644 --- a/speed_Boat/speed_Boat/GenericClass.cs +++ b/speed_Boat/speed_Boat/GenericClass.cs @@ -5,6 +5,7 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using speed_Boat.Exceptions; namespace speed_Boat.Generics { @@ -34,12 +35,12 @@ namespace speed_Boat.Generics /// /// Добавление объекта в набор /// - public bool Insert(T boat) + public int Insert(T boat) { if(_places.Count == 0) { _places.Add(boat); - return true; + return 0; } else { @@ -52,10 +53,13 @@ namespace speed_Boat.Generics _places[i] = _places[_places.Count - 1]; _places[_places.Count - 1] = temp; } - return true; + return 0; + } + else + { + throw new StorageOverflowException(); } } - return false; } /// /// Добавление объекта в набор на конкретную позицию. @@ -87,7 +91,10 @@ namespace speed_Boat.Generics } return true; } - return false; + else + { + throw new StorageOverflowException(); + } } /// @@ -96,8 +103,12 @@ namespace speed_Boat.Generics public bool Remove(int position) { if (position < 0 || position >= Count) + { + throw new BoatNotFoundException(); + } + if (_places[position] == null) { - return false; + throw new BoatNotFoundException(); } _places[position] = null; return true; diff --git a/speed_Boat/speed_Boat/Program.cs b/speed_Boat/speed_Boat/Program.cs index 5c3bf4d..bc24dd4 100644 --- a/speed_Boat/speed_Boat/Program.cs +++ b/speed_Boat/speed_Boat/Program.cs @@ -1,23 +1,46 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using System.Windows.Forms; +using System.IO; + namespace SpeedBoatLab { static class Program { - /// - /// The main entry point for the application. - /// [STAThread] static void Main() { - Application.SetHighDpiMode(HighDpiMode.SystemAware); - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new FormBoatCollection()); + ApplicationConfiguration.Initialize(); + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build(); + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); + } } } diff --git a/speed_Boat/speed_Boat/StorageOverflowException.cs b/speed_Boat/speed_Boat/StorageOverflowException.cs new file mode 100644 index 0000000..f0a679b --- /dev/null +++ b/speed_Boat/speed_Boat/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 speed_Boat.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/speed_Boat/speed_Boat/appsettings.json b/speed_Boat/speed_Boat/appsettings.json new file mode 100644 index 0000000..93ed51a --- /dev/null +++ b/speed_Boat/speed_Boat/appsettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "speed_Boat" + } + } +} \ No newline at end of file diff --git a/speed_Boat/speed_Boat/nlog.config b/speed_Boat/speed_Boat/nlog.config new file mode 100644 index 0000000..ee75e5d --- /dev/null +++ b/speed_Boat/speed_Boat/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/speed_Boat/speed_Boat/speed_Boat.csproj b/speed_Boat/speed_Boat/speed_Boat.csproj index 2faea65..ca91c10 100644 --- a/speed_Boat/speed_Boat/speed_Boat.csproj +++ b/speed_Boat/speed_Boat/speed_Boat.csproj @@ -2,10 +2,22 @@ WinExe - net5.0-windows + net7.0-windows true + + + + + + + + + + + + True