From 3c0b05bfc7330985bf668db1795fc6744b46fb9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Wed, 13 Dec 2023 20:15:31 +0400 Subject: [PATCH 1/7] problems AddLogging in Program.cs --- .../ElectricLocomotive.csproj | 5 + .../FormLocomotiveCollection.cs | 92 +++++++++++++------ .../LocoNotFoundException.cs | 21 +++++ .../LocomotiveGenericStorage.cs | 28 +++--- .../ElectricLocomotive/Program.cs | 33 ++++++- .../StorageOverflowException.cs | 21 +++++ .../ElectricLocomotive/appSettings.json | 20 ++++ .../ElectricLocomotive/nlog.config | 14 +++ 8 files changed, 184 insertions(+), 50 deletions(-) create mode 100644 ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs create mode 100644 ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs create mode 100644 ElectricLocomotive/ElectricLocomotive/appSettings.json create mode 100644 ElectricLocomotive/ElectricLocomotive/nlog.config diff --git a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj index 13ee123..f15df17 100644 --- a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj +++ b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj @@ -8,6 +8,11 @@ enable + + + + + True diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs index f0ac0b1..62658b2 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs @@ -1,5 +1,8 @@ using ElectricLocomotive.DrawningObject; using ElectricLocomotive.Generics; +using Microsoft.Extensions.Logging; +using ProjectElectricLocomotive; +using ProjectElectricLocomotive.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -16,10 +19,15 @@ namespace ElectricLocomotive { private readonly LocomotiveGenericStorage _storage; - public FormLocomotiveCollection() + /// + /// Логер + /// + private readonly ILogger _logger; + public FormLocomotiveCollection(ILogger logger) { InitializeComponent(); _storage = new LocomotiveGenericStorage(CollectionPictureBox.Width, CollectionPictureBox.Height); + _logger = logger; } /// @@ -49,10 +57,13 @@ namespace ElectricLocomotive if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e) @@ -66,12 +77,15 @@ namespace ElectricLocomotive { return; } + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Набор '{name}' удален"); } + _logger.LogWarning("Отмена удаления набора"); } private void ButtonAddLocomotive_Click(object sender, EventArgs e) @@ -92,17 +106,26 @@ namespace ElectricLocomotive { return; } - + try + { + if (obj + loco > -1) + { + MessageBox.Show("Объект добавлен"); + CollectionPictureBox.Image = obj.ShowLocomotives(); + _logger.LogInformation($"Добавлен объект {obj}"); + ; + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + } //проверяем, удалось ли нам загрузить объект - if (obj + loco > -1) - { - MessageBox.Show("Объект добавлен"); - CollectionPictureBox.Image = obj.ShowLocomotives(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } + } private void ButtonRemoveLocomotive_Click(object sender, EventArgs e) @@ -116,17 +139,28 @@ namespace ElectricLocomotive if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning("Отмена удаления объекта"); return; } int pos = Convert.ToInt32(Input.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - CollectionPictureBox.Image = obj.ShowLocomotives(); + var removeObj = obj - pos; + if (removeObj != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект с позиции{pos}"); + CollectionPictureBox.Image = obj.ShowLocomotives(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LocoNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не найден объект по позиции: {obj}"); } } @@ -150,15 +184,15 @@ namespace ElectricLocomotive { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно!", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + _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}"); } } } @@ -169,17 +203,19 @@ namespace ElectricLocomotive /// private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { + // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка завершена!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + _logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}"); ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Ошибка загрузки!", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); - + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}"); } } } diff --git a/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs b/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.cs new file mode 100644 index 0000000..b2a0ec9 --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/LocoNotFoundException.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 ProjectElectricLocomotive.Exceptions +{ + [Serializable] + + internal class LocoNotFoundException : ApplicationException + { + public LocoNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public LocoNotFoundException() : base() { } + public LocoNotFoundException(string message) : base(message) { } + public LocoNotFoundException(string message, Exception exception) : base(message, exception) { } + protected LocoNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + + } +} diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs index 8838fb6..6045226 100644 --- a/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs +++ b/ElectricLocomotive/ElectricLocomotive/LocomotiveGenericStorage.cs @@ -97,7 +97,7 @@ namespace ElectricLocomotive.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -115,53 +115,47 @@ namespace ElectricLocomotive.Generics } if (data.Length == 0) { - return false; + throw new Exception("Нет данных для записи, ошибка"); } using StreamWriter fs = new StreamWriter(filename); { fs.WriteLine($"LocomotiveStorage{Environment.NewLine}"); fs.WriteLine(data); } - return true; + return; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// 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)) { - string str = fs.ReadLine(); - if (str == null || str.Length == 0) { - return false; + throw new IOException("Нет данных для загрузки"); } - if (!str.StartsWith("LocomotiveStorage")) { //если нет такой записи, то это не те данные - return false; + throw new FileFormatException("Неверный формат данных"); } - _locomotivesStorage.Clear(); string strs = ""; - - while ((strs = fs.ReadLine()) != null) { if (strs == null) { - return false; + throw new FileNotFoundException("Нет данных для загрузки"); } string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); @@ -176,15 +170,15 @@ namespace ElectricLocomotive.Generics DrawningLocomotive? loco = elem?.CreateDrawningLocomotive(_separatorForObject, _pictureWidth, _pictureHeight); if (loco != null) { - if ((collection + loco) == -1) + if ((collection + loco) == -1) // for my realization it's -1, for eegov's realization it's boolean { - return false; + throw new Exception("Ошибка добавления "); } } } _locomotivesStorage.Add(record[0], collection); } - return true; + return; } } } diff --git a/ElectricLocomotive/ElectricLocomotive/Program.cs b/ElectricLocomotive/ElectricLocomotive/Program.cs index ead2f34..3280605 100644 --- a/ElectricLocomotive/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/ElectricLocomotive/Program.cs @@ -1,19 +1,42 @@ -using ProjectElectricLocomotive; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + + namespace ElectricLocomotive { 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 FormLocomotiveCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLoggging(option =>// Addlogging + { + 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}appSettings.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/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs b/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.cs new file mode 100644 index 0000000..98ccf57 --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/StorageOverflowException.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 ProjectElectricLocomotive +{ + [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/ElectricLocomotive/ElectricLocomotive/appSettings.json b/ElectricLocomotive/ElectricLocomotive/appSettings.json new file mode 100644 index 0000000..f98af6a --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/appSettings.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": "Locomotives" + } + } +} \ No newline at end of file diff --git a/ElectricLocomotive/ElectricLocomotive/nlog.config b/ElectricLocomotive/ElectricLocomotive/nlog.config new file mode 100644 index 0000000..cca6f0f --- /dev/null +++ b/ElectricLocomotive/ElectricLocomotive/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + -- 2.25.1 From 2fc3246df8e8bee563fec9137d8566c2f38c1415 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Thu, 14 Dec 2023 17:50:55 +0400 Subject: [PATCH 2/7] good --- .../ElectricLocomotive/ElectricLocomotive.csproj | 12 ++++++++++++ ElectricLocomotive/ElectricLocomotive/Program.cs | 7 +++---- .../ElectricLocomotive/appSettings.json | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj index f15df17..fe30e6a 100644 --- a/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj +++ b/ElectricLocomotive/ElectricLocomotive/ElectricLocomotive.csproj @@ -9,8 +9,20 @@ + + + + + + + + + + + + diff --git a/ElectricLocomotive/ElectricLocomotive/Program.cs b/ElectricLocomotive/ElectricLocomotive/Program.cs index 3280605..6d62a0d 100644 --- a/ElectricLocomotive/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/ElectricLocomotive/Program.cs @@ -1,8 +1,7 @@ - +using Serilog; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; - - +using Microsoft.Extensions.Configuration; namespace ElectricLocomotive { @@ -23,7 +22,7 @@ namespace ElectricLocomotive } private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton().AddLoggging(option =>// Addlogging + services.AddSingleton().AddLogging(option => { string[] path = Directory.GetCurrentDirectory().Split('\\'); string pathNeed = ""; diff --git a/ElectricLocomotive/ElectricLocomotive/appSettings.json b/ElectricLocomotive/ElectricLocomotive/appSettings.json index f98af6a..49318ec 100644 --- a/ElectricLocomotive/ElectricLocomotive/appSettings.json +++ b/ElectricLocomotive/ElectricLocomotive/appSettings.json @@ -6,7 +6,7 @@ { "Name": "File", "Args": { - "path": "log_.log", + "path": "Logs/log_.log", "rollingInterval": "Day", "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" } -- 2.25.1 From 7cfdcda5ed9e8168e4983412c337d47dc30affd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Fri, 15 Dec 2023 11:37:10 +0400 Subject: [PATCH 3/7] Done --- .../ElectricLocomotive/SetGeneric.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs index 8c310ef..92bc661 100644 --- a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectElectricLocomotive.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -24,7 +25,14 @@ namespace ProjectElectricLocomotive.Generics public int Insert(T loco, int position) { - if (position < 0 || position >= _maxCount) return -1; + if (_places.Count >= _maxCount) + throw new StorageOverflowException(_maxCount); + + if (position < 0 || position >= _maxCount) + { + return -1; + } + _places.Insert(position, loco); return position; } @@ -34,6 +42,8 @@ namespace ProjectElectricLocomotive.Generics return null; T? tmp = _places[position]; + if (tmp == null) + throw new LocoNotFoundException(position); _places[position] = null; return tmp; } -- 2.25.1 From 9b337df21ce7da0e7506f8f2c26f1616a53ef7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Mon, 18 Dec 2023 19:56:44 +0400 Subject: [PATCH 4/7] WarningDell in Logs --- .../ElectricLocomotive/FormLocomotiveCollection.cs | 4 ++-- .../ElectricLocomotive/SetGeneric.cs | 14 ++++++-------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs index 62658b2..651cabd 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs @@ -145,8 +145,7 @@ namespace ElectricLocomotive int pos = Convert.ToInt32(Input.Text); try { - var removeObj = obj - pos; - if (removeObj != null) + if ( obj - pos != null ) { MessageBox.Show("Объект удален"); _logger.LogInformation($"Удален объект с позиции{pos}"); @@ -155,6 +154,7 @@ namespace ElectricLocomotive else { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}"); } } catch (LocoNotFoundException ex) diff --git a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs index 92bc661..c7d91a1 100644 --- a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs @@ -36,16 +36,14 @@ namespace ProjectElectricLocomotive.Generics _places.Insert(position, loco); return position; } - public T? Remove(int position) + public bool Remove(int position) { - if (position >= Count || position < 0) - return null; - - T? tmp = _places[position]; - if (tmp == null) + if (position < 0 || position >= _places.Count) + { throw new LocoNotFoundException(position); - _places[position] = null; - return tmp; + } + _places.RemoveAt(position); + return true; } public T? this[int position] { -- 2.25.1 From 4f67d6f78ab04206dd50baf4787c4901d1f47f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Wed, 27 Dec 2023 19:43:17 +0400 Subject: [PATCH 5/7] Add warning --- .../FormLocomotiveCollection.cs | 15 +++------------ .../LocomotivesGenericCollection.cs | 6 +++--- .../ElectricLocomotive/SetGeneric.cs | 14 ++++++++------ 3 files changed, 14 insertions(+), 21 deletions(-) diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs index 651cabd..051b4c6 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs @@ -3,15 +3,6 @@ using ElectricLocomotive.Generics; using Microsoft.Extensions.Logging; using ProjectElectricLocomotive; using ProjectElectricLocomotive.Exceptions; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; namespace ElectricLocomotive { @@ -113,11 +104,11 @@ namespace ElectricLocomotive MessageBox.Show("Объект добавлен"); CollectionPictureBox.Image = obj.ShowLocomotives(); _logger.LogInformation($"Добавлен объект {obj}"); - ; } else { MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); } } catch (StorageOverflowException ex) @@ -154,13 +145,13 @@ namespace ElectricLocomotive else { MessageBox.Show("Не удалось удалить объект"); - _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}"); + _logger.LogWarning($"Не найден объект по позиции: {pos}"); } } catch (LocoNotFoundException ex) { MessageBox.Show(ex.Message); - _logger.LogWarning($"Не найден объект по позиции: {obj}"); + _logger.LogWarning($"Не найден объект по позиции: {pos}"); } } diff --git a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs index 5b95146..41373ce 100644 --- a/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/LocomotivesGenericCollection.cs @@ -27,13 +27,13 @@ namespace ElectricLocomotive.Generics _pictureHeight = picHeight; _collection = new SetGeneric(width * height); } - public static int operator +(LocomotivesGenericCollection collect, T? loco) + public static int operator +(LocomotivesGenericCollection collect, T? locomotive) { - if (loco == null) + if (locomotive == null) { return -1; } - return collect._collection.Insert(loco); + return collect._collection.Insert(locomotive); } diff --git a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs index c7d91a1..92bc661 100644 --- a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs @@ -36,14 +36,16 @@ namespace ProjectElectricLocomotive.Generics _places.Insert(position, loco); return position; } - public bool Remove(int position) + public T? Remove(int position) { - if (position < 0 || position >= _places.Count) - { + if (position >= Count || position < 0) + return null; + + T? tmp = _places[position]; + if (tmp == null) throw new LocoNotFoundException(position); - } - _places.RemoveAt(position); - return true; + _places[position] = null; + return tmp; } public T? this[int position] { -- 2.25.1 From 24a7f06439732db3e69773e6cfdfa575bc6f5daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Wed, 27 Dec 2023 20:02:32 +0400 Subject: [PATCH 6/7] last --- .../ElectricLocomotive/FormLocomotiveCollection.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs index 051b4c6..2ae9e30 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveCollection.cs @@ -114,6 +114,7 @@ namespace ElectricLocomotive catch (StorageOverflowException ex) { MessageBox.Show(ex.Message); + _logger.LogInformation("Не удалось добавить объект"); } //проверяем, удалось ли нам загрузить объект -- 2.25.1 From 41e57526ba9ee090f4ff58d0841c46bcf18686a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=93=D0=BE=D1=80=D0=B4?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2?= <89176335310x@gmail.com> Date: Fri, 29 Dec 2023 10:55:57 +0400 Subject: [PATCH 7/7] GG --- ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs | 1 - ElectricLocomotive/ElectricLocomotive/SetGeneric.cs | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs index 33c1044..87d18ad 100644 --- a/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs +++ b/ElectricLocomotive/ElectricLocomotive/FormLocomotiveConfig.cs @@ -30,7 +30,6 @@ namespace ElectricLocomotive panelColorBlue.MouseDown += PanelColor_MouseDown; buttonCancelObject.Click += (s, e) => Close(); - } public void AddEvent(Action ev) { diff --git a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs index 92bc661..a308aca 100644 --- a/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs +++ b/ElectricLocomotive/ElectricLocomotive/SetGeneric.cs @@ -25,8 +25,7 @@ namespace ProjectElectricLocomotive.Generics public int Insert(T loco, int position) { - if (_places.Count >= _maxCount) - throw new StorageOverflowException(_maxCount); + if (position < 0 || position >= _maxCount) { -- 2.25.1