From a8456abc3610852a91b76080cbcc4ebc4f25a1fa Mon Sep 17 00:00:00 2001 From: ksenianeva <95441235+ksenianeva@users.noreply.github.com> Date: Tue, 29 Nov 2022 13:14:11 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=A1=D0=B5=D0=B4=D1=8C=D0=BC=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0.=20=D0=94?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20Except?= =?UTF-8?q?ion.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ContainerShip/ContainerShip/ShipNotFoundException.cs | 12 ++++++++++++ .../ContainerShip/StorageOverflowException.cs | 12 ++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 ContainerShip/ContainerShip/ShipNotFoundException.cs create mode 100644 ContainerShip/ContainerShip/StorageOverflowException.cs diff --git a/ContainerShip/ContainerShip/ShipNotFoundException.cs b/ContainerShip/ContainerShip/ShipNotFoundException.cs new file mode 100644 index 0000000..2f5c52c --- /dev/null +++ b/ContainerShip/ContainerShip/ShipNotFoundException.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ContainerShip +{ + internal class ShipNotFoundException + { + } +} diff --git a/ContainerShip/ContainerShip/StorageOverflowException.cs b/ContainerShip/ContainerShip/StorageOverflowException.cs new file mode 100644 index 0000000..4ea92bb --- /dev/null +++ b/ContainerShip/ContainerShip/StorageOverflowException.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ContainerShip +{ + internal class StorageOverflowException + { + } +} -- 2.25.1 From 4ab74bde46ed8af3d4920370534b111127b8a3fd Mon Sep 17 00:00:00 2001 From: ksenianeva <95441235+ksenianeva@users.noreply.github.com> Date: Fri, 2 Dec 2022 00:04:23 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=BE=D0=B3=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ContainerShip/ContainerShip.csproj | 24 +++++++++++ .../ContainerShip/FormMapWithSetShips.cs | 40 +++++++++++++------ .../ContainerShip/MapWithSetShipsGeneric.cs | 2 +- ContainerShip/ContainerShip/MapsCollection.cs | 14 +++---- ContainerShip/ContainerShip/Program.cs | 27 ++++++++++++- .../ContainerShip/SetShipsGeneric.cs | 8 ++-- .../ContainerShip/ShipNotFoundException.cs | 9 ++++- .../ContainerShip/StorageOverflowException.cs | 9 ++++- ContainerShip/ContainerShip/appsettings.json | 24 +++++++++++ 9 files changed, 131 insertions(+), 26 deletions(-) create mode 100644 ContainerShip/ContainerShip/appsettings.json diff --git a/ContainerShip/ContainerShip/ContainerShip.csproj b/ContainerShip/ContainerShip/ContainerShip.csproj index 13ee123..f7fe2a1 100644 --- a/ContainerShip/ContainerShip/ContainerShip.csproj +++ b/ContainerShip/ContainerShip/ContainerShip.csproj @@ -8,6 +8,30 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + + True diff --git a/ContainerShip/ContainerShip/FormMapWithSetShips.cs b/ContainerShip/ContainerShip/FormMapWithSetShips.cs index 97ba096..b35292a 100644 --- a/ContainerShip/ContainerShip/FormMapWithSetShips.cs +++ b/ContainerShip/ContainerShip/FormMapWithSetShips.cs @@ -8,6 +8,7 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.DataFormats; +using Microsoft.Extensions.Logging; namespace ContainerShip { @@ -28,9 +29,14 @@ namespace ContainerShip /// /// Конструктор /// - public FormMapWithSetShips() + /// /// + /// Логер + /// + private readonly ILogger _logger; + public FormMapWithSetShips(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); ComboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -97,14 +103,21 @@ namespace ContainerShip 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("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } } - else + catch (ShipNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}") ; } } /// @@ -179,6 +192,7 @@ namespace ContainerShip } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } /// /// Выбор карты @@ -212,13 +226,14 @@ namespace ContainerShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(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); } } } @@ -227,14 +242,15 @@ namespace ContainerShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ContainerShip/ContainerShip/MapWithSetShipsGeneric.cs b/ContainerShip/ContainerShip/MapWithSetShipsGeneric.cs index d87b334..4afb290 100644 --- a/ContainerShip/ContainerShip/MapWithSetShipsGeneric.cs +++ b/ContainerShip/ContainerShip/MapWithSetShipsGeneric.cs @@ -71,7 +71,7 @@ namespace ContainerShip foreach (var ship in _setShips.GetShips()) { return _map.CreateMap(_pictureWidth, _pictureHeight, ship); - } + } return new(_pictureWidth, _pictureHeight); } public string GetData(char separatorType, char separatorData) diff --git a/ContainerShip/ContainerShip/MapsCollection.cs b/ContainerShip/ContainerShip/MapsCollection.cs index 6eadab9..605ca47 100644 --- a/ContainerShip/ContainerShip/MapsCollection.cs +++ b/ContainerShip/ContainerShip/MapsCollection.cs @@ -104,7 +104,7 @@ namespace ContainerShip /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -119,19 +119,17 @@ namespace ContainerShip sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw); } } - return true; } - /// /// Загрузка нформации по автомобилям на парковках из файла /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new StreamReader(fs)) @@ -139,7 +137,10 @@ namespace ContainerShip string line; line = sr.ReadLine(); line.Trim(); - if (line != "MapsCollection") return false; + if (line != "MapsCollection") + { + throw new Exception("Неправильный формат данных в файле"); + } _mapStorages.Clear(); while ((line = sr.ReadLine()) != null) { @@ -158,7 +159,6 @@ namespace ContainerShip _mapStorages.Add(elem[0], new MapWithSetShipsGeneric(_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 d579063..af64b50 100644 --- a/ContainerShip/ContainerShip/Program.cs +++ b/ContainerShip/ContainerShip/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Logging; namespace ContainerShip { internal static class Program @@ -11,7 +16,27 @@ 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 FormMapWithSetShips()); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json") + .Build(); + Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + option.AddSerilog(); + }); } } } \ No newline at end of file diff --git a/ContainerShip/ContainerShip/SetShipsGeneric.cs b/ContainerShip/ContainerShip/SetShipsGeneric.cs index cb778d4..196ab35 100644 --- a/ContainerShip/ContainerShip/SetShipsGeneric.cs +++ b/ContainerShip/ContainerShip/SetShipsGeneric.cs @@ -44,8 +44,10 @@ namespace ContainerShip /// public int Insert(T ship, int position) { - if (position < 0 || position >= _maxCount) return -1; - if (_places.Count + 1 >= _maxCount) return -1; + if (position < 0 || position >= _maxCount || _places.Count + 1 >= _maxCount) + { + throw new StorageOverflowException(_maxCount); + } _places.Add(ship); return position; } @@ -58,7 +60,7 @@ namespace ContainerShip { if (position < 0 || position >= _maxCount) { - return null; + throw new ShipNotFoundException(position); } T ship = _places[position]; _places.RemoveAt(position); diff --git a/ContainerShip/ContainerShip/ShipNotFoundException.cs b/ContainerShip/ContainerShip/ShipNotFoundException.cs index 2f5c52c..88d5e98 100644 --- a/ContainerShip/ContainerShip/ShipNotFoundException.cs +++ b/ContainerShip/ContainerShip/ShipNotFoundException.cs @@ -1,12 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ContainerShip { - internal class ShipNotFoundException + [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 index 4ea92bb..1ebac1f 100644 --- a/ContainerShip/ContainerShip/StorageOverflowException.cs +++ b/ContainerShip/ContainerShip/StorageOverflowException.cs @@ -1,12 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ContainerShip { - internal class StorageOverflowException + [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/appsettings.json b/ContainerShip/ContainerShip/appsettings.json new file mode 100644 index 0000000..ad4b089 --- /dev/null +++ b/ContainerShip/ContainerShip/appsettings.json @@ -0,0 +1,24 @@ +{ + "exclude": [ + "/bin", + "/bower_components", + "/jspm_packages", + "/node_modules", + "/obj", + "/platforms" + ], + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "Logs/log.txt" } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1 From e84985aaf55acc07145d5c5b2d73994ed34a21e2 Mon Sep 17 00:00:00 2001 From: ksenianeva <95441235+ksenianeva@users.noreply.github.com> Date: Tue, 13 Dec 2022 12:26:09 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=A1=D0=B5=D0=B4=D1=8C=D0=BC=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0.=20=D0=9B?= =?UTF-8?q?=D0=BE=D0=B3=D0=B5=D1=80=20+=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4?= =?UTF-8?q?=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormMapWithSetShips.Designer.cs | 18 +++--- .../ContainerShip/FormMapWithSetShips.cs | 60 +++++++++++++++---- .../ContainerShip/FormMapWithSetShips.resx | 3 + ContainerShip/ContainerShip/MapsCollection.cs | 4 +- .../ContainerShip/SetShipsGeneric.cs | 8 ++- 5 files changed, 70 insertions(+), 23 deletions(-) diff --git a/ContainerShip/ContainerShip/FormMapWithSetShips.Designer.cs b/ContainerShip/ContainerShip/FormMapWithSetShips.Designer.cs index 70195a7..926fae2 100644 --- a/ContainerShip/ContainerShip/FormMapWithSetShips.Designer.cs +++ b/ContainerShip/ContainerShip/FormMapWithSetShips.Designer.cs @@ -72,7 +72,7 @@ this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right; this.groupBox1.Location = new System.Drawing.Point(553, 33); this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(300, 654); + this.groupBox1.Size = new System.Drawing.Size(300, 709); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Инструменты"; @@ -154,7 +154,7 @@ this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.BackgroundImage = global::ContainerShip.Properties.Resources.upArrow; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonUp.Location = new System.Drawing.Point(131, 536); + this.buttonUp.Location = new System.Drawing.Point(131, 591); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(50, 50); this.buttonUp.TabIndex = 9; @@ -166,7 +166,7 @@ this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRight.BackgroundImage = global::ContainerShip.Properties.Resources.LeftArrow; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonRight.Location = new System.Drawing.Point(187, 592); + this.buttonRight.Location = new System.Drawing.Point(187, 647); this.buttonRight.Name = "buttonRight"; this.buttonRight.Size = new System.Drawing.Size(50, 50); this.buttonRight.TabIndex = 8; @@ -178,7 +178,7 @@ this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.BackgroundImage = global::ContainerShip.Properties.Resources.DownArrow; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonDown.Location = new System.Drawing.Point(131, 592); + this.buttonDown.Location = new System.Drawing.Point(131, 647); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(50, 50); this.buttonDown.TabIndex = 7; @@ -190,7 +190,7 @@ this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonLeft.BackgroundImage = global::ContainerShip.Properties.Resources.RightArrow; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.buttonLeft.Location = new System.Drawing.Point(75, 592); + this.buttonLeft.Location = new System.Drawing.Point(75, 647); this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Size = new System.Drawing.Size(50, 50); this.buttonLeft.TabIndex = 6; @@ -240,7 +240,7 @@ this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Location = new System.Drawing.Point(0, 33); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(553, 654); + this.pictureBox.Size = new System.Drawing.Size(553, 709); this.pictureBox.TabIndex = 1; this.pictureBox.TabStop = false; // @@ -267,14 +267,14 @@ // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - this.SaveToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(212, 34); this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // LoadToolStripMenuItem // this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - this.LoadToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(212, 34); this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // @@ -291,7 +291,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(853, 687); + this.ClientSize = new System.Drawing.Size(853, 742); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBox1); this.Controls.Add(this.menuStrip); diff --git a/ContainerShip/ContainerShip/FormMapWithSetShips.cs b/ContainerShip/ContainerShip/FormMapWithSetShips.cs index b35292a..19aeb7f 100644 --- a/ContainerShip/ContainerShip/FormMapWithSetShips.cs +++ b/ContainerShip/ContainerShip/FormMapWithSetShips.cs @@ -33,12 +33,14 @@ namespace ContainerShip /// Логер /// private readonly ILogger _logger; + private Action addShipAction; public FormMapWithSetShips(ILogger logger) { InitializeComponent(); _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); ComboBoxSelectorMap.Items.Clear(); + addShipAction = addShip; foreach (var elem in _mapsDict) { ComboBoxSelectorMap.Items.Add(elem.Key); @@ -66,6 +68,30 @@ namespace ContainerShip listBoxMaps.SelectedIndex = index; } } + private void addShip(DrawingShip ship) + { + try + { + _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectShip(ship)); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект {ship}"); + } + catch(ArgumentNullException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + catch(StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + } /// /// Добавление объекта /// @@ -78,9 +104,7 @@ namespace ContainerShip return; } var formShipConfig = new FormShipConfig(); - formShipConfig.AddEvent(new Action(ship => { - _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectShip(ship)); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();})); + formShipConfig.AddEvent(addShipAction); formShipConfig.Show(); } /// @@ -105,19 +129,20 @@ namespace ContainerShip int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } + IDrawingObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + MessageBox.Show("Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Удален объект {drawingObject}"); } catch (ShipNotFoundException ex) { MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.LogWarning($"Ошибка: {ex.Message}"); } catch (Exception ex) { - MessageBox.Show($"Неизвестная ошибка: {ex.Message}") ; + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.LogWarning($"Ошибка: {ex.Message}"); } } /// @@ -202,6 +227,7 @@ namespace ContainerShip private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Выбрана карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } /// /// Удаление карты @@ -214,11 +240,12 @@ namespace ContainerShip { return; } - + string deletedMapName = listBoxMaps.SelectedItem?.ToString(); if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта {deletedMapName}"); } } @@ -230,6 +257,7 @@ namespace ContainerShip { _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Данные сохранены в файле {saveFileDialog.FileName}"); } catch (Exception ex) { @@ -247,10 +275,22 @@ namespace ContainerShip _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); + } + catch (FileFormatException ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); + } + catch (FileNotFoundException ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } catch (Exception ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Ошибка: {ex.Message}"); } } } diff --git a/ContainerShip/ContainerShip/FormMapWithSetShips.resx b/ContainerShip/ContainerShip/FormMapWithSetShips.resx index 0034e6c..52520fa 100644 --- a/ContainerShip/ContainerShip/FormMapWithSetShips.resx +++ b/ContainerShip/ContainerShip/FormMapWithSetShips.resx @@ -66,4 +66,7 @@ 357, 17 + + 25 + \ No newline at end of file diff --git a/ContainerShip/ContainerShip/MapsCollection.cs b/ContainerShip/ContainerShip/MapsCollection.cs index 605ca47..094674c 100644 --- a/ContainerShip/ContainerShip/MapsCollection.cs +++ b/ContainerShip/ContainerShip/MapsCollection.cs @@ -129,7 +129,7 @@ namespace ContainerShip { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new StreamReader(fs)) @@ -139,7 +139,7 @@ namespace ContainerShip line.Trim(); if (line != "MapsCollection") { - throw new Exception("Неправильный формат данных в файле"); + throw new FileFormatException("Неправильный формат данных в файле"); } _mapStorages.Clear(); while ((line = sr.ReadLine()) != null) diff --git a/ContainerShip/ContainerShip/SetShipsGeneric.cs b/ContainerShip/ContainerShip/SetShipsGeneric.cs index 196ab35..d42a56b 100644 --- a/ContainerShip/ContainerShip/SetShipsGeneric.cs +++ b/ContainerShip/ContainerShip/SetShipsGeneric.cs @@ -44,7 +44,11 @@ namespace ContainerShip /// public int Insert(T ship, int position) { - if (position < 0 || position >= _maxCount || _places.Count + 1 >= _maxCount) + if(position < 0 || position >= _maxCount) + { + throw new ShipNotFoundException(position); + } + if ( _places.Count >= _maxCount) { throw new StorageOverflowException(_maxCount); } @@ -57,7 +61,7 @@ namespace ContainerShip /// /// public T Remove(int position) - { + { if (position < 0 || position >= _maxCount) { throw new ShipNotFoundException(position); -- 2.25.1