From 668d6a7a7f974fb716cda71bb798e799f27e78bb Mon Sep 17 00:00:00 2001 From: Adelina888 Date: Thu, 9 May 2024 22:08:07 +0400 Subject: [PATCH 1/3] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 39 ++--- .../MassiveGenericObjects.cs | 15 +- .../StorageCollection.cs | 36 +++-- .../StormtrooperSharingService.cs | 10 +- .../Exceptions/CollectionOverflowException.cs | 22 +++ .../Exceptions/ObjectNotFoundException.cs | 21 +++ .../PositionOutOfCollectionException.cs | 20 +++ .../FormStormtrooperCollection.cs | 141 ++++++++++++------ ProjectStormtrooper/Program.cs | 28 +++- .../ProjectStormtrooper.csproj | 18 +++ ProjectStormtrooper/serilog.config | 13 ++ 11 files changed, 267 insertions(+), 96 deletions(-) create mode 100644 ProjectStormtrooper/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectStormtrooper/serilog.config diff --git a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 64df773..16cfc50 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectStormtrooper.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -48,23 +49,18 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position>=0 && position < _collection.Count) - { - return _collection[position]; - } - return null; + if (position>=Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора - if (_collection.Count <= _maxCount) - { - _collection.Add(obj); - return _collection.Count; - } - return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; + } public int Insert(T obj, int position) @@ -72,25 +68,20 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции - if (position >= 0 && position < _maxCount && _collection.Count <= _maxCount) - { - _collection.Insert(position, obj); - return position; - } - return -1; + 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 < 0 || position > _maxCount) - { - return null; - } - T temp = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } public IEnumerable GetItems() diff --git a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 0194fec..656733e 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectStormtrooper.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -52,7 +53,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // проверка позиции - if (position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + //if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } @@ -69,7 +71,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) @@ -79,7 +81,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до // TODO вставка - if (position >= _collection.Length || position < 0) return -1; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; @@ -105,14 +107,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index--; } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null - if(position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T temp = _collection[position]; _collection[position] = null; return temp; diff --git a/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs index e0aad9b..80d8390 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectStormtrooper.Drawnings; +using ProjectStormtrooper.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -95,12 +96,12 @@ 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)) { @@ -133,30 +134,30 @@ public class StorageCollection writer.Write(_separatorItems); } } - 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 = ""; @@ -171,7 +172,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -179,15 +180,24 @@ public class StorageCollection { if (elem?.CreateDrawningStormtrooper() is T stormtrooper) { - if (collection.Insert(stormtrooper) == -1) + try { - return false; + if (collection.Insert(stormtrooper) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию" + record[3]); + } } + catch(CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } + + } } _storages.Add(record[0], collection); } - return true; + } } /// diff --git a/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs b/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs index 4fed574..c556794 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs @@ -44,11 +44,15 @@ public class StormtrooperSharingService : AbstractCompany int curHeight = 0; 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 + 15, curHeight * _placeSizeHeight + 3); + if (_collection.Get(i) != null) + { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 15, curHeight * _placeSizeHeight + 3); + } } + catch (Exception) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs b/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..83adace --- /dev/null +++ b/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectStormtrooper.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException:ApplicationException +{ + public CollectionOverflowException(int count): base("В коллекции превышено допустимое количество: count" + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message): base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info,StreamingContext context) : base(info, context) { } + + +} diff --git a/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs b/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..5fd15b9 --- /dev/null +++ b/ProjectStormtrooper/Exceptions/ObjectNotFoundException.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 ProjectStormtrooper.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) { } + +} diff --git a/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs b/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..4d499af --- /dev/null +++ b/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectStormtrooper.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/ProjectStormtrooper/FormStormtrooperCollection.cs b/ProjectStormtrooper/FormStormtrooperCollection.cs index 348a4e8..0566c63 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.cs +++ b/ProjectStormtrooper/FormStormtrooperCollection.cs @@ -1,5 +1,7 @@ -using ProjectStormtrooper.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectStormtrooper.CollectionGenericObjects; using ProjectStormtrooper.Drawnings; +using ProjectStormtrooper.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -22,16 +24,22 @@ public partial class FormStormtrooperCollection : Form /// private readonly StorageCollection _storageCollection; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Компания /// private AbstractCompany? _company; /// /// Конструктор /// - public FormStormtrooperCollection() + public FormStormtrooperCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } @@ -64,18 +72,24 @@ public partial class FormStormtrooperCollection : Form /// private void SetStormtrooper(DrawningStormtrooperBase stormtrooper) { - if (_company == null || stormtrooper == null) + try { - return; + if (_company == null || stormtrooper == null) + { + return; + } + if (_company + stormtrooper != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект:" + stormtrooper.GetDataForSave); + } } - if (_company + stormtrooper != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -86,10 +100,7 @@ public partial class FormStormtrooperCollection : Form /// private void ButtonRemoveStormtrooper_Click(object sender, EventArgs e) { - if (_company == null) - { - return; - } + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; @@ -99,14 +110,19 @@ public partial class FormStormtrooperCollection : Form return; } int pos = Convert.ToInt32(maskedTextBox.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); } } /// @@ -122,24 +138,27 @@ public partial class FormStormtrooperCollection : Form } DrawningStormtrooperBase? stormtrooper = null; int counter = 100; - while (stormtrooper == null) + try { - stormtrooper = _company.GetRandomObject(); - counter--; - if (counter < -0) + while (stormtrooper == null) { - break; + stormtrooper = _company.GetRandomObject(); + counter--; + if (counter < -0) + { + break; + } } + FormStormtrooper form = new() + { + SetStormtrooper = stormtrooper + }; + form.ShowDialog(); } - if (stormtrooper == null) + catch(Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormStormtrooper form = new() - { - SetStormtrooper = stormtrooper - }; - form.ShowDialog(); } /// /// Перерисовка коллекции @@ -165,19 +184,26 @@ public partial class FormStormtrooperCollection : Form MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); 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(); - } /// /// Удаление коллекции @@ -195,12 +221,21 @@ public partial class FormStormtrooperCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + try { - return; + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция:" + listBoxCollection.SelectedItem.ToString() + "удалена"); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + catch(Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } /// /// Добавление списка в listBoxCollection @@ -254,16 +289,20 @@ public partial class FormStormtrooperCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } } /// @@ -276,17 +315,21 @@ public partial class FormStormtrooperCollection : Form // TODO продумать логику 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("Загрузка не удалась", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } } diff --git a/ProjectStormtrooper/Program.cs b/ProjectStormtrooper/Program.cs index 41063d3..29149d9 100644 --- a/ProjectStormtrooper/Program.cs +++ b/ProjectStormtrooper/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace ProjectStormtrooper { internal static class Program @@ -11,7 +17,27 @@ namespace ProjectStormtrooper // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormStormtrooperCollection()); + ServiceCollection service = new(); + ConfigureServices(service); + using ServiceProvider serviceProvider = service.BuildServiceProvider(); + + Application.Run(serviceProvider.GetRequiredService()); + } + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .WriteTo.File("log.txt") + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectStormtrooper/ProjectStormtrooper.csproj b/ProjectStormtrooper/ProjectStormtrooper.csproj index 244387d..c32975c 100644 --- a/ProjectStormtrooper/ProjectStormtrooper.csproj +++ b/ProjectStormtrooper/ProjectStormtrooper.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectStormtrooper/serilog.config b/ProjectStormtrooper/serilog.config new file mode 100644 index 0000000..84300c8 --- /dev/null +++ b/ProjectStormtrooper/serilog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 9688585e321521cda0efe899a88c6621d1e50b54 Mon Sep 17 00:00:00 2001 From: Adelina888 Date: Mon, 13 May 2024 21:19:14 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=B7=D0=B0=D0=BA=D0=BE=D0=BD=D1=87=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BD=D0=B0=D1=8F=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 15 +++++++-- .../ListGenericObjects.cs | 4 +-- .../MassiveGenericObjects.cs | 2 +- .../StormtrooperSharingService.cs | 6 ++-- .../Drawnings/DrawingStormtrooper.cs | 4 +-- .../Drawnings/DrawingStormtrooperBase.cs | 4 +-- .../FormStormtrooperCollection.Designer.cs | 6 ++-- .../FormStormtrooperCollection.cs | 32 ++++++++++--------- .../FormStormtrooperCollection.resx | 3 ++ 9 files changed, 45 insertions(+), 31 deletions(-) diff --git a/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs b/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs index 5898eec..71e19ad 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -9,7 +9,7 @@ public abstract class AbstractCompany /// /// Размер места (ширина) /// - protected readonly int _placeSizeWidth = 210; + protected readonly int _placeSizeWidth = 220; /// /// Размер места (высота) /// @@ -22,10 +22,15 @@ public abstract class AbstractCompany /// Высота окна /// protected readonly int _pictureHeight; + protected static int amountOfObjects = 0; /// /// Коллекция штурмовика /// protected ICollectionGenericObjects? _collection = null; + public static int getAmountOfObjects() + { + return amountOfObjects; + } /// /// Вычисление максимального количества элементов, который можно разместить в окне /// @@ -85,8 +90,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningStormtrooperBase? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningStormtrooperBase? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; } diff --git a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 16cfc50..73ce612 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -79,9 +79,9 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции // TODO удаление объекта из списка if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); - T obj = _collection[position]; + T temp = _collection[position]; _collection.RemoveAt(position); - return obj; + return temp; } public IEnumerable GetItems() diff --git a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 656733e..3738366 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -54,7 +54,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects { // проверка позиции if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); - //if (_collection[position] == null) throw new ObjectNotFoundException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } diff --git a/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs b/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs index c556794..04c94f0 100644 --- a/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs +++ b/ProjectStormtrooper/CollectionGenericObjects/StormtrooperSharingService.cs @@ -46,15 +46,15 @@ public class StormtrooperSharingService : AbstractCompany { try { - if (_collection.Get(i) != null) - { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 15, curHeight * _placeSizeHeight + 3); - } + } catch (Exception) { } if (curWidth > 0) curWidth--; + else { curWidth = width - 1; diff --git a/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs index eae3cd5..e1d4d01 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooper.cs @@ -20,7 +20,7 @@ public class DrawingStormtrooper: DrawningStormtrooperBase /// /// - public DrawingStormtrooper(int speed,double weight, Color bodyColor,Color additionalColor, bool rockets, bool bombs):base(140,140) + public DrawingStormtrooper(int speed,double weight, Color bodyColor,Color additionalColor, bool rockets, bool bombs):base(140,135) { EntityStormtrooperBase = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, rockets, bombs); @@ -62,7 +62,7 @@ public class DrawingStormtrooper: DrawningStormtrooperBase g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 40, 10, 10); g.DrawRectangle(pen, _startPosX.Value + 50, _startPosY.Value + 90, 10, 10); } - + } diff --git a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs index e386756..5ac903e 100644 --- a/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs +++ b/ProjectStormtrooper/Drawnings/DrawingStormtrooperBase.cs @@ -36,7 +36,7 @@ public class DrawningStormtrooperBase /// Высота прорисовки /// - private readonly int _drawningStormtooperHeight = 140; + private readonly int _drawningStormtooperHeight = 135; /// /// Координата Х объекта @@ -215,7 +215,7 @@ public class DrawningStormtrooperBase Pen pen = new(Color.Black); Brush bodyColorBrush = new SolidBrush(EntityStormtrooperBase.BodyColor); - + //нос штурмовика Brush brBlack = new SolidBrush(Color.Black); diff --git a/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs b/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs index 1992de9..006cca3 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs +++ b/ProjectStormtrooper/FormStormtrooperCollection.Designer.cs @@ -68,7 +68,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(911, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(173, 604); + groupBoxTools.Size = new Size(173, 646); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -248,7 +248,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(911, 604); + pictureBox.Size = new Size(911, 646); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // @@ -296,7 +296,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1084, 628); + ClientSize = new Size(1084, 670); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/ProjectStormtrooper/FormStormtrooperCollection.cs b/ProjectStormtrooper/FormStormtrooperCollection.cs index 0566c63..77b5c1c 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.cs +++ b/ProjectStormtrooper/FormStormtrooperCollection.cs @@ -100,7 +100,7 @@ public partial class FormStormtrooperCollection : Form /// private void ButtonRemoveStormtrooper_Click(object sender, EventArgs e) { - + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; @@ -110,6 +110,7 @@ public partial class FormStormtrooperCollection : Form return; } int pos = Convert.ToInt32(maskedTextBox.Text); + int tempSize = StormtrooperSharingService.getAmountOfObjects(); try { if (_company - pos != null) @@ -119,7 +120,7 @@ public partial class FormStormtrooperCollection : Form _logger.LogInformation("Удален объект по позиции" + pos); } } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); _logger.LogError("Ошибка: {Message}", ex.Message); @@ -140,22 +141,23 @@ public partial class FormStormtrooperCollection : Form int counter = 100; try { + while (stormtrooper == null) { stormtrooper = _company.GetRandomObject(); counter--; - if (counter < -0) + if (counter <= 0) { break; } } - FormStormtrooper form = new() + FormStormtrooper form = new(); { - SetStormtrooper = stormtrooper + SetStormtrooper(stormtrooper); }; form.ShowDialog(); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -200,7 +202,7 @@ public partial class FormStormtrooperCollection : Form RerfreshListBoxItems(); _logger.LogInformation("Коллекция добавлена" + textBoxCollectionName.Text); } - catch(Exception ex) + catch (Exception ex) { _logger.LogError("Ошибка: {Message}", ex.Message); } @@ -231,11 +233,11 @@ public partial class FormStormtrooperCollection : Form RerfreshListBoxItems(); _logger.LogInformation("Коллекция:" + listBoxCollection.SelectedItem.ToString() + "удалена"); } - catch(Exception ex) + catch (Exception ex) { _logger.LogError("Ошибка: {Message}", ex.Message); } - + } /// /// Добавление списка в listBoxCollection @@ -302,7 +304,7 @@ public partial class FormStormtrooperCollection : Form MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } } /// @@ -323,20 +325,20 @@ public partial class FormStormtrooperCollection : Form RerfreshListBoxItems(); _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } - + } } - - - + + + } diff --git a/ProjectStormtrooper/FormStormtrooperCollection.resx b/ProjectStormtrooper/FormStormtrooperCollection.resx index 8b1dfa1..ca20953 100644 --- a/ProjectStormtrooper/FormStormtrooperCollection.resx +++ b/ProjectStormtrooper/FormStormtrooperCollection.resx @@ -126,4 +126,7 @@ 261, 17 + + 25 + \ No newline at end of file -- 2.25.1 From eac299fe2c3186ad1acdfa9e4ee67ec4c3aa031d Mon Sep 17 00:00:00 2001 From: Adelina888 Date: Tue, 14 May 2024 10:01:44 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=BC=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectStormtrooper/Exceptions/CollectionOverflowException.cs | 2 +- ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs | 2 +- .../Exceptions/PositionOutOfCollectionException.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs b/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs index 83adace..4b68566 100644 --- a/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs +++ b/ProjectStormtrooper/Exceptions/CollectionOverflowException.cs @@ -12,7 +12,7 @@ namespace ProjectStormtrooper.Exceptions; [Serializable] internal class CollectionOverflowException:ApplicationException { - public CollectionOverflowException(int count): base("В коллекции превышено допустимое количество: count" + count) { } + public CollectionOverflowException(int count): base("В коллекции превышено допустимое количество: count " + count) { } public CollectionOverflowException() : base() { } public CollectionOverflowException(string message): base(message) { } public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } diff --git a/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs b/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs index 5fd15b9..fbd2976 100644 --- a/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs +++ b/ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs @@ -12,7 +12,7 @@ namespace ProjectStormtrooper.Exceptions; [Serializable] internal class ObjectNotFoundException:ApplicationException { - public ObjectNotFoundException(int i): base("Не найден объект по позиции" + i) { } + public ObjectNotFoundException(int i): base("Не найден объект по позиции " + i) { } public ObjectNotFoundException() : base() { } public ObjectNotFoundException(string message) : base(message) { } public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } diff --git a/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs b/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs index 4d499af..3eabe01 100644 --- a/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectStormtrooper/Exceptions/PositionOutOfCollectionException.cs @@ -12,7 +12,7 @@ namespace ProjectStormtrooper.Exceptions; [Serializable] internal class PositionOutOfCollectionException:ApplicationException { - public PositionOutOfCollectionException(int i):base("Выход за границы коллекции. Позиция" + i) { } + public PositionOutOfCollectionException(int i):base("Выход за границы коллекции. Позиция " + i) { } public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException(string message) : base(message) { } public PositionOutOfCollectionException(string message, Exception exception): base(message, exception) { } -- 2.25.1