From a8c9d45998e2b9c4645b099e495da776af487dd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B9=D0=B4=D0=B0=D1=80?= Date: Fri, 25 Nov 2022 16:43:47 +0400 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=82=D0=BE=D0=B3=D0=BE=D0=B2=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B2=D0=B0=D1=80=D0=B8=D0=B0=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Battleship/Battleship/Battleship.csproj | 24 ++++ .../Battleship/BattleshipNotFoundException.cs | 19 +++ .../Battleship/FormMapWithSetBattleship.cs | 109 +++++++++++++----- Battleship/Battleship/MapsCollection.cs | 10 +- Battleship/Battleship/Program.cs | 31 ++++- Battleship/Battleship/SetBattleshipGeneric.cs | 34 ++++-- .../Battleship/StorageOverflowException.cs | 19 +++ Battleship/Battleship/appsettings.json | 16 +++ 8 files changed, 214 insertions(+), 48 deletions(-) create mode 100644 Battleship/Battleship/BattleshipNotFoundException.cs create mode 100644 Battleship/Battleship/StorageOverflowException.cs create mode 100644 Battleship/Battleship/appsettings.json diff --git a/Battleship/Battleship/Battleship.csproj b/Battleship/Battleship/Battleship.csproj index 13ee123..2fc2cc5 100644 --- a/Battleship/Battleship/Battleship.csproj +++ b/Battleship/Battleship/Battleship.csproj @@ -8,6 +8,24 @@ enable + + + + + + + + + + + + + + + + + + True @@ -16,6 +34,12 @@ + + + Always + + + ResXFileCodeGenerator diff --git a/Battleship/Battleship/BattleshipNotFoundException.cs b/Battleship/Battleship/BattleshipNotFoundException.cs new file mode 100644 index 0000000..cc7167c --- /dev/null +++ b/Battleship/Battleship/BattleshipNotFoundException.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 Battleship +{ + [Serializable] + internal class BattleshipNotFoundException : ApplicationException + { + public BattleshipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public BattleshipNotFoundException() : base() { } + public BattleshipNotFoundException(string message) : base(message) { } + public BattleshipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected BattleshipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Battleship/Battleship/FormMapWithSetBattleship.cs b/Battleship/Battleship/FormMapWithSetBattleship.cs index 8e80590..5a244f9 100644 --- a/Battleship/Battleship/FormMapWithSetBattleship.cs +++ b/Battleship/Battleship/FormMapWithSetBattleship.cs @@ -1,9 +1,11 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; @@ -21,14 +23,18 @@ namespace Battleship private readonly MapsCollection _mapsCollection; - public FormMapWithSetBattleship() + //логер + private readonly ILogger _logger; + + public FormMapWithSetBattleship(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); - foreach (var elem in _mapDict) + foreach (var element in _mapDict) { - comboBoxSelectorMap.Items.Add(elem.Key); + comboBoxSelectorMap.Items.Add(element.Key); } } @@ -58,45 +64,76 @@ namespace Battleship private void AddBattleshipOnMap(DrawningBattleship battleship) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectBattleship(battleship) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Battleship}", battleship); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - DrawningObjectBattleship boat = new(battleship); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка, переполнение хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch (ArgumentException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Battleship}", ex.Message, battleship); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonRemoveBattleship_Click(object sender, EventArgs e) { - if (listBoxMaps.SelectedIndex == -1) + if (listBoxMaps.SelectedIndex == -1 || string.IsNullOrEmpty(maskedTextBoxPosition.Text)) { return; } - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)) - { - return; - } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, + MessageBoxIcon.Question) == DialogResult.No) { 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(); + var deletedBattleship = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + + if (deletedBattleship != null) + { + MessageBox.Show("Объект удалён"); + _logger.LogInformation("Из текущей карты удалён объект {@Battleship}", deletedBattleship); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (BattleshipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -159,6 +196,7 @@ namespace Battleship listBoxMaps.Items.Clear(); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text); } private void ButtonDeleteMap_Click(object sender, EventArgs e) { @@ -171,6 +209,7 @@ namespace Battleship _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); listBoxMaps.Items.Clear(); ReloadMaps(); + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } } @@ -187,13 +226,18 @@ namespace Battleship { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", 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); + _logger.LogInformation("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); } } } @@ -206,16 +250,19 @@ namespace Battleship { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { - ReloadMaps(); + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); MessageBox.Show("Загрузка данных прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Ошибка загрузки данных", "Результат", + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); } } } diff --git a/Battleship/Battleship/MapsCollection.cs b/Battleship/Battleship/MapsCollection.cs index 492dc98..b811e51 100644 --- a/Battleship/Battleship/MapsCollection.cs +++ b/Battleship/Battleship/MapsCollection.cs @@ -63,7 +63,7 @@ namespace Battleship /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -77,7 +77,6 @@ namespace Battleship fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } /// @@ -85,17 +84,17 @@ namespace Battleship /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader fs = new(filename)) { if (!fs.ReadLine().Contains("MapsCollection")) { - return false; + throw new Exception("Формат данных в файле не правильный"); } _mapStorage.Clear(); while (!fs.EndOfStream) @@ -117,7 +116,6 @@ namespace Battleship StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } \ No newline at end of file diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs index d328611..0a64823 100644 --- a/Battleship/Battleship/Program.cs +++ b/Battleship/Battleship/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; + namespace Battleship { internal static class Program @@ -11,7 +17,30 @@ namespace Battleship // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetBattleship()); + 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: "appsettings.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/Battleship/Battleship/SetBattleshipGeneric.cs b/Battleship/Battleship/SetBattleshipGeneric.cs index bf9d43a..2e15199 100644 --- a/Battleship/Battleship/SetBattleshipGeneric.cs +++ b/Battleship/Battleship/SetBattleshipGeneric.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; @@ -28,28 +29,41 @@ namespace Battleship public int Insert(T battleship) { - if (_places.Count + 1 >= _maxCount) - return -1; - _places.Insert(0, battleship); - return 0; + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } + + if (Count + 1 <= _maxCount) return Insert(battleship, 0); + + else return -1; } public int Insert(T battleship, int position) { - if (position >= _maxCount || position < 0) - return -1; - if (_places.Count + 1 >= _maxCount) + if (position > _maxCount && position < 0) + { return -1; + } + if (_places.Contains(battleship)) + { + throw new ArgumentException($"Объект {battleship} уже есть в наборе"); + } _places.Insert(position, battleship); return position; } public T Remove(int position) { - if (position < 0 || position >= _maxCount) return null; - T savedBattleship = _places[position]; + if (position >= Count || position < 0) + { + throw new BattleshipNotFoundException(position); + } + + T result = _places[position]; _places.RemoveAt(position); - return savedBattleship; + + return result; } public T this[int position] diff --git a/Battleship/Battleship/StorageOverflowException.cs b/Battleship/Battleship/StorageOverflowException.cs new file mode 100644 index 0000000..cd4acd3 --- /dev/null +++ b/Battleship/Battleship/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 Battleship +{ + [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/Battleship/Battleship/appsettings.json b/Battleship/Battleship/appsettings.json new file mode 100644 index 0000000..6e66299 --- /dev/null +++ b/Battleship/Battleship/appsettings.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