From 92f5da95a6bc1376ba197d96e2be33ae54ea859f Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Wed, 1 May 2024 16:28:32 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=D0=9D=D0=B5=D0=B4=D0=BE=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ICollectionGenericObjects.cs | 2 +- .../ListGenericObjects.cs | 49 ++++----- .../MassiveGenericObjects.cs | 68 ++++++------ .../StorageCollection.cs | 29 +++-- .../Exceptions/CollectionOverflowException.cs | 25 +++++ .../Exceptions/ObjectNotFoundException.cs | 21 ++++ .../PositionOutOfCollectionException.cs | 21 ++++ .../FormAircraftCollection.Designer.cs | 1 - .../Stormtrooper/FormAircraftCollection.cs | 101 +++++++++++++----- Stormtrooper/Stormtrooper/Program.cs | 33 +++++- Stormtrooper/Stormtrooper/Stormtrooper.csproj | 9 ++ Stormtrooper/Stormtrooper/appSetting.json | 20 ++++ 12 files changed, 270 insertions(+), 109 deletions(-) create mode 100644 Stormtrooper/Stormtrooper/Exceptions/CollectionOverflowException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/ObjectNotFoundException.cs create mode 100644 Stormtrooper/Stormtrooper/Exceptions/PositionOutOfCollectionException.cs create mode 100644 Stormtrooper/Stormtrooper/appSetting.json diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index 29e71ba..12d793b 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -30,7 +30,7 @@ where T : class /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj, int position); + bool Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs index bf71592..6d8108a 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using Stormtrooper.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -36,47 +37,35 @@ where T : class } public T? Get(int position) { - // TODO проверка позиции - if( position>= 0 && position < Count) - { - return _collection[position]; - } - return null; + if (position < 0 || position >= _collection.Count) + throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count <= _maxCount) + if (_collection.Count + 1 <= _maxCount) { _collection.Add(obj); - return Count; + return _collection.Count - 1; } - return -1; + throw new CollectionOverflowException(MaxCount); } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count < _maxCount && position>=0 && position < _maxCount) - { - _collection.Insert(position, obj); - return position; - } - return -1; + if (_collection.Count + 1 > MaxCount) + throw new CollectionOverflowException(MaxCount); + if (position < 0 || position >= MaxCount) + throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); + return true; } public T Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка + if (position < 0 || position >= _collection.Count) + throw new PositionOutOfCollectionException(position); T temp = _collection[position]; - if(position>=0 && position < _maxCount) - { - _collection.RemoveAt(position); - return temp; - } - return null; + _collection.RemoveAt(position); + return temp; } public IEnumerable GetItems() diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index aebd7fc..4245b49 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; +using System.CodeDom; namespace Stormtrooper.CollectionGenericObjects; @@ -47,67 +49,61 @@ where T : class } public T? Get(int position) { - // проверка позиции - if (position >= _collection.Length || position < 0) - { - return null; - } + if (position < 0 || position >= _collection.Length) + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - // вставка в свободное место набора - int index = 0; - while (index < _collection.Length) + for (int i = 0; i < _collection.Length; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return i; } - index++; } - return -1; + throw new CollectionOverflowException(_collection.Length); } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { - - if (position >= _collection.Length || position < 0) - { return -1; } - - if (_collection[position] == null) + if (position < 0 || position >= _collection.Length) // проверка позиции + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) // Попытка вставить на указанную позицию { _collection[position] = obj; - return position; + return true; } - int index; - - for (index = position + 1; index < _collection.Length; ++index) + for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[position] = obj; - return position; + _collection[i] = obj; + return true; } } - - for (index = position - 1; index >= 0; --index) + for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[position] = obj; - return position; + _collection[i] = obj; + return true; } } - return -1; + throw new CollectionOverflowException(_collection.Length); } + public T Remove(int position) { - if (position >= _collection.Length || position < 0) - { return null; } - T DrawningAircraft = _collection[position]; + if (position < 0 || position >= _collection.Length) // проверка позиции + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + T temp = _collection[position]; _collection[position] = null; - return DrawningAircraft; + return temp; } public IEnumerable GetItems() diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index 20407b5..e7db10d 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using Stormtrooper.CollectionGenericObjects; using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -98,11 +99,11 @@ where T : DrawningAircraft /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } @@ -148,25 +149,23 @@ where T : DrawningAircraft } } - 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 sr = new StreamReader(filename))// открываем файла на чтение { string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - return false; + throw new Exception("Неверные данные"); _storages.Clear(); @@ -184,7 +183,7 @@ where T : DrawningAircraft ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось определить тип коллекции"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -194,15 +193,23 @@ where T : DrawningAircraft { if (elem?.CreateDrawningAircraft() is T aircraft) { - if (collection.Insert(aircraft) == -1) - return false; + try + { + if (collection.Insert(aircraft) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - return true; } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { diff --git a/Stormtrooper/Stormtrooper/Exceptions/CollectionOverflowException.cs b/Stormtrooper/Stormtrooper/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..5a579ca --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Stormtrooper.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public 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) { } +} diff --git a/Stormtrooper/Stormtrooper/Exceptions/ObjectNotFoundException.cs b/Stormtrooper/Stormtrooper/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..b2cd58e --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System.Runtime.Serialization; + + +namespace Stormtrooper.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/Stormtrooper/Stormtrooper/Exceptions/PositionOutOfCollectionException.cs b/Stormtrooper/Stormtrooper/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..5371d59 --- /dev/null +++ b/Stormtrooper/Stormtrooper/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,21 @@ +using System.Runtime.Serialization; + + +namespace Stormtrooper.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/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs index 0613a06..09b9374 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs @@ -285,7 +285,6 @@ loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.Size = new Size(227, 26); loadToolStripMenuItem.Text = "Загрузка"; - loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // // saveFileDialog // diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs index c550944..5fca7eb 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs @@ -1,5 +1,7 @@ -using Stormtrooper.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using Stormtrooper.CollectionGenericObjects; using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -25,13 +27,19 @@ public partial class FormAircraftCollection : Form /// private AbstractCompany? _company; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormAircraftCollection() + public FormAircraftCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -62,42 +70,72 @@ public partial class FormAircraftCollection : Form { return; } - - if (_company + aircraft != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + aircraft != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавление самолета {aircraft} в коллекцию", aircraft); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить самолет {aircraft} в коллекцию", aircraft); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Ошибка переполнения коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } + /// + /// Кнопка удаления самолета + /// + /// + /// private void ButtonRemoveAircraft_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + try { - return; + if (MessageBox.Show("Удалить объект?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + int pos = Convert.ToInt32(maskedTextBox.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален!"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление самолета по индексу {pos}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить самолет из коллекции по индексу {pos}", pos); + + } } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + catch (ObjectNotFoundException ex) { - MessageBox.Show("Объект удален!"); - pictureBox.Image = _company.Show(); + MessageBox.Show("Ошибка: отсутствует объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } - else + catch (PositionOutOfCollectionException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Ошибка: неправильная позиция"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - private void ButtonGoToCheck_Click(object sender, EventArgs e) + private void ButtonGoToCheck_Click(object sender, EventArgs e) { if (_company == null) { @@ -146,8 +184,8 @@ public partial class FormAircraftCollection : 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; @@ -160,6 +198,7 @@ public partial class FormAircraftCollection : Form collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); RerfreshListBoxItems(); } @@ -184,6 +223,7 @@ public partial class FormAircraftCollection : Form return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } @@ -244,13 +284,15 @@ public partial class FormAircraftCollection : 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -260,18 +302,21 @@ public partial class FormAircraftCollection : Form /// /// /// - private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + private void loadToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.LoadData(openFileDialog.FileName); RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/Stormtrooper/Stormtrooper/Program.cs b/Stormtrooper/Stormtrooper/Program.cs index 8d32d67..f17f11a 100644 --- a/Stormtrooper/Stormtrooper/Program.cs +++ b/Stormtrooper/Stormtrooper/Program.cs @@ -1,4 +1,10 @@ -namespace Stormtrooper +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; +using Stormtrooper; + +namespace Battleship { internal static class Program { @@ -11,7 +17,30 @@ namespace Stormtrooper // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAircraftCollection()); + 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 => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "C:\\Users\\User\\Desktop\\2sem\\Egovoop\\lab1\\Stormtrooper\\Stormtrooper\\appSetting.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Stormtrooper.csproj b/Stormtrooper/Stormtrooper/Stormtrooper.csproj index 244387d..7d4a893 100644 --- a/Stormtrooper/Stormtrooper/Stormtrooper.csproj +++ b/Stormtrooper/Stormtrooper/Stormtrooper.csproj @@ -8,6 +8,15 @@ enable + + + + + + + + + True diff --git a/Stormtrooper/Stormtrooper/appSetting.json b/Stormtrooper/Stormtrooper/appSetting.json new file mode 100644 index 0000000..d97e26c --- /dev/null +++ b/Stormtrooper/Stormtrooper/appSetting.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": "Stormtrooper" + } + } +} -- 2.25.1 From 44f7ef01e8d74dcc00e43b8860ed1161257f2017 Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Wed, 1 May 2024 17:15:59 +0300 Subject: [PATCH 2/6] 2 --- .../MassiveGenericObjects.cs | 23 ++++--- .../StorageCollection.cs | 32 ++++----- Stormtrooper/Stormtrooper/Program.cs | 67 +++++++++---------- Stormtrooper/Stormtrooper/Stormtrooper.csproj | 5 +- 4 files changed, 65 insertions(+), 62 deletions(-) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index 4245b49..fa61f9e 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,31 +1,33 @@ -using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; +using Stormtrooper.CollectionGenericObjects; using Stormtrooper.Exceptions; -using System.CodeDom; namespace Stormtrooper.CollectionGenericObjects; - /// /// Параметризованный набор объектов /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects -where T : class + where T : class { /// /// Массив объектов, которые храним /// private T?[] _collection; - public int Count => _collection.Length; - - public int MaxCount { + /// + /// Установка максимального кол-ва объектов + /// + public int MaxCount + { get { return _collection.Length; } set { - if (value > 0) { + if (value > 0) + { if (_collection.Length > 0) { Array.Resize(ref _collection, value); @@ -47,6 +49,11 @@ where T : class { _collection = Array.Empty(); } + /// + /// Получение объекта по позиции + /// + /// Позиция (индекс) + /// public T? Get(int position) { if (position < 0 || position >= _collection.Length) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index e7db10d..797dbf2 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -52,22 +52,23 @@ where T : DrawningAircraft /// /// Название коллекции /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления - if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) + return; + switch (collectionType) { - if (collectionType == CollectionType.List) - { + case CollectionType.List: _storages.Add(name, new ListGenericObjects()); - } - else if (collectionType == CollectionType.Massive) - { + break; + case CollectionType.Massive: _storages.Add(name, new MassiveGenericObjects()); - } + break; + default: + break; } } + /// /// Удаление коллекции /// @@ -82,15 +83,12 @@ where T : DrawningAircraft /// /// Название коллекции /// - public ICollectionGenericObjects? this[string name] + public ICollectionGenericObjects? this[string name] { get { - // TODO Продумать логику получения объекта - if (_storages.ContainsKey(name)) - { - return _storages[name]; - } + if (_storages.TryGetValue(name, out ICollectionGenericObjects? value)) + return value; return null; } } @@ -112,8 +110,6 @@ where T : DrawningAircraft File.Delete(filename); } - - using FileStream fs = new(filename, FileMode.Create); using StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_collectionKey); diff --git a/Stormtrooper/Stormtrooper/Program.cs b/Stormtrooper/Stormtrooper/Program.cs index f17f11a..f9bc13c 100644 --- a/Stormtrooper/Stormtrooper/Program.cs +++ b/Stormtrooper/Stormtrooper/Program.cs @@ -4,43 +4,42 @@ using Microsoft.Extensions.Configuration; using Serilog; using Stormtrooper; -namespace Battleship +namespace Stormtrooper; + +internal static class Program { - internal static class Program + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - 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 => - { - var configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path: "C:\\Users\\User\\Desktop\\2sem\\Egovoop\\lab1\\Stormtrooper\\Stormtrooper\\appSetting.json", optional: false, reloadOnChange: true) - .Build(); - - var logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .CreateLogger(); - - option.SetMinimumLevel(LogLevel.Information); - option.AddSerilog(logger); - }); + Application.Run(serviceProvider.GetRequiredService()); } } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "C:\\Users\\User\\Desktop\\2sem\\Egovoop\\lab1\\Stormtrooper\\Stormtrooper\\appSetting.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); + } } \ No newline at end of file diff --git a/Stormtrooper/Stormtrooper/Stormtrooper.csproj b/Stormtrooper/Stormtrooper/Stormtrooper.csproj index 7d4a893..ec6b790 100644 --- a/Stormtrooper/Stormtrooper/Stormtrooper.csproj +++ b/Stormtrooper/Stormtrooper/Stormtrooper.csproj @@ -9,9 +9,10 @@ + + + - - -- 2.25.1 From a272e8dbd0a1fcdb6bd3ce6bc64cb02f3e76f294 Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Wed, 1 May 2024 17:20:31 +0300 Subject: [PATCH 3/6] 3 --- .../MassiveGenericObjects.cs | 83 ++++++++++--------- 1 file changed, 44 insertions(+), 39 deletions(-) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index fa61f9e..bfd8836 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -56,63 +56,68 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// public T? Get(int position) { - if (position < 0 || position >= _collection.Length) - throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); + // проверка позиции + if (position >= _collection.Length || position < 0) + { + return null; + } return _collection[position]; } public int Insert(T obj) { - for (int i = 0; i < _collection.Length; i++) + // вставка в свободное место набора + int index = 0; + while (index < _collection.Length) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; - return i; + _collection[index] = obj; + return index; } + index++; } - throw new CollectionOverflowException(_collection.Length); + return -1; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { - if (position < 0 || position >= _collection.Length) // проверка позиции - throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) // Попытка вставить на указанную позицию + + if (position >= _collection.Length || position < 0) + { return -1; } + + if (_collection[position] == null) { _collection[position] = obj; - return true; + return position; } - for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной - { - if (_collection[i] == null) - { - _collection[i] = obj; - return true; - } - } - for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной - { - if (_collection[i] == null) - { - _collection[i] = obj; - return true; - } - } - throw new CollectionOverflowException(_collection.Length); - } + int index; + for (index = position + 1; index < _collection.Length; ++index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + + for (index = position - 1; index >= 0; --index) + { + if (_collection[index] == null) + { + _collection[position] = obj; + return position; + } + } + return -1; + } public T Remove(int position) { - if (position < 0 || position >= _collection.Length) // проверка позиции - throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); - T temp = _collection[position]; + if (position >= _collection.Length || position < 0) + { return null; } + T DrawningAircraft = _collection[position]; _collection[position] = null; - return temp; + return DrawningAircraft; } - public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) -- 2.25.1 From 4dfab08ee68331f1e22de08789ac07b13fc82e67 Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Wed, 1 May 2024 18:17:48 +0300 Subject: [PATCH 4/6] 4 --- .../AbstractCompany.cs | 14 +++++++--- .../AircraftHangarService.cs | 13 +++++---- .../ListGenericObjects.cs | 19 ++++++++++++- .../MassiveGenericObjects.cs | 28 +++++++++++-------- .../StorageCollection.cs | 17 ++++------- 5 files changed, 58 insertions(+), 33 deletions(-) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs index 7fa344c..5fddf33 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; namespace Stormtrooper.CollectionGenericObjects; @@ -92,12 +93,17 @@ public abstract class AbstractCompany { Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + DrawBackground(graphics); + SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningAircraft? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningAircraft? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) { }; } return bitmap; } @@ -105,7 +111,7 @@ public abstract class AbstractCompany /// Вывод заднего фона /// /// - protected abstract void DrawBackgound(Graphics g); + protected abstract void DrawBackground(Graphics g); /// /// Расстановка объектов diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs index 63282a7..c67dbdc 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs @@ -1,4 +1,5 @@ using Stormtrooper.Drawnings; +using Stormtrooper.Exceptions; namespace Stormtrooper.CollectionGenericObjects { @@ -17,7 +18,7 @@ namespace Stormtrooper.CollectionGenericObjects ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) { } - protected override void DrawBackgound(Graphics g) + protected override void DrawBackground(Graphics g) { int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; @@ -41,18 +42,17 @@ namespace Stormtrooper.CollectionGenericObjects 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 + 10, curHeight * _placeSizeHeight + 10); } - + catch (ObjectNotFoundException) { } if (curWidth > 0) curWidth--; else { - curWidth = width - 1; - curHeight ++; + curWidth = width - 1; + curHeight++; } if (curHeight >= height) @@ -63,3 +63,4 @@ namespace Stormtrooper.CollectionGenericObjects } } } + diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs index 6d8108a..a920646 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -24,7 +24,21 @@ where T : class private int _maxCount; public int Count => _collection.Count; - public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } } + public int MaxCount + { + set + { + if (value > 0) + { + _maxCount = value; + } + } + get + { + + return Count; + } + } public CollectionType GetCollectionType => CollectionType.List; @@ -41,6 +55,7 @@ where T : class throw new PositionOutOfCollectionException(position); return _collection[position]; } + public int Insert(T obj) { if (_collection.Count + 1 <= _maxCount) @@ -50,6 +65,7 @@ where T : class } throw new CollectionOverflowException(MaxCount); } + public bool Insert(T obj, int position) { if (_collection.Count + 1 > MaxCount) @@ -59,6 +75,7 @@ where T : class _collection.Insert(position, obj); return true; } + public T Remove(int position) { if (position < 0 || position >= _collection.Count) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index bfd8836..d545787 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -59,7 +59,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects // проверка позиции if (position >= _collection.Length || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); } return _collection[position]; } @@ -76,18 +80,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index++; } - return -1; + throw new CollectionOverflowException(_collection.Length); } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { if (position >= _collection.Length || position < 0) - { return -1; } + { throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) { _collection[position] = obj; - return position; + return true; } int index; @@ -96,7 +100,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[index] == null) { _collection[position] = obj; - return position; + return true; } } @@ -105,18 +109,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (_collection[index] == null) { _collection[position] = obj; - return position; + return true; } } - return -1; + throw new CollectionOverflowException(_collection.Length); } public T Remove(int position) { if (position >= _collection.Length || position < 0) - { return null; } - T DrawningAircraft = _collection[position]; + { throw new PositionOutOfCollectionException(position); } + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + T temp = _collection[position]; _collection[position] = null; - return DrawningAircraft; + return temp; } public IEnumerable GetItems() { diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index 797dbf2..d9af62f 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -154,32 +154,28 @@ where T : DrawningAircraft { if (!File.Exists(filename)) { - throw new Exception("Файл не существует"); + throw new FileNotFoundException("Файл не существует"); } - using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение + + using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - throw new Exception("Неверные данные"); - + throw new FormatException("В файле неверные данные"); _storages.Clear(); - while ((str = sr.ReadLine()) != null) { string[] record = str.Split(_separatorForKeyValue); - - if (record.Length != 4) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - throw new Exception("Не удалось определить тип коллекции"); + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -191,7 +187,7 @@ where T : DrawningAircraft { try { - if (collection.Insert(aircraft) == -1) + if (collection.Insert(ship) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } @@ -202,7 +198,6 @@ where T : DrawningAircraft } } } - _storages.Add(record[0], collection); } } -- 2.25.1 From dd959915105c52857620ec656a4ab0774fd0a6ee Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Wed, 1 May 2024 23:12:01 +0300 Subject: [PATCH 5/6] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D1=8B=D0=B9?= =?UTF-8?q?=20=D0=B2=D0=B0=D1=80=D0=B8=D0=B0=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 10 +- .../AircraftHangarService.cs | 1 + .../ICollectionGenericObjects.cs | 2 +- .../ListGenericObjects.cs | 33 +++--- .../MassiveGenericObjects.cs | 99 ++++++++-------- .../StorageCollection.cs | 2 +- .../FormAircraftCollection.Designer.cs | 11 +- .../Stormtrooper/FormAircraftCollection.cs | 110 +++++++++--------- Stormtrooper/Stormtrooper/Program.cs | 27 +++-- .../{appSetting.json => serilogConfig.json} | 0 10 files changed, 146 insertions(+), 149 deletions(-) rename Stormtrooper/Stormtrooper/{appSetting.json => serilogConfig.json} (100%) diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs index 5fddf33..380341f 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AbstractCompany.cs @@ -36,8 +36,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); - + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор /// @@ -103,10 +102,15 @@ public abstract class AbstractCompany DrawningAircraft? obj = _collection?.Get(i); obj?.DrawTransport(graphics); } - catch (ObjectNotFoundException) { }; + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } + return bitmap; } + /// /// Вывод заднего фона /// diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs index c67dbdc..96fe711 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/AircraftHangarService.cs @@ -47,6 +47,7 @@ namespace Stormtrooper.CollectionGenericObjects _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); } catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (curWidth > 0) curWidth--; else diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index 12d793b..29e71ba 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -30,7 +30,7 @@ where T : class /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - bool Insert(T obj, int position); + int Insert(T obj, int position); /// /// Удаление объекта из коллекции с конкретной позиции diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs index a920646..eb0d568 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -49,43 +49,36 @@ where T : class { _collection = new(); } - public T? Get(int position) + public T Get(int position) { - if (position < 0 || position >= _collection.Count) - throw new PositionOutOfCollectionException(position); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - if (_collection.Count + 1 <= _maxCount) - { - _collection.Add(obj); - return _collection.Count - 1; - } - throw new CollectionOverflowException(MaxCount); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { - if (_collection.Count + 1 > MaxCount) - throw new CollectionOverflowException(MaxCount); - if (position < 0 || position >= MaxCount) - throw new PositionOutOfCollectionException(position); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return true; + return position; } public T Remove(int position) { - if (position < 0 || position >= _collection.Count) - throw new PositionOutOfCollectionException(position); - T temp = _collection[position]; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } - public IEnumerable GetItems() +public IEnumerable GetItems() { for (int i = 0; i < Count; ++i) { diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs index d545787..4819b3b 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -56,71 +56,76 @@ public class MassiveGenericObjects : ICollectionGenericObjects /// public T? Get(int position) { - // проверка позиции - if (position >= _collection.Length || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - if (_collection[position] == null) - { - throw new ObjectNotFoundException(position); - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } + public int Insert(T obj) { - // вставка в свободное место набора - int index = 0; - while (index < _collection.Length) + // вставка в свободное место набора + for (int i = 0; i < Count; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return i; } - index++; } - throw new CollectionOverflowException(_collection.Length); + + throw new CollectionOverflowException(Count); } - public bool Insert(T obj, int position) + + public int Insert(T obj, int position) { + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (position >= _collection.Length || position < 0) - { throw new PositionOutOfCollectionException(position); } - - if (_collection[position] == null) + if (_collection[position] != null) { - _collection[position] = obj; - return true; - } - int index; - - for (index = position + 1; index < _collection.Length; ++index) - { - if (_collection[index] == null) + bool pushed = false; + for (int index = position + 1; index < Count; index++) { - _collection[position] = obj; - return true; + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + + if (!pushed) + { + for (int index = position - 1; index >= 0; index--) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + } + + if (!pushed) + { + throw new CollectionOverflowException(Count); } } - for (index = position - 1; index >= 0; --index) - { - if (_collection[index] == null) - { - _collection[position] = obj; - return true; - } - } - throw new CollectionOverflowException(_collection.Length); + // вставка + _collection[position] = obj; + return position; } - public T Remove(int position) + + public T? Remove(int position) { - if (position >= _collection.Length || position < 0) - { throw new PositionOutOfCollectionException(position); } - if (_collection[position] == null) - throw new ObjectNotFoundException(position); - T temp = _collection[position]; + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + + if (_collection[position] == null) throw new ObjectNotFoundException(position); + + T? temp = _collection[position]; _collection[position] = null; return temp; } diff --git a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs index d9af62f..75bf013 100644 --- a/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs +++ b/Stormtrooper/Stormtrooper/CollectionGenericObjects/StorageCollection.cs @@ -187,7 +187,7 @@ where T : DrawningAircraft { try { - if (collection.Insert(ship) == -1) + if (collection.Insert(aircraft) == -1) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); } diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs index 09b9374..3cc8154 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.Designer.cs @@ -66,9 +66,9 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(980, 28); + groupBoxTools.Location = new Point(959, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(264, 649); + groupBoxTools.Size = new Size(264, 660); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Tag = ""; @@ -250,7 +250,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(980, 649); + pictureBox.Size = new Size(959, 660); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -260,7 +260,7 @@ menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1244, 28); + menuStrip.Size = new Size(1223, 28); menuStrip.TabIndex = 2; menuStrip.Text = "menuStrip1"; // @@ -285,6 +285,7 @@ loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.Size = new Size(227, 26); loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; // // saveFileDialog // @@ -298,7 +299,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1244, 677); + ClientSize = new Size(1223, 688); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); diff --git a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs index 5fca7eb..50b9227 100644 --- a/Stormtrooper/Stormtrooper/FormAircraftCollection.cs +++ b/Stormtrooper/Stormtrooper/FormAircraftCollection.cs @@ -72,22 +72,16 @@ public partial class FormAircraftCollection : Form } try { - if (_company + aircraft != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавление самолета {aircraft} в коллекцию", aircraft); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - _logger.LogInformation("Не удалось добавить самолет {aircraft} в коллекцию", aircraft); - } + var res = _company + aircraft; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBox.Image = _company.Show(); } - catch (CollectionOverflowException ex) + catch (Exception ex) { - MessageBox.Show("Ошибка переполнения коллекции"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -102,40 +96,30 @@ public partial class FormAircraftCollection : Form { return; } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBox.Text); try { - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален!"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Удаление самолета по индексу {pos}", pos); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogInformation("Не удалось удалить самолет из коллекции по индексу {pos}", pos); - - } + var res = _company - pos; + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); + pictureBox.Image = _company.Show(); } - catch (ObjectNotFoundException ex) + catch (Exception ex) { - MessageBox.Show("Ошибка: отсутствует объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show("Ошибка: неправильная позиция"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } - private void ButtonGoToCheck_Click(object sender, EventArgs e) + private void ButtonGoToCheck_Click(object sender, EventArgs e) { if (_company == null) { @@ -181,13 +165,13 @@ public partial class FormAircraftCollection : Form /// private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } + CollectionType collectionType = CollectionType.None; if (radioButtonMassive.Checked) { @@ -197,9 +181,19 @@ public partial class FormAircraftCollection : Form { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); - RerfreshListBoxItems(); + + try + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } /// @@ -209,23 +203,21 @@ public partial class FormAircraftCollection : Form /// private void ButtonCollectionDel_Click(object sender, EventArgs e) { - // TODO прописать логику удаления элемента из коллекции - // нужно убедиться, что есть выбранная коллекция - // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись - // удалить и обновить ListBox if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } /// @@ -241,7 +233,8 @@ public partial class FormAircraftCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -252,12 +245,12 @@ public partial class FormAircraftCollection : Form { case "Хранилище": _company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); - } /// /// Обновление списка в listBoxCollection @@ -290,7 +283,8 @@ public partial class FormAircraftCollection : Form MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) { + catch (Exception ex) + { MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } diff --git a/Stormtrooper/Stormtrooper/Program.cs b/Stormtrooper/Stormtrooper/Program.cs index f9bc13c..eea7db2 100644 --- a/Stormtrooper/Stormtrooper/Program.cs +++ b/Stormtrooper/Stormtrooper/Program.cs @@ -2,15 +2,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Serilog; -using Stormtrooper; + namespace Stormtrooper; internal static class Program { - /// - /// The main entry point for the application. - /// [STAThread] static void Main() { @@ -24,20 +21,22 @@ internal static class Program Application.Run(serviceProvider.GetRequiredService()); } } + private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton() - .AddLogging(option => + services.AddSingleton().AddLogging(option => { - var configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path: "C:\\Users\\User\\Desktop\\2sem\\Egovoop\\lab1\\Stormtrooper\\Stormtrooper\\appSetting.json", optional: false, reloadOnChange: true) + 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}serilogConfig.json", optional: false, reloadOnChange: true) .Build(); - - var logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .CreateLogger(); - + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); option.SetMinimumLevel(LogLevel.Information); option.AddSerilog(logger); }); diff --git a/Stormtrooper/Stormtrooper/appSetting.json b/Stormtrooper/Stormtrooper/serilogConfig.json similarity index 100% rename from Stormtrooper/Stormtrooper/appSetting.json rename to Stormtrooper/Stormtrooper/serilogConfig.json -- 2.25.1 From 8efbfd9691c4b38abc900cd59787ceee91ffa233 Mon Sep 17 00:00:00 2001 From: rakhaliullov Date: Thu, 2 May 2024 08:27:50 +0300 Subject: [PATCH 6/6] =?UTF-8?q?=D0=A1=D0=B2-=D0=B2=D0=BE=20=D0=BB=D0=BE?= =?UTF-8?q?=D0=B3=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Stormtrooper/Stormtrooper/Stormtrooper.csproj | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Stormtrooper/Stormtrooper/Stormtrooper.csproj b/Stormtrooper/Stormtrooper/Stormtrooper.csproj index ec6b790..42fac2c 100644 --- a/Stormtrooper/Stormtrooper/Stormtrooper.csproj +++ b/Stormtrooper/Stormtrooper/Stormtrooper.csproj @@ -33,4 +33,10 @@ + + + Always + + + \ No newline at end of file -- 2.25.1