diff --git a/Battleship/Battleship/AppSetting.json b/Battleship/Battleship/AppSetting.json new file mode 100644 index 0000000..b3dda2f --- /dev/null +++ b/Battleship/Battleship/AppSetting.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": "Battleship" + } + } +} \ No newline at end of file diff --git a/Battleship/Battleship/Battleship.csproj b/Battleship/Battleship/Battleship.csproj index 13ee123..b28931e 100644 --- a/Battleship/Battleship/Battleship.csproj +++ b/Battleship/Battleship/Battleship.csproj @@ -8,6 +8,15 @@ enable + + + + + + + + + True diff --git a/Battleship/Battleship/FormShipCollection.cs b/Battleship/Battleship/FormShipCollection.cs index d7a3d54..1f912fa 100644 --- a/Battleship/Battleship/FormShipCollection.cs +++ b/Battleship/Battleship/FormShipCollection.cs @@ -1,4 +1,6 @@ -using Battleship.DrawningObjects; +using Microsoft.Extensions.Logging; +using Battleship.DrawningObjects; +using Battleship.Exceptions; using Battleship.Generics; using Battleship.MovementStrategy; using System; @@ -20,12 +22,17 @@ namespace Battleship /// private readonly ShipsGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Обработка нажатия "Сохранение" @@ -36,15 +43,16 @@ namespace Battleship { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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.Information); + _logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}"); } } } @@ -57,15 +65,16 @@ namespace Battleship { if(openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + 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.Information); + _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); } } ReloadObjects(); @@ -99,12 +108,12 @@ namespace Battleship { if (string.IsNullOrEmpty(textBoxStorageName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -125,12 +134,16 @@ namespace Battleship { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string nameSet = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {nameSet}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(nameSet); ReloadObjects(); + _logger.LogInformation($"Удален набор: {nameSet}"); } } /// @@ -142,6 +155,7 @@ namespace Battleship { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; @@ -170,10 +184,12 @@ namespace Battleship { MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowShips(); - } + _logger.LogInformation($"Объект {obj.GetType()} добавлен"); + } else { MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation($"Не удалось добавить объект"); } } @@ -194,25 +210,30 @@ namespace Battleship return; } - int pos; + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try { - - pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); + pictureBoxCollection.Image = obj.ShowShips(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - catch + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); - return; + MessageBox.Show(ex.Message); + _logger.LogWarning($"Нет объекта{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); } - if (obj - pos != null) + catch (FormatException) { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowShips(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Было введено не число"); + MessageBox.Show("Введите число"); } } diff --git a/Battleship/Battleship/FormShipConfig.cs b/Battleship/Battleship/FormShipConfig.cs index 4f09ab2..7e1de0a 100644 --- a/Battleship/Battleship/FormShipConfig.cs +++ b/Battleship/Battleship/FormShipConfig.cs @@ -40,7 +40,7 @@ namespace Battleship buttonCancel.Click += (s, e) => Close(); } /// - /// Отрисовать машину + /// Отрисовать /// private void DrawShip() { @@ -112,7 +112,7 @@ namespace Battleship DrawShip(); } /// - /// Добавление машины + /// Добавление /// /// /// diff --git a/Battleship/Battleship/Program.cs b/Battleship/Battleship/Program.cs index 65edaed..fab5bc1 100644 --- a/Battleship/Battleship/Program.cs +++ b/Battleship/Battleship/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Battleship { internal static class Program @@ -8,10 +13,31 @@ namespace Battleship [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + 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}appSetting.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/SetGeneric.cs b/Battleship/Battleship/SetGeneric.cs index c0e3858..6280321 100644 --- a/Battleship/Battleship/SetGeneric.cs +++ b/Battleship/Battleship/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using Battleship.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -19,49 +20,45 @@ namespace Battleship.Generics _places = new List(count); } - public bool Insert(T ship) + public void Insert(T ship) { if(_places.Count == _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } Insert(ship, 0); - return true; } - public bool Insert(T ship, int position) + public void Insert(T ship, int position) { - if(!(position >= 0 && position <= Count && _places.Count < _maxCount)) - { - return false; - } - _places.Insert(position, ship); - return true; + if(_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (position < 0 || position >= _maxCount) + throw new ShipNotFoundException("Impossible to insert"); + _places.Insert(position, ship); + } - public bool Remove(int position) + public void Remove(int position) { - if (position < 0 || position >= Count) - return false; + if (position < 0 || position > _maxCount || position >= Count) + throw new ShipNotFoundException(position); + _places.RemoveAt(position); - return true; } public T? this[int position] { get { - if (position < 0 || position > _maxCount) + if (position < 0 || position >= Count) return null; return _places[position]; } set { - if(!(position >= 0 && position < Count && _places.Count < _maxCount)) - { + if (position < 0 || position > _maxCount || Count == _maxCount) return; - } - _places.Insert(position, value); - return; + _places[position] = value; } } diff --git a/Battleship/Battleship/ShipGenericCollection.cs b/Battleship/Battleship/ShipGenericCollection.cs index a95b907..2acbe24 100644 --- a/Battleship/Battleship/ShipGenericCollection.cs +++ b/Battleship/Battleship/ShipGenericCollection.cs @@ -33,7 +33,8 @@ namespace Battleship.Generics { if (obj != null && collect != null) { - return collect._collection.Insert(obj); + collect._collection.Insert(obj); + return true; } return false; } diff --git a/Battleship/Battleship/ShipNotFoundException.cs b/Battleship/Battleship/ShipNotFoundException.cs new file mode 100644 index 0000000..567a3c2 --- /dev/null +++ b/Battleship/Battleship/ShipNotFoundException.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 Battleship.Exceptions +{ + [Serializable] + internal class ShipNotFoundException : ApplicationException + { + 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 context) : base(info, context) { } + } +} diff --git a/Battleship/Battleship/ShipsGenericStorage.cs b/Battleship/Battleship/ShipsGenericStorage.cs index 63b6d35..bfee486 100644 --- a/Battleship/Battleship/ShipsGenericStorage.cs +++ b/Battleship/Battleship/ShipsGenericStorage.cs @@ -68,7 +68,7 @@ namespace Battleship.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -86,13 +86,12 @@ namespace Battleship.Generics } if (data.Length == 0) { - return false; + throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.Write($"ShipStorage{Environment.NewLine}{data}"); } - return true; } /// /// Загрузка информации по кораблям в хранилище из файла @@ -100,11 +99,11 @@ namespace Battleship.Generics /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"Файл {filename} не найден"); } using (StreamReader fs = File.OpenText(filename)) @@ -112,21 +111,20 @@ namespace Battleship.Generics string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new NullReferenceException("Нет данных для загрузки"); } if (!str.StartsWith("ShipStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _shipStorages.Clear(); string strs = ""; - while ((strs = fs.ReadLine()) != null) { if (strs == null) { - return false; + throw new NullReferenceException("Нет данных для загрузки"); } string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); @@ -143,13 +141,12 @@ namespace Battleship.Generics { if (!(collection + plane)) { - return false; + throw new InvalidOperationException("Ошибка добавления в коллекцию"); } } } _shipStorages.Add(record[0], collection); } - return true; } } } diff --git a/Battleship/Battleship/StorageOverflowException.cs b/Battleship/Battleship/StorageOverflowException.cs new file mode 100644 index 0000000..ac2af72 --- /dev/null +++ b/Battleship/Battleship/StorageOverflowException.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 Battleship.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) { } + } +}