diff --git a/FileWithSave.txt b/FileWithSave.txt index 0c324cd..2132006 100644 --- a/FileWithSave.txt +++ b/FileWithSave.txt @@ -1,5 +1,5 @@ MapsCollection -were|SimpleMap|100:100:Lime; -ert4rg|SimpleMap|100:100:Red;100:100:Fuchsia:Yellow:True:True:True; -32e32|SecondMap|100:100:Lime:Fuchsia:True:True:False;100:100:Cyan:Cyan:False:False:True;100:100:Red:Yellow:True:True:True; -fdgwdf|SecondMap| +Карта 1 (первая)|SimpleMap|100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:True:True;100:100:White:Black:False:False:False;100:100:Yellow:Black:False:False:False;100:100:Lime:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:True:True:True;100:100:White:Black:False:False:False;100:100:White:Black:True:True:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:Red;100:100:Silver:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:Silver:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White;100:100:White;100:100:White:Lime:False:True:True;100:100:Lime:Black:False:False:False;100:100:Red;100:100:Blue:Black:False:True:True;100:100:White:Silver:False:True:True;100:100:Fuchsia;100:100:ffff8000:ffff8000:False:False:False;100:100:Red:Lime:True:True:True;100:100:Silver:Lime:True:True:True;100:100:Fuchsia;100:100:White;100:100:Red;100:100:Lime:Silver:True:True:False; +Карта 2 (первая)|SimpleMap| +Карта 3 (вторая)|SecondMap| +Карта 4 (вторая)|SecondMap| diff --git a/Warship/Warship/EntityAdvancedWarship.cs b/Warship/Warship/EntityAdvancedWarship.cs index 83ea10b..1862169 100644 --- a/Warship/Warship/EntityAdvancedWarship.cs +++ b/Warship/Warship/EntityAdvancedWarship.cs @@ -18,6 +18,5 @@ namespace Warship Antenna = antenna; Missile = missile; } - } } diff --git a/Warship/Warship/FormMapWithSetWarships.cs b/Warship/Warship/FormMapWithSetWarships.cs index 4a5a575..e4b918b 100644 --- a/Warship/Warship/FormMapWithSetWarships.cs +++ b/Warship/Warship/FormMapWithSetWarships.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 Warship }; private readonly MapsCollection _mapsCollection; + private readonly ILogger _logger; - public FormMapWithSetWarships() + public FormMapWithSetWarships(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach(var elem in _mapDict) @@ -62,14 +65,29 @@ namespace Warship return; } DrawingObjectWarship warship = new(drawingWarship); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship != -1) + { + _logger.LogInformation("Новый объект добавлен"); + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning("Не удалось добавить объект"); + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Хранилище переполнено: {ex.Message}"); + MessageBox.Show($"Хранилище переполнено: {ex.Message}", "Ошибка", MessageBoxButtons.OK,MessageBoxIcon.Error); + } + catch (Exception ex) + { + _logger.LogWarning($"Неизвестная ошибка: {ex.Message}"); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -88,14 +106,24 @@ namespace Warship 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($"Объект на позиции {pos} удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning($"Не удалось удалить объект на позиции {pos}, так как он равен null"); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (WarshipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Ошибка удаления: {ex.Message}"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); } } @@ -148,21 +176,25 @@ namespace Warship if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxMap.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "не выбрали карту" : "не указали название карты"); return; } if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Карта с названием {textBoxMap.Text} отсутствует"); return; } listBoxMaps.Items.Clear(); _mapsCollection.AddMap(textBoxMap.Text, _mapDict[comboBoxSelectorMap.Text]); + _logger.LogInformation($"Добавлена карта {textBoxMap.Text}"); ReloadMaps(); } private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } private void ButtonDeleteMap_Click(object sender, EventArgs e) @@ -175,6 +207,7 @@ namespace Warship { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); listBoxMaps.Items.Clear(); + _logger.LogInformation($"Карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty} удалена"); ReloadMaps(); } } @@ -183,13 +216,16 @@ namespace Warship { if (SaveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(SaveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно!", "Результат", MessageBoxButtons.OK,MessageBoxIcon.Information); + _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}: {ex.Message}"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -198,14 +234,17 @@ namespace Warship { 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}: {ex.Message}"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/Warship/Warship/FormWarshipConfig.cs b/Warship/Warship/FormWarshipConfig.cs index 61302d8..5538162 100644 --- a/Warship/Warship/FormWarshipConfig.cs +++ b/Warship/Warship/FormWarshipConfig.cs @@ -27,7 +27,7 @@ namespace Warship PanelSilver.MouseDown += PanelColor_MouseDown; PanelYellow.MouseDown += PanelColor_MouseDown; ButtonCancel.Click += (sender, e) => Close(); - } + } private void DrawWarship() { diff --git a/Warship/Warship/MapsCollection.cs b/Warship/Warship/MapsCollection.cs index b129965..7e1afc5 100644 --- a/Warship/Warship/MapsCollection.cs +++ b/Warship/Warship/MapsCollection.cs @@ -25,7 +25,7 @@ namespace Warship _pictureHeight = pictureHeight; } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -39,21 +39,20 @@ namespace Warship 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 Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { - return false; + throw new Exception("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -73,7 +72,6 @@ namespace Warship _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } - return true; } public void AddMap(string name, AbstractMap map) diff --git a/Warship/Warship/Program.cs b/Warship/Warship/Program.cs index 4c572c2..c176942 100644 --- a/Warship/Warship/Program.cs +++ b/Warship/Warship/Program.cs @@ -1,17 +1,39 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Warship { internal static class Program { - /// - /// The main entry point for the application. - /// [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 FormMapWithSetWarships()); + 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() + .AddJsonFile("E:\\\\2 \\\\PIbd-22_Zhimolostnova_A.V._Battleship._Base\\Warship\\Warship\\Serilog.json") + .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/Warship/Warship/Serilog.json b/Warship/Warship/Serilog.json new file mode 100644 index 0000000..e06a64b --- /dev/null +++ b/Warship/Warship/Serilog.json @@ -0,0 +1,12 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "E:\\УлГТУ\\2 курс\\РПП\\PIbd-22_Zhimolostnova_A.V._Battleship._Base\\Warship\\Warship\\bin\\Debug\\net6.0-windows\\Logs.txt" } + } + ] + } +} \ No newline at end of file diff --git a/Warship/Warship/SetWarshipsGeneric.cs b/Warship/Warship/SetWarshipsGeneric.cs index 936cf77..977fb0a 100644 --- a/Warship/Warship/SetWarshipsGeneric.cs +++ b/Warship/Warship/SetWarshipsGeneric.cs @@ -23,8 +23,8 @@ namespace Warship public int Insert(T warship) { - if (_places.Count + 1 >= _maxCount) - return -1; + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); _places.Insert(0, warship); return 0; } @@ -32,17 +32,20 @@ namespace Warship public int Insert(T warship, int position) { if (position >= _maxCount || position < 0) - return -1; - if (_places.Count + 1 >= _maxCount) - return -1; + throw new StorageOverflowException(_maxCount); _places.Insert(position, warship); return position; } public T Remove(int position) { - if (position >= _maxCount || position < 0) + if (position < 0 || position >= Count) + { return null; + } + var obj = _places[position]; + if (obj == null) + throw new WarshipNotFoundException(position); T deleted =_places[position]; _places.RemoveAt(position); diff --git a/Warship/Warship/StorageOverflowException.cs b/Warship/Warship/StorageOverflowException.cs new file mode 100644 index 0000000..d2e1618 --- /dev/null +++ b/Warship/Warship/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 Warship +{ + [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/Warship/Warship/Warship.csproj b/Warship/Warship/Warship.csproj index 13ee123..c85347a 100644 --- a/Warship/Warship/Warship.csproj +++ b/Warship/Warship/Warship.csproj @@ -8,6 +8,31 @@ enable + + + + + + + + + + + + + + + + + + + + + + + + + True diff --git a/Warship/Warship/WarshipNotFoundException.cs b/Warship/Warship/WarshipNotFoundException.cs new file mode 100644 index 0000000..3f13c18 --- /dev/null +++ b/Warship/Warship/WarshipNotFoundException.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 Warship +{ + [Serializable] + internal class WarshipNotFoundException : ApplicationException + { + public WarshipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public WarshipNotFoundException() : base() { } + public WarshipNotFoundException(string message) : base(message) { } + public WarshipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected WarshipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/fsdf.txt b/fsdf.txt new file mode 100644 index 0000000..077aa90 --- /dev/null +++ b/fsdf.txt @@ -0,0 +1,3 @@ +MapsCollection +djhfjrdhfv|SimpleMap|23:10:Lime:Silver:True:True:True;100:100:Red; +rgrjthgiot|SecondMap|12:100:Red:Fuchsia:True:True:True;100:100:Lime:Fuchsia:True:True:True;100:100:Blue;