diff --git a/WarmlyShip/WarmlyShip/FormMapWithSetShip.cs b/WarmlyShip/WarmlyShip/FormMapWithSetShip.cs index ee87e04..6261fb6 100644 --- a/WarmlyShip/WarmlyShip/FormMapWithSetShip.cs +++ b/WarmlyShip/WarmlyShip/FormMapWithSetShip.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -23,9 +24,12 @@ namespace WarmlyShip private readonly MapsCollection _mapsCollection; - public FormMapWithSetShip() + private readonly ILogger _logger; + + public FormMapWithSetShip(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -66,6 +70,7 @@ namespace WarmlyShip } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) @@ -81,9 +86,9 @@ namespace WarmlyShip } if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? - string.Empty); + _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } } @@ -100,15 +105,24 @@ namespace WarmlyShip { return; } - - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) > -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) > -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект: {ship} на карте: {listBoxMaps.SelectedItem}"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Ошибка переполнения при добавлении объекта: {ex.Message}"); + MessageBox.Show($"Ошибка переполнения: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка при добавлении объекта: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -127,15 +141,29 @@ namespace WarmlyShip 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(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удален объект с позиции: [{pos}] на карте: {listBoxMaps.SelectedItem}"); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Ошибка при удалении объекта на позиции: {ex.Message}"); + MessageBox.Show($"Ошибка удаления: {ex.Message} "); + } + catch (StorageOverflowException ex) + { + _logger.LogWarning($"Ошибка при удалении объекта на позиции: {ex.Message}"); + MessageBox.Show($"Превышение размерности: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка при удалении объекта на позиции: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message} "); } } @@ -146,6 +174,7 @@ namespace WarmlyShip return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход в хранилище: {listBoxMaps.SelectedItem}"); } private void ButtonShowOnMap_Click(object sender, EventArgs e) @@ -155,6 +184,7 @@ namespace WarmlyShip return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap(); + _logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem}"); } private void ButtonMove_Click(object sender, EventArgs e) @@ -188,13 +218,16 @@ namespace WarmlyShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation($"Карта успешно сохранена в файл: {saveFileDialog.FileName}"); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не сохранилось в файл: {saveFileDialog.FileName}"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -203,14 +236,17 @@ namespace WarmlyShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation($"Карта успешно загружена из файла: {openFileDialog.FileName}"); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не загрузилось из файла: {openFileDialog.FileName}"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/WarmlyShip/WarmlyShip/MapsCollection.cs b/WarmlyShip/WarmlyShip/MapsCollection.cs index 503080b..f642942 100644 --- a/WarmlyShip/WarmlyShip/MapsCollection.cs +++ b/WarmlyShip/WarmlyShip/MapsCollection.cs @@ -50,7 +50,7 @@ namespace WarmlyShip } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -65,14 +65,13 @@ namespace WarmlyShip sw.Write($"{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 FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -84,7 +83,7 @@ namespace WarmlyShip { if (!bufferStr.Contains("MapsCollection")) { - return false; + throw new FormatException("Формат данных в файле не правильный"); } else { @@ -113,7 +112,6 @@ namespace WarmlyShip } } } - return true; } } } diff --git a/WarmlyShip/WarmlyShip/Program.cs b/WarmlyShip/WarmlyShip/Program.cs index de3a3a8..ef09eae 100644 --- a/WarmlyShip/WarmlyShip/Program.cs +++ b/WarmlyShip/WarmlyShip/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace WarmlyShip { internal static class Program @@ -11,7 +16,31 @@ namespace WarmlyShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetShip()); - } - } + 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: "serilogConfig.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/WarmlyShip/WarmlyShip/SetShipGeneric.cs b/WarmlyShip/WarmlyShip/SetShipGeneric.cs index 7d336d8..8a37607 100644 --- a/WarmlyShip/WarmlyShip/SetShipGeneric.cs +++ b/WarmlyShip/WarmlyShip/SetShipGeneric.cs @@ -27,15 +27,16 @@ namespace WarmlyShip public int Insert(T ship, int position) { - if (position < 0 || position > Count || Count == _maxCount) return -1; + if (position < 0 || position > Count || Count == _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, ship); return position; } public T Remove(int position) { + if (position >= _maxCount || position >= _places.Count) throw new ShipNotFoundException(position); T DelElement = _places[position]; - _places[position] = null; + _places.Remove(DelElement); return DelElement; } diff --git a/WarmlyShip/WarmlyShip/ShipDelegate.cs b/WarmlyShip/WarmlyShip/ShipDelegate.cs deleted file mode 100644 index c80372b..0000000 --- a/WarmlyShip/WarmlyShip/ShipDelegate.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WarmlyShip -{ - public delegate void ShipDelegate(DrawingWarmlyShip warmlyShip); -} diff --git a/WarmlyShip/WarmlyShip/ShipNotFoundException.cs b/WarmlyShip/WarmlyShip/ShipNotFoundException.cs new file mode 100644 index 0000000..528b699 --- /dev/null +++ b/WarmlyShip/WarmlyShip/ShipNotFoundException.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 WarmlyShip +{ + [Serializable] + internal class ShipNotFoundException : Exception + { + public ShipNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public ShipNotFoundException() : base() { } + public ShipNotFoundException(string message) : base(message) { } + public ShipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/WarmlyShip/WarmlyShip/StorageOverflowException.cs b/WarmlyShip/WarmlyShip/StorageOverflowException.cs new file mode 100644 index 0000000..e6c922a --- /dev/null +++ b/WarmlyShip/WarmlyShip/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 WarmlyShip +{ + [Serializable] + internal class StorageOverflowException : Exception + { + 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/WarmlyShip/WarmlyShip/WarmlyShip.csproj b/WarmlyShip/WarmlyShip/WarmlyShip.csproj index 13ee123..62b17eb 100644 --- a/WarmlyShip/WarmlyShip/WarmlyShip.csproj +++ b/WarmlyShip/WarmlyShip/WarmlyShip.csproj @@ -8,6 +8,30 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + + True diff --git a/WarmlyShip/WarmlyShip/serilogConfig.json b/WarmlyShip/WarmlyShip/serilogConfig.json new file mode 100644 index 0000000..3825ce1 --- /dev/null +++ b/WarmlyShip/WarmlyShip/serilogConfig.json @@ -0,0 +1,16 @@ +{ + "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}" + } + } + ] + } +} \ No newline at end of file