From 705355a3bad372084cf5c02d3e8568b855a7e33e Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Tue, 21 Nov 2023 20:53:23 +0400 Subject: [PATCH 1/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D0=BD?= =?UTF-8?q?=D0=B0=D1=87=D0=B0=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplaneNotFoundException.cs | 21 ++++++ .../AirplanesGenericStorage.cs | 20 +++--- .../FormAirplaneCollection.cs | 64 ++++++++++++------- .../AirplaneWithRadar/Program.cs | 21 +++++- .../StorageOverflowException.cs | 22 +++++++ .../AirplaneWithRadar/nlog.config | 13 ++++ 6 files changed, 128 insertions(+), 33 deletions(-) create mode 100644 AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs create mode 100644 AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs create mode 100644 AirplaneWithRadar/AirplaneWithRadar/nlog.config diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs new file mode 100644 index 0000000..3e24f0f --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace AirplaneWithRadar.Exceptoins +{ + [Serializable] + internal class AirplaneNotFoundException : ApplicationException + { + public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AirplaneNotFoundException() : base() { } + public AirplaneNotFoundException(string message) : base(message) { } + public AirplaneNotFoundException(string message, Exception exception) : + base(message, exception) { } + protected AirplaneNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index 1f5ae6d..d061c7e 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -96,7 +96,7 @@ namespace AirplaneWithRadar.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -115,24 +115,25 @@ namespace AirplaneWithRadar.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); + } using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}"); fs.Write(info, 0, info.Length); - return true; + return; } /// /// Загрузка информации по самолетам в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } string bufferTextFromFile = ""; using (FileStream fs = new(filename, FileMode.Open)) @@ -148,12 +149,13 @@ namespace AirplaneWithRadar.Generics StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); + } if (!strs[0].StartsWith("AirplaneStorage")) { //если нет такой записи, то это не те данные - return false; + throw new Exception("Неверный формат данных"); } _airplaneStorages.Clear(); foreach (string data in strs) @@ -176,13 +178,13 @@ namespace AirplaneWithRadar.Generics { if (!(collection + airplane)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); + } } } _airplaneStorages.Add(record[0], collection); } - return true; } } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index 40db2ed..1bc0988 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -1,15 +1,18 @@ -using System; +/*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.Threading.Tasks;*/ using System.Windows.Forms; +//using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.Generics; -using AirplaneWithRadar.MovementStrategy; +using AirplaneWithRadar.Exceptoins; +using Microsoft.Extensions.Logging; +//using NLog.Extensions.Logging; namespace AirplaneWithRadar { @@ -23,12 +26,17 @@ namespace AirplaneWithRadar /// private readonly AirplanesGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormAirplaneCollection() + public FormAirplaneCollection(ILogger logger) { InitializeComponent(); _storage = new AirplanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Обработка нажатия "Сохранение" @@ -39,15 +47,16 @@ namespace AirplaneWithRadar { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.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); } } } @@ -60,18 +69,18 @@ namespace AirplaneWithRadar { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - ReloadObjects(); } /// @@ -111,6 +120,7 @@ namespace AirplaneWithRadar } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -121,7 +131,6 @@ namespace AirplaneWithRadar { pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowAirplanes(); - } /// /// Удаление набора @@ -134,12 +143,13 @@ namespace AirplaneWithRadar { 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}"); } } /// @@ -202,15 +212,23 @@ namespace AirplaneWithRadar return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowAirplanes(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowAirplanes(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (AirplaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); } + } /// /// Обновление рисунка по набору diff --git a/AirplaneWithRadar/AirplaneWithRadar/Program.cs b/AirplaneWithRadar/AirplaneWithRadar/Program.cs index ec2131f..6d0e5fb 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/Program.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; + namespace AirplaneWithRadar { internal static class Program @@ -11,7 +16,21 @@ namespace AirplaneWithRadar // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAirplaneCollection()); + 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); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs b/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs new file mode 100644 index 0000000..2baf541 --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/StorageOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + + +namespace AirplaneWithRadar.Exceptoins +{ + [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/AirplaneWithRadar/AirplaneWithRadar/nlog.config b/AirplaneWithRadar/AirplaneWithRadar/nlog.config new file mode 100644 index 0000000..9d784f9 --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + -- 2.25.1 From 542144f95d4dab71e5004ead7178cd5f880a55cd Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Tue, 21 Nov 2023 21:11:31 +0400 Subject: [PATCH 2/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B8=D0=BB=D0=B0=20=D0=BF?= =?UTF-8?q?=D0=B0=D0=BA=D0=B5=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj index 13ee123..eb2b961 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj @@ -8,6 +8,11 @@ enable + + + + + True -- 2.25.1 From 62d6124a7999b2b7836d360faf775cb7ec01162a Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Wed, 22 Nov 2023 08:34:44 +0400 Subject: [PATCH 3/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D0=B8?= =?UTF-8?q?=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplaneWithRadar/AirplanesGenericStorage.cs | 5 ++--- .../AirplaneWithRadar/FormAirplaneCollection.cs | 2 ++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index d061c7e..f4f4ddf 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -72,9 +72,8 @@ namespace AirplaneWithRadar.Generics /// Название набора public void DelSet(string name) { - if (!_airplaneStorages.ContainsKey(name)) - return; - _airplaneStorages.Remove(name); + if (_airplaneStorages.ContainsKey(name)) + _airplaneStorages.Remove(name); } /// /// Доступ к набору diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index 1bc0988..2ed9279 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -81,6 +81,7 @@ namespace AirplaneWithRadar MessageBoxButtons.OK, MessageBoxIcon.Error); } } + ReloadObjects(); } /// @@ -217,6 +218,7 @@ namespace AirplaneWithRadar if (obj - pos != null) { MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект с позиции {pos}"); pictureBoxCollection.Image = obj.ShowAirplanes(); } else -- 2.25.1 From ef234a35ba25d3cef19a452688835cfe5195b8c1 Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Tue, 5 Dec 2023 20:59:54 +0400 Subject: [PATCH 4/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D0=B2=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=86=D0=B5=D1=81=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplaneWithRadar.csproj | 5 ++ .../AirplanesGenericStorage.cs | 41 ++++++++------ .../AirplaneWithRadar/AppSettings.json | 20 +++++++ .../AirplaneWithRadar/DrawningAirplane.cs | 12 ++--- .../FormAirplaneCollection.cs | 53 ++++++++++++------- .../AirplaneWithRadar/FormAirplaneConfig.cs | 2 + .../AirplaneWithRadar/Program.cs | 19 +++++-- .../AirplaneWithRadar/SetGeneric.cs | 19 ++++++- .../AirplaneWithRadar/nlog.config | 13 ----- 9 files changed, 124 insertions(+), 60 deletions(-) create mode 100644 AirplaneWithRadar/AirplaneWithRadar/AppSettings.json delete mode 100644 AirplaneWithRadar/AirplaneWithRadar/nlog.config diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj index eb2b961..2d6a006 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadar.csproj @@ -9,8 +9,13 @@ + + + + + diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index f4f4ddf..d9da00a 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.MovementStrategy; +using AirplaneWithRadar.Exceptoins; namespace AirplaneWithRadar.Generics { @@ -114,14 +115,13 @@ namespace AirplaneWithRadar.Generics } if (data.Length == 0) { - throw new Exception("Невалиданя операция, нет данных для сохранения"); + throw new ArgumentException("Невалиданя операция, нет данных для сохранения"); } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new - UTF8Encoding(true).GetBytes($"AirplaneStorage{Environment.NewLine}{data}"); - fs.Write(info, 0, info.Length); - return; + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write($"AirplaneStorage{Environment.NewLine}{data}"); + } } /// /// Загрузка информации по самолетам в хранилище из файла @@ -132,29 +132,28 @@ namespace AirplaneWithRadar.Generics { if (!File.Exists(filename)) { - throw new Exception("Файл не найден"); + throw new FileNotFoundException("Файл не найден"); } string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader reader = new StreamReader(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str; + while ((str = reader.ReadLine()) != null) { - bufferTextFromFile += temp.GetString(b); + bufferTextFromFile += str + '\r' + '\n'; } } var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - throw new Exception("Нет данных для загрузки"); + throw new ArgumentException("Нет данных для загрузки"); } if (!strs[0].StartsWith("AirplaneStorage")) { //если нет такой записи, то это не те данные - throw new Exception("Неверный формат данных"); + throw new InvalidDataException("Неверный формат данных"); } _airplaneStorages.Clear(); foreach (string data in strs) @@ -177,8 +176,18 @@ namespace AirplaneWithRadar.Generics { if (!(collection + airplane)) { - throw new Exception("Ошибка добавления в коллекцию"); - + try + { + _ = collection + airplane; + } + catch (AirplaneNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } } } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/AppSettings.json b/AirplaneWithRadar/AirplaneWithRadar/AppSettings.json new file mode 100644 index 0000000..0c69bec --- /dev/null +++ b/AirplaneWithRadar/AirplaneWithRadar/AppSettings.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": "AirplaneWithRadar" + } + } +} \ No newline at end of file diff --git a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs index fc95e9a..53c49b8 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs @@ -57,12 +57,12 @@ namespace AirplaneWithRadar.DrawningObjects /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height) { - _pictureWidth = width; - _pictureHeight = height; if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) { return; } + _pictureWidth = width; + _pictureHeight = height; EntityAirplane = new EntityAirplane(speed, weight, bodyColor); } /// @@ -78,14 +78,14 @@ namespace AirplaneWithRadar.DrawningObjects protected DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height, int airplaneWidth, int airplaneHeight) { - _pictureWidth = width; - _pictureHeight = height; - _airplaneWidth = airplaneWidth; - _airplaneHeight = airplaneHeight; if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) { return; } + _pictureWidth = width; + _pictureHeight = height; + _airplaneWidth = airplaneWidth; + _airplaneHeight = airplaneHeight; EntityAirplane = new EntityAirplane(speed, weight, bodyColor); } /// diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index 2ed9279..a6fbc28 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -1,18 +1,17 @@ -/*using System; +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.Threading.Tasks; using System.Windows.Forms; -//using AirplaneWithRadar.MovementStrategy; +using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.Generics; using AirplaneWithRadar.Exceptoins; using Microsoft.Extensions.Logging; -//using NLog.Extensions.Logging; namespace AirplaneWithRadar { @@ -52,11 +51,13 @@ namespace AirplaneWithRadar _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}"); } catch (Exception ex) { MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не прошло"); } } } @@ -74,14 +75,15 @@ namespace AirplaneWithRadar _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загружено из файла {openFileDialog.FileName}"); } catch (Exception ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла"); } } - ReloadObjects(); } /// @@ -173,21 +175,31 @@ namespace AirplaneWithRadar var formAirplaneConfig = new FormAirplaneConfig(); formAirplaneConfig.Show(); - Action? airplaneDelegate = new((m) => + formAirplaneConfig.AddEvent(AddAirplane); + } + private void AddAirplane(DrawningAirplane airplane) + { + if (listBoxStorages.SelectedIndex == -1) { - bool isAddSuccessful = (obj + m); - if (isAddSuccessful) - { - MessageBox.Show("Объект добавлен"); - m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); - pictureBoxCollection.Image = obj.ShowAirplanes(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - }); - formAirplaneConfig.AddEvent(airplaneDelegate); + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + return; + } + try + { + _ = obj + airplane; + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowAirplanes(); + _logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + } } /// @@ -212,9 +224,9 @@ namespace AirplaneWithRadar { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); if (obj - pos != null) { MessageBox.Show("Объект удален"); @@ -229,6 +241,7 @@ namespace AirplaneWithRadar catch (AirplaneNotFoundException ex) { MessageBox.Show(ex.Message); + _logger.LogWarning($"AirplaneNotFound: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs index 29caba0..4dd6312 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs @@ -9,6 +9,8 @@ using System.Threading.Tasks; using System.Windows.Forms; using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.Entities; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace AirplaneWithRadar { diff --git a/AirplaneWithRadar/AirplaneWithRadar/Program.cs b/AirplaneWithRadar/AirplaneWithRadar/Program.cs index 6d0e5fb..4baf5a0 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/Program.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/Program.cs @@ -1,6 +1,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; using System; namespace AirplaneWithRadar @@ -25,11 +31,18 @@ namespace AirplaneWithRadar } private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton() - .AddLogging(option => + 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}appsettings.json", optional: false, reloadOnChange: true).Build(); + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); + option.AddSerilog(logger); }); } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs index ba61aa2..32e4402 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using AirplaneWithRadar.Exceptoins; namespace AirplaneWithRadar.Generics { @@ -56,7 +57,14 @@ namespace AirplaneWithRadar.Generics /// public bool Insert(T airplane, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) return false; + if (Count >= _maxCount) + { + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new StorageOverflowException("Невозможно добавить"); + } _places.Insert(position, airplane); return true; } @@ -67,7 +75,14 @@ namespace AirplaneWithRadar.Generics /// public bool Remove(int position) { - if (position < 0 || position >= Count) return false; + if (position >= Count || position < 0) + { + throw new AirplaneNotFoundException("Невалидная операция"); + } + if (_places[position] == null) + { + throw new AirplaneNotFoundException(position); + } _places.RemoveAt(position); return true; } diff --git a/AirplaneWithRadar/AirplaneWithRadar/nlog.config b/AirplaneWithRadar/AirplaneWithRadar/nlog.config deleted file mode 100644 index 9d784f9..0000000 --- a/AirplaneWithRadar/AirplaneWithRadar/nlog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - -- 2.25.1 From e016aa1b8ed923dbb5c533e960e1c592c21e1265 Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Wed, 6 Dec 2023 01:03:31 +0400 Subject: [PATCH 5/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D0=BD?= =?UTF-8?q?=D0=B0=D0=B4=D0=BE=20=D0=BF=D0=BE=D0=B4=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=BF=D0=BE=D0=B7=D0=B8=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplaneWithRadarForm.cs | 2 +- .../AirplanesGenericCollection.cs | 2 +- .../AirplaneWithRadar/DrawningAirplane.cs | 4 +-- .../DrawningAirplaneWithRadar.cs | 2 +- .../FormAirplaneCollection.cs | 5 +-- .../FormAirplaneConfig.Designer.cs | 4 +-- .../AirplaneWithRadar/FormAirplaneConfig.cs | 35 +++++++++++++++---- 7 files changed, 39 insertions(+), 15 deletions(-) diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadarForm.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadarForm.cs index 02fbcbe..71cb855 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadarForm.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplaneWithRadarForm.cs @@ -28,7 +28,7 @@ namespace AirplaneWithRadar /// /// Выбранный самолет /// - public DrawningAirplane? SelectedAirplane { get; private set; } + public DrawningAirplane? SelectedAirplane { get; set; } /// /// Инициализация формы diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs index c9f54cf..ee633e1 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs @@ -133,7 +133,7 @@ namespace AirplaneWithRadar.Generics int i = 0; foreach (var airplane in _collection.GetAirplanes()) { - if (airplane!= null) + if (airplane != null) { airplane.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); if (airplane is DrawningAirplaneWithRadar) diff --git a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs index 53c49b8..b53e938 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs @@ -57,7 +57,7 @@ namespace AirplaneWithRadar.DrawningObjects /// true - объект создан, false - проверка не пройдена, нельзя создать объект в этих размерах public DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height) { - if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) + if (width <= _airplaneWidth || height <= _airplaneHeight) { return; } @@ -78,7 +78,7 @@ namespace AirplaneWithRadar.DrawningObjects protected DrawningAirplane(int speed, double weight, Color bodyColor, int width, int height, int airplaneWidth, int airplaneHeight) { - if (_pictureWidth < _airplaneWidth || _pictureHeight < _airplaneHeight) + if (width <= _airplaneWidth || height <= _airplaneHeight) { return; } diff --git a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplaneWithRadar.cs b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplaneWithRadar.cs index 89e8a80..4f48d16 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplaneWithRadar.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplaneWithRadar.cs @@ -50,7 +50,6 @@ namespace AirplaneWithRadar.DrawningObjects g.FillRectangle(additionalBrush, _startPosX + 85, _startPosY + 35, 10, 5); g.DrawRectangle(penBlack, _startPosX + 85, _startPosY + 35, 10, 5); } - base.DrawTransport(g); // Штырь if (airplaneWithRadar.Pin) { @@ -63,6 +62,7 @@ namespace AirplaneWithRadar.DrawningObjects g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 70, _startPosY + 65), new Point(_startPosX + 60, _startPosY + 72), new Point(_startPosX + 70, _startPosY + 80) }); g.FillPolygon(additionalBrush, new Point[] { new Point(_startPosX + 115, _startPosY + 65), new Point(_startPosX + 125, _startPosY + 72), new Point(_startPosX + 115, _startPosY + 80) }); } + base.DrawTransport(g); } public void SetAddColor(Color color) { diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index a6fbc28..6593ce9 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -230,18 +230,19 @@ namespace AirplaneWithRadar if (obj - pos != null) { MessageBox.Show("Объект удален"); - _logger.LogInformation($"Удален объект с позиции {pos}"); pictureBoxCollection.Image = obj.ShowAirplanes(); + _logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}"); } else { MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); } } catch (AirplaneNotFoundException ex) { MessageBox.Show(ex.Message); - _logger.LogWarning($"AirplaneNotFound: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); + _logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs index 134a209..b38d425 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.Designer.cs @@ -300,7 +300,7 @@ labelAdditionalColor.TabIndex = 13; labelAdditionalColor.Text = "Доп. цвет"; labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter; - labelAdditionalColor.DragDrop += labelColor_DragDrop; + labelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop; labelAdditionalColor.DragEnter += labelColor_DragEnter; // // labelBodyColor @@ -313,7 +313,7 @@ labelBodyColor.TabIndex = 12; labelBodyColor.Text = "Цвет"; labelBodyColor.TextAlign = ContentAlignment.MiddleCenter; - labelBodyColor.DragDrop += labelColor_DragDrop; + labelBodyColor.DragDrop += LabelBodyColor_DragDrop; labelBodyColor.DragEnter += labelColor_DragEnter; // // pictureBoxObject diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs index 4dd6312..584082d 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneConfig.cs @@ -101,18 +101,21 @@ namespace AirplaneWithRadar /// private void PanelObject_DragDrop(object sender, DragEventArgs e) { + ILogger logger = new NullLogger(); switch (e.Data?.GetData(DataFormats.Text).ToString()) { case "labelSimpleObject": + labelAdditionalColor.AllowDrop = false; + _airplane = new DrawningAirplane((int)numericUpDownSpeed.Value, - (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, - pictureBoxObject.Height); + (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height); break; case "labelModifiedObject": + labelAdditionalColor.AllowDrop = true; + _airplane = new DrawningAirplaneWithRadar((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.DimGray, checkBoxRadar.Checked, - checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, - pictureBoxObject.Height); + checkBoxTank.Checked, checkBoxPin.Checked, pictureBoxObject.Width, pictureBoxObject.Height); break; } DrawAirplane(); @@ -138,19 +141,39 @@ namespace AirplaneWithRadar { if (_airplane == null) return; + var color = e.Data.GetData(typeof(Color)); switch (((Label)sender).Name) { case "labelBodyColor": - _airplane.SetBodyColor((Color)e.Data.GetData(typeof(Color))); + _airplane.EntityAirplane.BodyColor = (Color)color; break; case "labelAdditionalColor": if (!(_airplane is DrawningAirplaneWithRadar)) return; - (_airplane as DrawningAirplaneWithRadar).SetAddColor((Color)e.Data.GetData(typeof(Color))); + (_airplane as DrawningAirplaneWithRadar).EntityAirplane.BodyColor = (Color)color; break; } DrawAirplane(); } + private void LabelBodyColor_DragDrop(object sender, DragEventArgs e) + { + var color = e.Data.GetData(typeof(Color)); + if (_airplane != null && color != null) + { + _airplane.EntityAirplane.BodyColor = (Color)color; + DrawAirplane(); + } + } + private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e) + { + var color = e.Data.GetData(typeof(Color)); + + if (_airplane != null && color != null && _airplane.EntityAirplane is EntityAirplaneWithRadar entityAirplaneWithRadar) + { + entityAirplaneWithRadar.AdditionalColor = (Color)color; + DrawAirplane(); + } + } private void labelColor_DragEnter(object sender, DragEventArgs e) { -- 2.25.1 From d177de49ad9e55c4990c48c170b4c9121ce5b4ea Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Tue, 19 Dec 2023 22:59:17 +0400 Subject: [PATCH 6/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207,=20=D1=8F=20?= =?UTF-8?q?=D1=82=D0=B0=D0=BA=20=D0=BF=D0=BE=D0=BB=D0=B0=D0=B3=D0=B0=D1=8E?= =?UTF-8?q?,=20=D0=B2=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD=D0=BE,=20=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=20=D0=B7=D0=BD=D0=B0=D0=B5=D1=82,=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D1=83=D0=B2=D0=B5=D1=80=D0=B5=D0=BD=D0=B0,=20=D0=B3=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplanesGenericStorage.cs | 83 ++++++++----------- .../FormAirplaneCollection.Designer.cs | 9 +- .../FormAirplaneCollection.cs | 61 +++++++------- .../FormAirplaneCollection.resx | 3 + .../AirplaneWithRadar/SetGeneric.cs | 2 +- 5 files changed, 77 insertions(+), 81 deletions(-) diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index d9da00a..e4218af 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using AirplaneWithRadar.DrawningObjects; using AirplaneWithRadar.MovementStrategy; using AirplaneWithRadar.Exceptoins; +using System.Numerics; namespace AirplaneWithRadar.Generics { @@ -115,7 +116,7 @@ namespace AirplaneWithRadar.Generics } if (data.Length == 0) { - throw new ArgumentException("Невалиданя операция, нет данных для сохранения"); + throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) @@ -132,66 +133,52 @@ namespace AirplaneWithRadar.Generics { if (!File.Exists(filename)) { - throw new FileNotFoundException("Файл не найден"); + throw new FileNotFoundException($"Файл {filename} не найден"); } - string bufferTextFromFile = ""; - using (StreamReader reader = new StreamReader(filename)) - { - string str; - while ((str = reader.ReadLine()) != null) - { - bufferTextFromFile += str + '\r' + '\n'; - } - } - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - throw new ArgumentException("Нет данных для загрузки"); - } - if (!strs[0].StartsWith("AirplaneStorage")) + using (StreamReader fs = File.OpenText(filename)) { - //если нет такой записи, то это не те данные - throw new InvalidDataException("Неверный формат данных"); - } - _airplaneStorages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) + string str = fs.ReadLine(); + if (str == null || str.Length == 0) { - continue; + throw new NullReferenceException("Нет данных для загрузки"); } - AirplanesGenericCollection - collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, - StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + if (!str.StartsWith("AirplaneStorage")) { - DrawningAirplane? airplane = - elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); - if (airplane != null) + //если нет такой записи, то это не те данные + throw new FormatException("Неверный формат данных"); + } + + _airplaneStorages.Clear(); + string strs = ""; + + while ((strs = fs.ReadLine()) != null) + { + if (strs == null) { - if (!(collection + airplane)) + throw new NullReferenceException("Нет данных для загрузки"); + } + + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + AirplanesGenericCollection collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); + if (airplane != null) { - try + if (!(collection + airplane)) { - _ = collection + airplane; - } - catch (AirplaneNotFoundException e) - { - throw e; - } - catch (StorageOverflowException e) - { - throw e; + throw new InvalidOperationException("Ошибка добавления в коллекцию"); } } } + _airplaneStorages.Add(record[0], collection); } - _airplaneStorages.Add(record[0], collection); } } } diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs index 94d8463..08ed5eb 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.Designer.cs @@ -185,14 +185,14 @@ // сохранениеToolStripMenuItem // сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem"; - сохранениеToolStripMenuItem.Size = new Size(180, 22); + сохранениеToolStripMenuItem.Size = new Size(141, 22); сохранениеToolStripMenuItem.Text = "Сохранение"; сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // // загрузкаToolStripMenuItem // загрузкаToolStripMenuItem.Name = "загрузкаToolStripMenuItem"; - загрузкаToolStripMenuItem.Size = new Size(180, 22); + загрузкаToolStripMenuItem.Size = new Size(141, 22); загрузкаToolStripMenuItem.Text = "Загрузка"; загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // @@ -210,6 +210,11 @@ // openFileDialog // openFileDialog.FileName = "openFileDialog1"; + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; // // FormAirplaneCollection // diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index 6593ce9..fd21250 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -84,6 +84,7 @@ namespace AirplaneWithRadar _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не прошла"); } } + ReloadObjects(); } /// @@ -144,10 +145,11 @@ namespace AirplaneWithRadar { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; - if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(name); @@ -164,6 +166,7 @@ namespace AirplaneWithRadar { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? @@ -175,33 +178,25 @@ namespace AirplaneWithRadar var formAirplaneConfig = new FormAirplaneConfig(); formAirplaneConfig.Show(); - formAirplaneConfig.AddEvent(AddAirplane); + Action? airplaneDelegate = new((m) => + { + bool isAddSuccessful = (obj + m); + if (isAddSuccessful) + { + MessageBox.Show("Объект добавлен"); + m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); + pictureBoxCollection.Image = obj.ShowAirplanes(); + _logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Набор переполнен! Не удалось добавить объект"); + _logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + } + }); + formAirplaneConfig.AddEvent(airplaneDelegate); } - private void AddAirplane(DrawningAirplane airplane) - { - if (listBoxStorages.SelectedIndex == -1) - { - return; - } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - if (obj == null) - { - return; - } - try - { - _ = obj + airplane; - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowAirplanes(); - _logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message); - _logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); - } - } - + /// /// Удаление объекта из набора /// @@ -222,21 +217,22 @@ namespace AirplaneWithRadar if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning("Отмена удаления объекта"); return; } try { - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); if (obj - pos != null) { MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowAirplanes(); _logger.LogInformation($"Удален объект с позиции {pos} из набора {listBoxStorages.SelectedItem.ToString()}"); + pictureBoxCollection.Image = obj.ShowAirplanes(); } else { MessageBox.Show("Не удалось удалить объект"); - _logger.LogInformation($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); + _logger.LogWarning($"Объект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); } } catch (AirplaneNotFoundException ex) @@ -244,6 +240,11 @@ namespace AirplaneWithRadar MessageBox.Show(ex.Message); _logger.LogWarning($"Самолет не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } + catch (FormatException) + { + _logger.LogWarning($"Было введено не число"); + MessageBox.Show("Введите число"); + } } /// diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx index f53194e..715a914 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.resx @@ -120,6 +120,9 @@ 17, 17 + + 17, 17 + 132, 17 diff --git a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs index 32e4402..9389b5e 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs @@ -75,7 +75,7 @@ namespace AirplaneWithRadar.Generics /// public bool Remove(int position) { - if (position >= Count || position < 0) + if (position >= Count || position < 0 || position > _maxCount) { throw new AirplaneNotFoundException("Невалидная операция"); } -- 2.25.1 From 925cc7a006fe0be8471e75d5d4584a0c0b2fbe12 Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Wed, 20 Dec 2023 02:08:29 +0400 Subject: [PATCH 7/7] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B07,=20=D0=B3=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=D0=B0=D1=8F,=20=D0=BD=D0=BE=20=D0=B1=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=D0=B5=20=D1=83=D0=B2=D0=B5=D1=80=D0=B5=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AirplanesGenericCollection.cs | 12 ++---- .../AirplanesGenericStorage.cs | 9 ++-- .../AirplaneWithRadar/DrawningAirplane.cs | 4 +- .../FormAirplaneCollection.cs | 42 ++++++++++++------- .../AirplaneWithRadar/SetGeneric.cs | 29 ++++--------- 5 files changed, 43 insertions(+), 53 deletions(-) diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs index ee633e1..8ee3f99 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericCollection.cs @@ -60,13 +60,13 @@ namespace AirplaneWithRadar.Generics /// /// /// - public static bool operator +(AirplanesGenericCollection collect, T? obj) + public static int operator +(AirplanesGenericCollection collect, T? obj) { if (obj == null) { - return false; + return -1; } - return (bool)collect?._collection.Insert(obj); + return collect._collection.Insert(obj); } /// /// Перегрузка оператора вычитания @@ -78,11 +78,7 @@ namespace AirplaneWithRadar.Generics pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } - return false; + return collect._collection.Remove(pos); } /// /// Получение объекта IMoveableObject diff --git a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs index e4218af..5783b50 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/AirplanesGenericStorage.cs @@ -63,10 +63,9 @@ namespace AirplaneWithRadar.Generics /// Название набора public void AddSet(string name) { - if (_airplaneStorages.ContainsKey(name)) - return; - _airplaneStorages[name] = new AirplanesGenericCollection(_pictureWidth, _pictureHeight); + if (!_airplaneStorages.ContainsKey(name)) + _airplaneStorages.Add(name,new AirplanesGenericCollection(_pictureWidth, _pictureHeight)); } /// /// Удаление набора @@ -171,7 +170,7 @@ namespace AirplaneWithRadar.Generics DrawningAirplane? airplane = elem?.CreateDrawningAirplane(_separatorForObject, _pictureWidth, _pictureHeight); if (airplane != null) { - if (!(collection + airplane)) + if (collection + airplane == -1) { throw new InvalidOperationException("Ошибка добавления в коллекцию"); } diff --git a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs index b53e938..66d417f 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/DrawningAirplane.cs @@ -25,11 +25,11 @@ namespace AirplaneWithRadar.DrawningObjects /// /// Ширина окна /// - private int _pictureWidth; + public int _pictureWidth; /// /// Высота окна /// - private int _pictureHeight; + public int _pictureHeight; /// /// /// Левая координата прорисовки самолета /// diff --git a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs index fd21250..631e6a6 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/FormAirplaneCollection.cs @@ -169,34 +169,44 @@ namespace AirplaneWithRadar _logger.LogWarning("Коллекция не выбрана"); return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; - if (obj == null) + var formAirplaneConfig = new FormAirplaneConfig(); + formAirplaneConfig.AddEvent(AddAirplane); + formAirplaneConfig.Show(); + } + private void AddAirplane(DrawningAirplane airplane) + { + airplane._pictureWidth = pictureBoxCollection.Image.Width; + airplane._pictureHeight = pictureBoxCollection.Image.Height; + if (listBoxStorages.SelectedIndex == -1) { return; } - - var formAirplaneConfig = new FormAirplaneConfig(); - formAirplaneConfig.Show(); - Action? airplaneDelegate = new((m) => + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { - bool isAddSuccessful = (obj + m); - if (isAddSuccessful) + _logger.LogWarning($"Не удалось добавить объект: набор пуст"); + return; + } + try + { + if (obj + airplane != -1) { MessageBox.Show("Объект добавлен"); - m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); pictureBoxCollection.Image = obj.ShowAirplanes(); - _logger.LogInformation($"Самолет добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + _logger.LogInformation($"Объект добавлен {airplane}"); } else { - MessageBox.Show("Набор переполнен! Не удалось добавить объект"); - _logger.LogWarning($"Самолет не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); + MessageBox.Show("Не удалось добавить объект"); } - }); - formAirplaneConfig.AddEvent(airplaneDelegate); + } + catch (ApplicationException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } } - + /// /// Удаление объекта из набора /// diff --git a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs index 9389b5e..d318640 100644 --- a/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs +++ b/AirplaneWithRadar/AirplaneWithRadar/SetGeneric.cs @@ -40,14 +40,9 @@ namespace AirplaneWithRadar.Generics /// /// Добавляемый самолет /// - public bool Insert(T airplane) + public int Insert(T airplane) { - if (_places.Count == _maxCount) - { - return false; - } - Insert(airplane, 0); - return true; + return Insert(airplane, 0); } /// /// Добавление объекта в набор на конкретную позицию @@ -55,18 +50,14 @@ namespace AirplaneWithRadar.Generics /// Добавляемый самолет /// Позиция /// - public bool Insert(T airplane, int position) + public int Insert(T airplane, int position) { + if (position < 0 || position > Count) + throw new AirplaneNotFoundException(position); if (Count >= _maxCount) - { throw new StorageOverflowException(_maxCount); - } - if (position < 0 || position >= _maxCount) - { - throw new StorageOverflowException("Невозможно добавить"); - } _places.Insert(position, airplane); - return true; + return position; } /// /// Удаление объекта из набора с конкретной позиции @@ -75,14 +66,8 @@ namespace AirplaneWithRadar.Generics /// public bool Remove(int position) { - if (position >= Count || position < 0 || position > _maxCount) - { - throw new AirplaneNotFoundException("Невалидная операция"); - } - if (_places[position] == null) - { + if (position >= Count || position < 0) throw new AirplaneNotFoundException(position); - } _places.RemoveAt(position); return true; } -- 2.25.1