From 8062cf5a6050ec6ed6926384ed1e11c127af0feb Mon Sep 17 00:00:00 2001 From: Danil Markov Date: Thu, 1 Dec 2022 23:16:23 +0400 Subject: [PATCH] lab done --- .../ContainerShip/ContainerShip.csproj | 12 +++ .../ContainerShip/FormMapWithSetShip.cs | 100 +++++++++++++----- ContainerShip/ContainerShip/MapsCollection.cs | 53 ++++++---- ContainerShip/ContainerShip/Program.cs | 31 +++++- ContainerShip/ContainerShip/SetShipGeneric.cs | 5 +- .../ContainerShip/ShipNotFoundException.cs | 17 +++ .../ContainerShip/StorageOverflowException.cs | 20 ++++ ContainerShip/ContainerShip/serilog.json | 20 ++++ 8 files changed, 203 insertions(+), 55 deletions(-) create mode 100644 ContainerShip/ContainerShip/ShipNotFoundException.cs create mode 100644 ContainerShip/ContainerShip/StorageOverflowException.cs create mode 100644 ContainerShip/ContainerShip/serilog.json diff --git a/ContainerShip/ContainerShip/ContainerShip.csproj b/ContainerShip/ContainerShip/ContainerShip.csproj index 13ee123..bad9658 100644 --- a/ContainerShip/ContainerShip/ContainerShip.csproj +++ b/ContainerShip/ContainerShip/ContainerShip.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True diff --git a/ContainerShip/ContainerShip/FormMapWithSetShip.cs b/ContainerShip/ContainerShip/FormMapWithSetShip.cs index b7427d9..ff6fd62 100644 --- a/ContainerShip/ContainerShip/FormMapWithSetShip.cs +++ b/ContainerShip/ContainerShip/FormMapWithSetShip.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -20,10 +21,12 @@ namespace ContainerShip }; private readonly MapsCollection _mapsCollection; + private readonly ILogger _logger; - public FormMapWithSetShip() + public FormMapWithSetShip(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach(var elem in _mapsDict) @@ -50,7 +53,7 @@ namespace ContainerShip listBoxMaps.SelectedIndex = index; } } - + private void ButtonAddMap_Click(object sender, EventArgs e) { if (comboBoxSelectorMap.SelectedIndex == -1 || @@ -58,17 +61,22 @@ namespace ContainerShip { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", + comboBoxSelectorMap.SelectedIndex == + -1 ? "Карта не выбрана" : "Карта не назавана"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Нет такой карты {0}", comboBoxSelectorMap.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void ButtonAddShip_Click(object sender, EventArgs e) @@ -80,48 +88,76 @@ namespace ContainerShip private void AddShip(DrawingShip ship) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + DrawingObjectShip objectShip = new(ship); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1) + { + MessageBox.Show("Object added"); + _logger.LogInformation("Добавлен корабль {@Ship}", ship); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Failed to add object"); + _logger.LogInformation("Не удалось добавить объект"); + } } - DrawingObjectShip objectShip = new(ship); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Object added"); - 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("Failed to add object"); + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, ship); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonRemoveShip_Click(object sender, EventArgs e) { - if (listBoxMaps.SelectedIndex == -1) - { - 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(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Ship}", pos); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект не существует", pos); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + } + } - + private void ButtonShowStorage_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) @@ -171,6 +207,7 @@ namespace ContainerShip private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Переход на карту {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } private void ButtonDeleteMap_Click(object sender, EventArgs e) { @@ -181,6 +218,7 @@ namespace ContainerShip if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); @@ -190,15 +228,18 @@ namespace ContainerShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Файл {0} сохранен", saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}': {1}", saveFileDialog.FileName, ex.Message); } } } @@ -206,14 +247,17 @@ namespace ContainerShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); ReloadMaps(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось загрузить файл '{0}': {1}", openFileDialog.FileName, ex.Message); + MessageBox.Show($"Не получилось загрузить файл:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ContainerShip/ContainerShip/MapsCollection.cs b/ContainerShip/ContainerShip/MapsCollection.cs index 1d9163a..bf783fc 100644 --- a/ContainerShip/ContainerShip/MapsCollection.cs +++ b/ContainerShip/ContainerShip/MapsCollection.cs @@ -73,41 +73,48 @@ namespace ContainerShip 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)) { + bool isFirst = true; string str; - if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) + while ((str = sr.ReadLine()) != null) { - return false; - } - _mapStorages.Clear(); - while((str = sr.ReadLine()) != null) - { - var elem = str.Split(separatorDict); - AbstractMap map = null; - switch (elem[1]) + if (isFirst) { - case "SimpleMap": - map = new SimpleMap(); - break; - case "IslandsMap": - map = new IslandsMap(); - break; - case "RocksMap": - map = new RocksMap(); - break; + if (!str.Contains("MapsCollection")) + { + throw new FileFormatException("Формат данных в файле не правильный"); + } + _mapStorages.Clear(); + isFirst = false; + } + else + { + var elem = str.Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "Простая карта": + map = new SimpleMap(); + break; + case "Острова": + map = new IslandsMap(); + break; + case "Скалы": + map = new RocksMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetShipGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } - _mapStorages.Add(elem[0], new MapWithSetShipGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } } } diff --git a/ContainerShip/ContainerShip/Program.cs b/ContainerShip/ContainerShip/Program.cs index f1976ba..0084178 100644 --- a/ContainerShip/ContainerShip/Program.cs +++ b/ContainerShip/ContainerShip/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + + namespace ContainerShip { internal static class Program @@ -11,7 +17,30 @@ namespace ContainerShip // 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: "serilog.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/ContainerShip/ContainerShip/SetShipGeneric.cs b/ContainerShip/ContainerShip/SetShipGeneric.cs index 6cf3cf3..bbba05b 100644 --- a/ContainerShip/ContainerShip/SetShipGeneric.cs +++ b/ContainerShip/ContainerShip/SetShipGeneric.cs @@ -9,7 +9,6 @@ namespace ContainerShip internal class SetShipGeneric where T : class { - private readonly List _places; public int Count => _places.Count; @@ -31,7 +30,7 @@ namespace ContainerShip { if (position < 0 || position > Count || Count == _maxCount) { - return -1; + throw new StorageOverflowException(_maxCount); } _places.Insert(position, ship); return position; @@ -41,7 +40,7 @@ namespace ContainerShip { if (position >= Count || position < 0) { - return null; + throw new ShipNotFoundException(position); } T removedObject = _places[position]; _places.RemoveAt(position); diff --git a/ContainerShip/ContainerShip/ShipNotFoundException.cs b/ContainerShip/ContainerShip/ShipNotFoundException.cs new file mode 100644 index 0000000..592727b --- /dev/null +++ b/ContainerShip/ContainerShip/ShipNotFoundException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + +namespace ContainerShip +{ + [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/ContainerShip/ContainerShip/StorageOverflowException.cs b/ContainerShip/ContainerShip/StorageOverflowException.cs new file mode 100644 index 0000000..8dc2494 --- /dev/null +++ b/ContainerShip/ContainerShip/StorageOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + + +namespace ContainerShip +{ + [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/ContainerShip/ContainerShip/serilog.json b/ContainerShip/ContainerShip/serilog.json new file mode 100644 index 0000000..5dd3d1b --- /dev/null +++ b/ContainerShip/ContainerShip/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } +} \ No newline at end of file -- 2.25.1