From 8322c1fcafa8f0b4e8564e08822251640a726f7a Mon Sep 17 00:00:00 2001 From: Aleksandr4350 Date: Wed, 12 Jun 2024 15:15:23 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 9 +- .../ListGenericObjects.cs | 35 +++-- .../MassiveGenericObjects.cs | 21 ++- .../PlaneSharingService.cs | 3 +- .../StorageCollection.cs | 62 ++++++--- .../Exceptions/CollectionOverflowException.cs | 20 +++ .../Exceptions/ObjectNotFoundException.cs | 21 +++ .../PositionOutOfCollectionException.cs | 23 ++++ .../ProjectSportCar/FormPlaneCollection.cs | 126 +++++++++++++----- ProjectSportCar/ProjectSportCar/Program.cs | 32 ++++- .../ProjectSportCar/ProjectAiroplane.csproj | 18 +++ ProjectSportCar/ProjectSportCar/serilog.json | 15 +++ 12 files changed, 300 insertions(+), 85 deletions(-) create mode 100644 ProjectSportCar/ProjectSportCar/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectSportCar/ProjectSportCar/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectSportCar/ProjectSportCar/serilog.json diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs index c1a481e..27926a8 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs @@ -81,11 +81,16 @@ public abstract class AbstractCompany Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); DrawBackgound(graphics); + SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - Drawningplane? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + Drawningplane? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; } diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs index f2e124e..3b856da 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,7 @@ -namespace ProjectAiroplane.CollectionGenericObjects; +using ProjectAiroplane.Exceptions; + +namespace ProjectAiroplane.CollectionGenericObjects; + public class ListGenericObjects : ICollectionGenericObjects where T : class { @@ -36,38 +39,34 @@ public class ListGenericObjects : ICollectionGenericObjects { _collection = new(); } - public T? Get(int position) + public T Get(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; - return _collection[position];// индексатор + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count == _maxCount) return -1; - _collection.Add(obj);//метод + if (Count == _maxCount) throw new CollectionOverflowException(); + _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; - _collection.Insert(position, obj);//метод + if (Count == _maxCount) throw new CollectionOverflowException(Count); + + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); return position; } public T Remove(int position) { // TODO проверка позиции // TODO удаление объекта из списка - if (position >= Count || position < 0) return null; - T obj = _collection[position]; - _collection.RemoveAt(position);//метод - return obj; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T temp = _collection[position]; + _collection.RemoveAt(position); + return temp; } public IEnumerable GetItems() diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs index 03e13e8..7c0b71b 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectAiroplane.CollectionGenericObjects; +using ProjectAiroplane.Exceptions; + +namespace ProjectAiroplane.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -49,7 +51,9 @@ where T : class { // TODO проверка позиции if (position >= _collection.Length || position < 0) - { return null; } + { throw new PositionOutOfCollectionException(position); } + + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) @@ -66,7 +70,7 @@ where T : class index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { @@ -76,7 +80,9 @@ where T : class // если нет после, ищем до // TODO вставка if (position >= _collection.Length || position < 0) - { return -1; } + { + throw new PositionOutOfCollectionException(position); + } if (_collection[position] == null) { @@ -102,7 +108,7 @@ where T : class return position; } } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) { @@ -110,7 +116,10 @@ where T : class // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null if (position >= _collection.Length || position < 0) - { return null; } + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) throw new ObjectNotFoundException(position); T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/PlaneSharingService.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/PlaneSharingService.cs index 3cd73f1..3915124 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/PlaneSharingService.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/PlaneSharingService.cs @@ -34,11 +34,12 @@ public class PlaneSharingService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 2); } + catch (Exception) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs index 849fdf8..93ac2b7 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAiroplane.Drawnings; +using ProjectAiroplane.Exceptions; using System.Text; namespace ProjectAiroplane.CollectionGenericObjects; @@ -87,38 +88,43 @@ public class StorageCollection /// true - сохранение прошло успешно, false - ошибка при ///сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } + if (File.Exists(filename)) { File.Delete(filename); } + using (StreamWriter writer = new StreamWriter(filename)) + { writer.Write(_collectionKey); foreach (KeyValuePair> value in _storages) + { StringBuilder sb = new(); sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции if (value.Value.Count == 0) + { continue; } + sb.Append(value.Key); sb.Append(_separatorForKeyValue); sb.Append(value.Value.GetCollectionType); sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); - foreach (T? item in value.Value.GetItems()) + { - string data = item?.GetDataForSave() ?? string.Empty;/////////////////////// + string data = item?.GetDataForSave() ?? string.Empty; if (string.IsNullOrEmpty(data)) { continue; @@ -126,73 +132,87 @@ public class StorageCollection sb.Append(data); sb.Append(_separatorItems); } + writer.Write(sb); } - } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла/// true - загрузка прошла успешно, false - ошибка при загрузке ///данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } + _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { - // - if (strs == null) - { - return false; - } + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) { continue; } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType);//////////////////CreateCollection + if (collection == null) + { - return false; + throw new Exception("Не удалось создать коллекцию"); } + collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) + { if (elem?.CreateDrawningplane() is T airoplane)//////////////////////////////////////////////////////////////////CreateDrawningplane() + { - if (collection.Insert(airoplane) == -1) + try + { - return false; + if (collection.Insert(airoplane) == -1) + + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + + { + throw new Exception("Коллекция переполнена", ex); + } + } + } _storages.Add(record[0], collection); } - return true; - } } diff --git a/ProjectSportCar/ProjectSportCar/Exceptions/CollectionOverflowException.cs b/ProjectSportCar/ProjectSportCar/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..16dacf4 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectAiroplane.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..a239c59 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System.Runtime.Serialization; + +namespace ProjectAiroplane.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + + public ObjectNotFoundException() : base() { } + + public ObjectNotFoundException(string message) : base(message) { } + + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectSportCar/ProjectSportCar/Exceptions/PositionOutOfCollectionException.cs b/ProjectSportCar/ProjectSportCar/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..22ff0b9 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; + +namespace ProjectAiroplane.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + + public PositionOutOfCollectionException() : base() { } + + public PositionOutOfCollectionException(string message) : base(message) { } + + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs b/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs index 74254e5..e6968b6 100644 --- a/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs +++ b/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs @@ -1,5 +1,7 @@ -using ProjectAiroplane.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAiroplane.CollectionGenericObjects; using ProjectAiroplane.Drawnings; +using ProjectAiroplane.Exceptions; using System.Windows.Forms; namespace ProjectAiroplane; @@ -14,15 +16,20 @@ public partial class FormPlaneCollection : Form /// /// Хранилище коллеций /// + /// private readonly StorageCollection _storageCollection; + private readonly ILogger _logger; + /// /// Конструктор /// - public FormPlaneCollection() + public FormPlaneCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// Выбор компании @@ -52,22 +59,37 @@ public partial class FormPlaneCollection : Form /// /// Добавление самолёта в коллекцию /// - /// + /// private void SetPlane(Drawningplane? plane) { - if (_company == null || plane == null) + try { - return; + if (_company == null || plane == null) + { + return; + } + + if (_company + plane != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + plane.GetDataForSave()); + } } - if (_company + plane != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + catch (ObjectNotFoundException) { MessageBox.Show("Не удалось добавить объект"); + } - else + + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show("Выход за границы коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -87,15 +109,23 @@ public partial class FormPlaneCollection : Form { return; } + int pos = Convert.ToInt32(maskedTextBox1.Text); - if (_company - pos != null) + + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } /// @@ -152,21 +182,30 @@ public partial class FormPlaneCollection : Form { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); } /// @@ -185,12 +224,20 @@ public partial class FormPlaneCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); } /// @@ -243,31 +290,38 @@ public partial class FormPlaneCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } + } private void loadToolStripMenuItem_Click_1(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectSportCar/ProjectSportCar/Program.cs b/ProjectSportCar/ProjectSportCar/Program.cs index c1bf899..fa36dc2 100644 --- a/ProjectSportCar/ProjectSportCar/Program.cs +++ b/ProjectSportCar/ProjectSportCar/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; +using System; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace ProjectAiroplane { internal static class Program @@ -11,7 +17,31 @@ namespace ProjectAiroplane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormPlaneCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider servicesProvider = services.BuildServiceProvider(); + Application.Run(servicesProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectSportCar/ProjectSportCar/ProjectAiroplane.csproj b/ProjectSportCar/ProjectSportCar/ProjectAiroplane.csproj index 244387d..4d8762f 100644 --- a/ProjectSportCar/ProjectSportCar/ProjectAiroplane.csproj +++ b/ProjectSportCar/ProjectSportCar/ProjectAiroplane.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectSportCar/ProjectSportCar/serilog.json b/ProjectSportCar/ProjectSportCar/serilog.json new file mode 100644 index 0000000..fa91ef7 --- /dev/null +++ b/ProjectSportCar/ProjectSportCar/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1 From f58ea26eb5ef03a1b802ed472478a284c7c52806 Mon Sep 17 00:00:00 2001 From: Aleksandr4350 Date: Wed, 12 Jun 2024 17:36:43 +0400 Subject: [PATCH 2/4] lab 7/0 --- .../CollectionGenericObjects/StorageCollection.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs index 93ac2b7..fb5a3c1 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/StorageCollection.cs @@ -90,9 +90,9 @@ public class StorageCollection public void SaveData(string filename) { - if (_storages.Count == 0) + if (_storages.Count < 1) { - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + throw new InvalidDataException("В хранилище отсутсвуют коллекции для сохранения"); } if (File.Exists(filename)) -- 2.25.1 From 75c7be6da35748076622e48d913f0bc18eb046ca Mon Sep 17 00:00:00 2001 From: Aleksandr4350 Date: Wed, 12 Jun 2024 19:58:09 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs index 27926a8..0b45261 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/AbstractCompany.cs @@ -28,7 +28,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместитьв окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-1; /// /// Конструктор /// -- 2.25.1 From 3a938f63494014cfb9c6ed468969039680365c4d Mon Sep 17 00:00:00 2001 From: Aleksandr4350 Date: Fri, 14 Jun 2024 08:14:29 +0400 Subject: [PATCH 4/4] , --- .../CollectionGenericObjects/MassiveGenericObjects.cs | 2 +- .../ProjectSportCar/Exceptions/ObjectNotFoundException.cs | 2 +- ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs index 7c0b71b..cd89687 100644 --- a/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectSportCar/ProjectSportCar/CollectionGenericObjects/MassiveGenericObjects.cs @@ -119,7 +119,7 @@ where T : class { throw new PositionOutOfCollectionException(position); } - if (_collection[position] == null) throw new ObjectNotFoundException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position);//выброс1 T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs index a239c59..d2d9d0e 100644 --- a/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs +++ b/ProjectSportCar/ProjectSportCar/Exceptions/ObjectNotFoundException.cs @@ -9,7 +9,7 @@ namespace ProjectAiroplane.Exceptions; [Serializable] internal class ObjectNotFoundException : ApplicationException { - public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }//обработка1 public ObjectNotFoundException() : base() { } diff --git a/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs b/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs index e6968b6..5949fca 100644 --- a/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs +++ b/ProjectSportCar/ProjectSportCar/FormPlaneCollection.cs @@ -77,7 +77,7 @@ public partial class FormPlaneCollection : Form } } - catch (ObjectNotFoundException) { MessageBox.Show("Не удалось добавить объект"); + catch (ObjectNotFoundException) { MessageBox.Show("Не удалось добавить объект");//ловлю ошибку1 } -- 2.25.1