diff --git a/WarmlyShip/WarmlyShip/AppSetting.json b/WarmlyShip/WarmlyShip/AppSetting.json new file mode 100644 index 0000000..493f426 --- /dev/null +++ b/WarmlyShip/WarmlyShip/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/WarmlyShip/WarmlyShip/FormShipCollection.cs b/WarmlyShip/WarmlyShip/FormShipCollection.cs index 4296539..4e89f0f 100644 --- a/WarmlyShip/WarmlyShip/FormShipCollection.cs +++ b/WarmlyShip/WarmlyShip/FormShipCollection.cs @@ -11,6 +11,8 @@ using System.Windows.Forms; using WarmlyShip.DrawingObjects; using WarmlyShip.Generics; using WarmlyShip.MovementStrategy; +using WarmlyShip.Exceptions; +using Microsoft.Extensions.Logging; namespace WarmlyShip @@ -25,12 +27,17 @@ namespace WarmlyShip /// private readonly ShipsGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -63,12 +70,14 @@ namespace WarmlyShip { if (string.IsNullOrEmpty(textBoxStorageName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Коллекция не добавлена, не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -90,13 +99,17 @@ namespace WarmlyShip { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } + _logger.LogWarning("Отмена удаления набора"); } /// /// Добавление объекта в набор @@ -107,38 +120,20 @@ namespace WarmlyShip { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; } + var formShipConfig = new FormShipConfig(); + formShipConfig.AddEvent(AddShip); formShipConfig.Show(); - Action? shipDelegate = new((m) => - { - bool isAddSuccessful = (obj + m); - if (isAddSuccessful) - { - MessageBox.Show("Объект добавлен"); - m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); - pictureBoxCollection.Image = obj.ShowShips(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - }); - formShipConfig.AddEvent(shipDelegate); } - /// - /// Удаление объекта из набора - /// - /// - /// - private void ButtonRemoveShip_Click(object sender, EventArgs e) + private void AddShip(DrawingWarmlyShip drawingWarmlyShip) { if (listBoxStorages.SelectedIndex == -1) { @@ -146,23 +141,69 @@ namespace WarmlyShip } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) + { + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + if (obj + drawingWarmlyShip) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowShips(); + _logger.LogInformation($"Объект {obj.GetType()} добавлен"); + } + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); + } + + } + /// + /// Удаление объекта из набора + /// + /// + /// + private void ButtonRemoveShip_Click(object sender, EventArgs e) + { + if (listBoxStorages.SelectedIndex == -1) + { + _logger.LogWarning("Удаление объекта из несуществующего набора"); + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { return; } if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning("Отмена удаления объекта"); return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowShips(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект с позиции {pos}"); + pictureBoxCollection.Image = obj.ShowShips(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}"); } + } /// /// Обновление рисунка по набору @@ -175,8 +216,7 @@ namespace WarmlyShip { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -192,15 +232,16 @@ namespace WarmlyShip { 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}"); } } } @@ -213,18 +254,19 @@ namespace WarmlyShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + ReloadObjects(); + 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(); } } } diff --git a/WarmlyShip/WarmlyShip/FormShipConfig.cs b/WarmlyShip/WarmlyShip/FormShipConfig.cs index cfd5750..61844b3 100644 --- a/WarmlyShip/WarmlyShip/FormShipConfig.cs +++ b/WarmlyShip/WarmlyShip/FormShipConfig.cs @@ -9,9 +9,11 @@ using System.Threading.Tasks; using System.Windows.Forms; using WarmlyShip.DrawingObjects; +using WarmlyShip.Generics; using WarmlyShip.Entities; using WarmlyShip.MovementStrategy; + namespace WarmlyShip { /// diff --git a/WarmlyShip/WarmlyShip/Program.cs b/WarmlyShip/WarmlyShip/Program.cs index 2dda87b..1474a85 100644 --- a/WarmlyShip/WarmlyShip/Program.cs +++ b/WarmlyShip/WarmlyShip/Program.cs @@ -1,3 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; +using WarmlyShip; + namespace WarmlyShip { internal static class Program @@ -8,10 +15,31 @@ namespace WarmlyShip [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/WarmlyShip/WarmlyShip/SetGeneric.cs b/WarmlyShip/WarmlyShip/SetGeneric.cs index 0c5069f..39b0e72 100644 --- a/WarmlyShip/WarmlyShip/SetGeneric.cs +++ b/WarmlyShip/WarmlyShip/SetGeneric.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using WarmlyShip.Exceptions; namespace WarmlyShip.Generics + { internal class SetGeneric where T : class @@ -37,12 +39,7 @@ namespace WarmlyShip.Generics /// public bool Insert(T warmlyship) { - if (_places.Count == _maxCount) - { - return false; - } - Insert(warmlyship, 0); - return true; + return Insert(warmlyship, 0); } /// /// Добавление объекта в набор на конкретную позицию @@ -52,11 +49,12 @@ namespace WarmlyShip.Generics /// public bool Insert(T warmlyship, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) - { - return false; - } - _places.Insert(position, warmlyship); + if (position < 0 || position >= _maxCount) + throw new ShipNotFoundException(position); + + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); + _places.Insert(0, warmlyship); return true; } /// @@ -66,10 +64,9 @@ namespace WarmlyShip.Generics /// public bool 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; } diff --git a/WarmlyShip/WarmlyShip/ShipNotFoundException.cs b/WarmlyShip/WarmlyShip/ShipNotFoundException.cs new file mode 100644 index 0000000..16abf6a --- /dev/null +++ b/WarmlyShip/WarmlyShip/ShipNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace WarmlyShip.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 contex) : base(info, contex) { } + } +} diff --git a/WarmlyShip/WarmlyShip/ShipsGenericCollection.cs b/WarmlyShip/WarmlyShip/ShipsGenericCollection.cs index 6adc621..8ed358b 100644 --- a/WarmlyShip/WarmlyShip/ShipsGenericCollection.cs +++ b/WarmlyShip/WarmlyShip/ShipsGenericCollection.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using WarmlyShip.DrawingObjects; using WarmlyShip.MovementStrategy; -using static System.Windows.Forms.VisualStyles.VisualStyleElement; + namespace WarmlyShip.Generics { @@ -135,7 +135,9 @@ namespace WarmlyShip.Generics if (ship != null) { int width = _pictureWidth / _placeSizeWidth; - ship.SetPosition((width - 1 - (i % width)) * _placeSizeWidth, i / width * _placeSizeHeight); + ship._pictureWidth = _pictureWidth; + ship._pictureHeight = _pictureHeight; + ship.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight); ship.DrawTransport(g); } i++; diff --git a/WarmlyShip/WarmlyShip/ShipsGenericStorage.cs b/WarmlyShip/WarmlyShip/ShipsGenericStorage.cs index f99f23f..bfa4a54 100644 --- a/WarmlyShip/WarmlyShip/ShipsGenericStorage.cs +++ b/WarmlyShip/WarmlyShip/ShipsGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using WarmlyShip.DrawingObjects; using WarmlyShip.MovementStrategy; +using WarmlyShip.Exceptions; namespace WarmlyShip.Generics { @@ -98,12 +99,13 @@ namespace WarmlyShip.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } + StringBuilder data = new(); foreach (KeyValuePair> record in _shipStorages) { @@ -113,16 +115,17 @@ namespace WarmlyShip.Generics records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } if (data.Length == 0) { - return false; + throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { - writer.Write($"ShipStorage{Environment.NewLine}{data}"); + writer.WriteLine("BoatStorage"); + writer.Write(data.ToString()); } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла @@ -130,55 +133,57 @@ namespace WarmlyShip.Generics /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } - using (StreamReader fs = File.OpenText(filename)) + + using (StreamReader reader = new StreamReader(filename)) { - string str = fs.ReadLine(); - if (str == null || str.Length == 0) + string checker = reader.ReadLine(); + if (checker == null) + throw new NullReferenceException("Нет данных для загрузки"); + if (!checker.StartsWith("BoatStorage")) { - return false; - } - if (!str.StartsWith("ShipStorage")) - { - return false; + //если нет такой записи, то это не те данные + throw new FormatException("Неверный формат данных"); } _shipStorages.Clear(); - string strs = ""; - - while ((strs = fs.ReadLine()) != null) + string strs; + bool firstinit = true; + while ((strs = reader.ReadLine()) != null) { + if (strs == null && firstinit) + throw new NullReferenceException("Нет данных для загрузки"); if (strs == null) - { - return false; - } - - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) - { - continue; - } + break; + firstinit = false; + string name = strs.Split('|')[0]; ShipsGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + foreach (string data in strs.Split('|')[1].Split(';')) { - DrawingWarmlyShip? ship = elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight); - if (ship != null) + DrawingWarmlyShip? vehicle = data?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight); + if (vehicle != null) { - if (!(collection + ship)) + try { - return false; + _ = collection + vehicle; + } + catch (ShipNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } - _shipStorages.Add(record[0], collection); + _shipStorages.Add(name, collection); } - return true; } } } diff --git a/WarmlyShip/WarmlyShip/StorageOverflowException.cs b/WarmlyShip/WarmlyShip/StorageOverflowException.cs new file mode 100644 index 0000000..477ee49 --- /dev/null +++ b/WarmlyShip/WarmlyShip/StorageOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace WarmlyShip.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/WarmlyShip/WarmlyShip/WarmlyShip.csproj b/WarmlyShip/WarmlyShip/WarmlyShip.csproj index 13ee123..b28931e 100644 --- a/WarmlyShip/WarmlyShip/WarmlyShip.csproj +++ b/WarmlyShip/WarmlyShip/WarmlyShip.csproj @@ -8,6 +8,15 @@ enable + + + + + + + + + True