diff --git a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/BoatNotFoundException.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/BoatNotFoundException.cs new file mode 100644 index 0000000..3717595 --- /dev/null +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/BoatNotFoundException.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 PIbd_22_Kalyshev_Y_V_MotorBoat_Base +{ + [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/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/FormMapWithSetBoats.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/FormMapWithSetBoats.cs index 0732c8a..34fcc89 100644 --- a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/FormMapWithSetBoats.cs +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/FormMapWithSetBoats.cs @@ -1,4 +1,5 @@ -using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; using static System.Windows.Forms.DataFormats; namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base @@ -18,11 +19,16 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base /// private readonly MapsCollection _mapsCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetBoats() + public FormMapWithSetBoats(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -68,6 +74,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -93,6 +100,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem}"); } } /// @@ -114,15 +122,30 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base return; } DrawningObjectBoat boat = new DrawningObjectBoat(drawingBoats); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1) + try { - MessageBox.Show("Object added"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"В карту {listBoxMaps.SelectedItem} добавлен объект {boat.GetInfo()}"); + } + else + { + MessageBox.Show("Невозможно добавить объект"); + _logger.LogInformation($"Невозможно добавить объект {boat.GetInfo()} в карту {listBoxMaps.SelectedItem}"); + } + } catch (StorageOverflowException ex) { - MessageBox.Show("Cant add object"); + MessageBox.Show($"Ошибка добавления: {ex.Message}"); + _logger.LogWarning($"Ошибка добавления: {ex.Message}"); } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + } + } /// /// Удаление объекта @@ -144,14 +167,28 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base 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(); - } - else + IDrawningObject boat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (boat != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Из карты {listBoxMaps.SelectedItem} удален объект {boat.GetInfo()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Невозможно удалить объект {boat.GetInfo()} в карту {listBoxMaps.SelectedItem}"); + } + } catch (BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.LogWarning($"Ошибка удаления: {ex.Message}"); + } catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); } } /// @@ -166,6 +203,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Показана гавань для карты {listBoxMaps.SelectedItem}"); } /// /// Вывод карты @@ -179,6 +217,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap(); + _logger.LogInformation($"Показана карта {listBoxMaps.SelectedItem}"); } /// /// Перемещение @@ -221,13 +260,15 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else + _logger.LogInformation($"Сохранен файл {saveFileDialog.FileName}"); + } catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не сохранилось: {ex.Message}"); } } } @@ -240,14 +281,16 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else + _logger.LogInformation($"Загружен файл {openFileDialog.FileName}"); + } catch (Exception ex) { MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не загрузилось: {ex.Message}"); } } } diff --git a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/MapsCollection.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/MapsCollection.cs index 21d785c..b7ae631 100644 --- a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/MapsCollection.cs +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/MapsCollection.cs @@ -94,7 +94,7 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -103,36 +103,35 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base using (FileStream fs = new(filename, FileMode.Create)) using (StreamWriter sw = new StreamWriter(fs)) { - sw.WriteLine($"MapsCollection{Environment.NewLine}"); + sw.WriteLine($"MapsCollection"); foreach (var storage in _mapStorages) { sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// /// Загрузка нформации по автомобилям на парковках из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader sr = new StreamReader(filename)) { string str; int count = 0; - while ((str = sr.ReadLine()) != null) + while ((str = sr.ReadLine()) != null && str != "") { if (count == 0) { if (!str.Contains("MapsCollection")) { - return false; + throw new Exception("Формат данных в файле не правильный"); } else { count++; @@ -154,7 +153,6 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base _mapStorages.Add(elem[0], new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } - return true; } } } diff --git a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/PIbd-22_Kalyshev_Y_V_MotorBoat_Base.csproj b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/PIbd-22_Kalyshev_Y_V_MotorBoat_Base.csproj index b53c66d..d422f99 100644 --- a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/PIbd-22_Kalyshev_Y_V_MotorBoat_Base.csproj +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/PIbd-22_Kalyshev_Y_V_MotorBoat_Base.csproj @@ -9,4 +9,26 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/Program.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/Program.cs index 1ab4654..baf31e3 100644 --- a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/Program.cs +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base { internal static class Program @@ -11,7 +16,31 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetBoats()); + 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() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serialog.json", optional: false, reloadOnChange: true) + .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/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/SetBoatsGeneric.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/SetBoatsGeneric.cs index 7cb6845..1c0f397 100644 --- a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/SetBoatsGeneric.cs +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/SetBoatsGeneric.cs @@ -55,14 +55,17 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base /// Добавляемый автомобиль /// Позиция /// - public bool Insert(T boat, int position) + public void Insert(T boat, int position) { - if (position < 0 || position > _places.Count) + if (_places.Count < _maxCount) { - return false; + if (position < 0 || position > _places.Count) + { + throw new StorageOverflowException(); + } + _places.Insert(position, boat); } - _places.Insert(position, boat); - return true; + return; } /// /// Удаление объекта из набора с конкретной позиции @@ -73,11 +76,11 @@ namespace PIbd_22_Kalyshev_Y_V_MotorBoat_Base { if (position < 0 || position > _places.Count) { - return null; + throw new BoatNotFoundException(position); } if (_places[position] == null) { - return null; + throw new BoatNotFoundException(position); } T removed = _places[position]; _places.RemoveAt(position); diff --git a/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/StorageOverflowException.cs b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/StorageOverflowException.cs new file mode 100644 index 0000000..d92d09a --- /dev/null +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/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 PIbd_22_Kalyshev_Y_V_MotorBoat_Base +{ + [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/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/serialog.json b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/serialog.json new file mode 100644 index 0000000..d4cda71 --- /dev/null +++ b/PIbd-22_Kalyshev_Y_V_MotorBoat_Base/serialog.json @@ -0,0 +1,48 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "{Message:lj}: [{Level:u4}]{Timestamp:HH:mm:ss.fff}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Destructure": [ + { + "Name": "ByTransforming", + "Args": { + "returnType": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base.EntityBoat", + "transformation": "r => new {r.Speed, r.Weight, BodyColor = r.BodyColor.Name }" + } + }, + { + "Name": "ByTransforming", + "Args": { + "returnType": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base.EntitySpeedboat", + "transformation": "r => new {r.Speed, r.Weight, BodyColor = r.BodyColor.Name, DopColor = r.DopColor.Name, r.bodyKit, r.wing, r.sportLine }" + } + }, + { + "Name": "ToMaximumDepth", + "Args": { "maximumDestructuringDepth": 4 } + }, + { + "Name": "ToMaximumStringLength", + "Args": { "maximumStringLength": 100 } + }, + { + "Name": "ToMaximumCollectionCount", + "Args": { "maximumCollectionCount": 10 } + } + ], + "Properties": { + "Application": "PIbd_22_Kalyshev_Y_V_MotorBoat_Base" + } + } +} \ No newline at end of file diff --git a/ok.txt b/ok.txt deleted file mode 100644 index 6f43650..0000000 --- a/ok.txt +++ /dev/null @@ -1,2 +0,0 @@ -MapsCollection -ok|SimpleMap|100:100:Blue;100:100:Yellow:Blue:False:True:True;