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