From d4da4c02ae4123635b8e8be715fbdb120290502f Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Sun, 9 Jun 2024 18:43:48 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 2 +- .../ListGenericObjects.cs | 38 +++--- .../MassiveGenericObjects.cs | 74 +++++------ .../StorageCollection.cs | 35 +++-- .../Drawnings/ExtentionDrawningBus.cs | 79 ++++++----- .../Exceptions/CollectionOverflowException.cs | 22 ++++ .../Exceptions/ObjectNotFoundException.cs | 20 +++ .../PositionOutOfCollectionException.cs | 24 ++++ .../FormBusCollection.Designer.cs | 9 +- .../TrolleybusProject/FormBusCollection.cs | 124 ++++++++++++------ .../TrolleybusProject/Program.cs | 49 +++++-- .../TrolleybusProject.csproj | 23 ++++ .../TrolleybusProject/nlog.config | 15 +++ .../TrolleybusProject/serilogConfig.json | 20 +++ 14 files changed, 365 insertions(+), 169 deletions(-) create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/CollectionOverflowException.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/ObjectNotFoundException.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/PositionOutOfCollectionException.cs create mode 100644 TrolleybusProject/TrolleybusProject/nlog.config create mode 100644 TrolleybusProject/TrolleybusProject/serilogConfig.json diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs index 5105be1..dcfd16e 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs @@ -32,7 +32,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// -private int GetMaxCount => _pictureWidth * _pictureHeight /(_placeSizeWidth * _placeSizeHeight); +private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight); /// /// Конструктор /// diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs index e9c1a10..a72d856 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Exceptions; namespace TrolleybusProject.CollectionGenericObjects; @@ -40,42 +41,43 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position >= Count || position < 0) + if (position < 0 || position >= Count) { - return null; + throw new PositionOutOfCollectionException(position); } return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) + if (Count + 1 > _maxCount) { - return -1; + throw new CollectionOverflowException(Count); } - _collection.Add(obj); - return _collection.Count; + return 1; } public int Insert(T obj, int position) { - if (Count == _maxCount || position < 0 || position > Count) - { - return -1; - } - - _collection.Insert(position, obj); - return position; + if (position < 0 || position > Count) + { + throw new PositionOutOfCollectionException(position); + } + if (Count + 1 > _maxCount) + { + throw new CollectionOverflowException(Count); + } + _collection.Insert(position, obj); + return 1; } public T? Remove(int position) { - if (_collection == null || position < 0 || position >= _collection.Count) { - - return null; - + if (position < 0 || position > Count) + { + throw new PositionOutOfCollectionException(position); } T? obj = _collection[position]; - _collection[position] = null; + _collection.RemoveAt(position); return obj; } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs index a661f5f..b37471f 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Exceptions; namespace TrolleybusProject.CollectionGenericObjects; @@ -50,16 +51,34 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= _collection.Length || position < 0) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - int index = 0; + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + + throw new CollectionOverflowException(Count); + } + + public int Insert(T obj, int position) + { + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + int index = position + 1; while (index < _collection.Length) { if (_collection[index] == null) @@ -67,50 +86,25 @@ internal class MassiveGenericObjects : ICollectionGenericObjects _collection[index] = obj; return index; } - index++; + ++index; } - return -1; - } - - public int Insert(T obj, int position) - { - - if (position >= _collection.Length || position < 0) - return -1; - - - if (_collection[position] != null) + index = position - 1; + while (index >= 0) { - int nullIndex = -1; - for (int i = position + 1; i < Count; i++) + if (_collection[index] == null) { - if (_collection[i] == null) - { - nullIndex = i; - break; - } - } - if (nullIndex < 0) - { - return -1; - } - int j = nullIndex - 1; - while (j >= position) - { - _collection[j + 1] = _collection[j]; - j--; + _collection[index] = obj; + return index; } + --index; } - _collection[position] = obj; - return position; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position >= _collection.Length || position < 0) - { - return null; - } + 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/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs index 5586c45..27fb31c 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using TrolleybusProject.Drawnings; +using TrolleybusProject.Exceptions; namespace TrolleybusProject.CollectionGenericObjects; @@ -90,11 +91,12 @@ public class StorageCollection } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + } if (File.Exists(filename)) { @@ -130,25 +132,25 @@ public class StorageCollection } } } - return true; + } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует!"); } using (StreamReader reader = new(filename)) { string line = reader.ReadLine(); if (line == null || line.Length == 0) { - return false; + throw new ArgumentException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - return false; + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); while ((line = reader.ReadLine()) != null) @@ -163,25 +165,34 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T bus) + if (elem?.CreateDrawningBus() is T boat) { - if (collection.Insert(bus) <0) + try { - return false; + if (collection.Insert(boat) < 0) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + + } } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } + } } _storages.Add(record[0], collection); } } - return true; + } /// diff --git a/TrolleybusProject/TrolleybusProject/Drawnings/ExtentionDrawningBus.cs b/TrolleybusProject/TrolleybusProject/Drawnings/ExtentionDrawningBus.cs index 9d66f43..0841849 100644 --- a/TrolleybusProject/TrolleybusProject/Drawnings/ExtentionDrawningBus.cs +++ b/TrolleybusProject/TrolleybusProject/Drawnings/ExtentionDrawningBus.cs @@ -5,52 +5,49 @@ using System.Text; using System.Threading.Tasks; using TrolleybusProject.Entities; -namespace TrolleybusProject.Drawnings { +namespace TrolleybusProject.Drawnings; - public static class ExtentionDrawningBus +public static class ExtentionDrawningBus +{ + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningBus? CreateDrawningBus(this string info) { - /// - /// Разделитель для записи информации по объекту в файл - /// - private static readonly string _separatorForObject = ":"; - /// - /// Создание объекта из строки - /// - /// Строка с данными для создания объекта - /// Объект - public static DrawningBus? CreateDrawningBus(this string info) + string[] strs = info.Split(_separatorForObject); + EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs); + if (bus != null) { - string[] strs = info.Split(_separatorForObject); - EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs); - if (bus != null) - { - return new DrawningTrolleybus(bus); - } - bus = EntityBus.CreateEntityBus(strs); - if (bus != null) - { - return new DrawningBus(bus); - } - return null; - } - /// - /// Получение данных для сохранения в файл - /// - /// Сохраняемый объект - /// Строка с данными по объекту - public static string GetDataForSave(this DrawningBus drawningBus) - { - string[]? array = drawningBus?.EntityBus?.GetStringRepresentation(); - if (array == null) - { - return string.Empty; - } - return string.Join(_separatorForObject, array); + return new DrawningTrolleybus(bus); } + bus = EntityBus.CreateEntityBus(strs); + if (bus != null) + { + return new DrawningBus(bus); + } - - + return null; } -} + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningBus drawningBus) + { + string[]? array = drawningBus?.EntityBus?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/Exceptions/CollectionOverflowException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..6ba70ce --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/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 TrolleybusProject.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/TrolleybusProject/TrolleybusProject/Exceptions/ObjectNotFoundException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..6330ff2 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/ObjectNotFoundException.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 TrolleybusProject.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/TrolleybusProject/TrolleybusProject/Exceptions/PositionOutOfCollectionException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..d6ebdf9 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace TrolleybusProject.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/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs index 74448a6..aa68b52 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs @@ -127,7 +127,7 @@ buttonAddBus.Location = new Point(26, 18); buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Size = new Size(244, 34); - buttonAddBus.TabIndex = 1; + buttonAddBus.TabIndex = 2; buttonAddBus.Text = "Добавление автобуса"; buttonAddBus.UseVisualStyleBackColor = true; buttonAddBus.Click += buttonAddBus_Click; @@ -212,7 +212,7 @@ radioButtonMassive.Location = new Point(11, 65); radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Size = new Size(98, 29); - radioButtonMassive.TabIndex = 2; + radioButtonMassive.TabIndex = 1; radioButtonMassive.TabStop = true; radioButtonMassive.Text = "Массив"; radioButtonMassive.UseVisualStyleBackColor = true; @@ -263,7 +263,6 @@ menuStrip.Size = new Size(1204, 33); menuStrip.TabIndex = 2; menuStrip.Text = "Фаил"; - // // FileToolStripMenuItem // @@ -281,7 +280,7 @@ // save_ToolStripMenuItem.Name = "save_ToolStripMenuItem"; save_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; - save_ToolStripMenuItem.Size = new Size(270, 34); + save_ToolStripMenuItem.Size = new Size(261, 34); save_ToolStripMenuItem.Text = "Сохранить"; save_ToolStripMenuItem.Click += save_ToolStripMenuItem_Click; // @@ -289,7 +288,7 @@ // load_ToolStripMenuItem.Name = "load_ToolStripMenuItem"; load_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; - load_ToolStripMenuItem.Size = new Size(270, 34); + load_ToolStripMenuItem.Size = new Size(261, 34); load_ToolStripMenuItem.Text = "Загрузить"; load_ToolStripMenuItem.Click += load_ToolStripMenuItem_Click; // diff --git a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs index 8c60c4a..aae2f7e 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -9,6 +10,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using TrolleybusProject.CollectionGenericObjects; using TrolleybusProject.Drawnings; +using TrolleybusProject.Exceptions; namespace TrolleybusProject; @@ -23,12 +25,18 @@ public partial class FormBusCollection : Form /// private AbstractCompany? _company = null; - public FormBusCollection() + /// + /// Логер + /// + private readonly ILogger _logger; + public FormBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } + private void buttonAddBus_Click(object sender, EventArgs e) { BusConfig form = new(); @@ -37,18 +45,24 @@ public partial class FormBusCollection : Form } private void SetBus(DrawningBus bus) { - if (_company == null || bus == null) + try { - return; + if (_company == null || bus == null) + { + return; + } + if (_company + bus != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave()); + } + } - if (_company + bus != -1) + catch (CollectionOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogError($"Ошибка: {ex.Message}"); } } @@ -67,20 +81,30 @@ public partial class FormBusCollection : Form { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { 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 + { + MessageBox.Show($"Не удалось удалить объект"); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -90,13 +114,23 @@ public partial class FormBusCollection : Form { return; } + DrawningBus? bus = null; int counter = 100; while (bus == null) { - bus = _company.GetRandomObject(); - counter--; - + try + { + bus = _company.GetRandomObject(); + } + catch (ObjectNotFoundException) + { + counter--; + if (counter <= 0) + { + break; + } + } } if (bus == null) { @@ -122,10 +156,11 @@ public partial class FormBusCollection : Form private void buttonCollectionAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || -(!radioButtonList.Checked && !radioButtonMassive.Checked)) + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не заполненная коллекция"); return; } CollectionType collectionType = CollectionType.None; @@ -137,10 +172,9 @@ public partial class FormBusCollection : Form { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, - collectionType); + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}"); RerfreshListBoxItems(); - } /// /// Обновление списка в listBoxCollection @@ -159,19 +193,19 @@ public partial class FormBusCollection : Form } private void buttonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedItem == null) return; - if (listBoxCollection.SelectedIndex < 0) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Удаление невыбранной коллекции"); return; } - - + string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция: {name}"); RerfreshListBoxItems(); } @@ -181,6 +215,7 @@ public partial class FormBusCollection : Form if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Создание компании невыбранной коллекции"); return; } ICollectionGenericObjects? collection = @@ -188,6 +223,7 @@ public partial class FormBusCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogWarning("Не удалось инициализировать коллекцию"); return; } switch (comboBoxSelectionCompany.Text) @@ -205,37 +241,47 @@ public partial class FormBusCollection : 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); } } - } + + + private void load_ToolStripMenuItem_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); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось загрузить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - } + + + } diff --git a/TrolleybusProject/TrolleybusProject/Program.cs b/TrolleybusProject/TrolleybusProject/Program.cs index 1b9f49a..fe2f22a 100644 --- a/TrolleybusProject/TrolleybusProject/Program.cs +++ b/TrolleybusProject/TrolleybusProject/Program.cs @@ -1,17 +1,40 @@ -namespace TrolleybusProject +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + +namespace TrolleybusProject; + +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(); - Application.Run(new FormBusCollection()); - } + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services + .AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + var config = new ConfigurationBuilder() + .AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + option.AddSerilog(Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(config) + .CreateLogger()); + }); } } \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/TrolleybusProject.csproj b/TrolleybusProject/TrolleybusProject/TrolleybusProject.csproj index 244387d..b35dd3a 100644 --- a/TrolleybusProject/TrolleybusProject/TrolleybusProject.csproj +++ b/TrolleybusProject/TrolleybusProject/TrolleybusProject.csproj @@ -8,6 +8,20 @@ enable + + + + + + + + + + + + + + True @@ -23,4 +37,13 @@ + + + Always + + + Always + + + \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/nlog.config b/TrolleybusProject/TrolleybusProject/nlog.config new file mode 100644 index 0000000..5c71e85 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/serilogConfig.json b/TrolleybusProject/TrolleybusProject/serilogConfig.json new file mode 100644 index 0000000..e1e66a6 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/serilogConfig.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": "Trolleybus" + } + } +} \ No newline at end of file -- 2.25.1 From 51836226ac7de257b413c2b285d10c4fd5ee4fa6 Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Mon, 10 Jun 2024 00:16:01 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CollectionGenericObjects/StorageCollection.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs index 27fb31c..25bb826 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs @@ -172,11 +172,11 @@ public class StorageCollection StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T boat) + if (elem?.CreateDrawningBus() is T bus ) { try { - if (collection.Insert(boat) < 0) + if (collection.Insert(bus) < 0) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); -- 2.25.1 From 2d339f7d204e8044f4d416dd25f3d90aca71385c Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Mon, 10 Jun 2024 03:49:04 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=B2=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 3 +- .../DrawningBusCompareByType.cs | 36 +++++++ .../ICollectionGenericObjects.cs | 11 ++- .../ListGenericObjects.cs | 57 ++++++++--- .../MassiveGenericObjects.cs | 49 +++++++++- .../StorageCollection.cs | 95 +++++++++++-------- .../TrolleybusProject/CollectionInfo.cs | 76 +++++++++++++++ .../Drawnings/DrawiningBusEqutables.cs | 70 ++++++++++++++ .../Drawnings/DrawningBusCompareByColor.cs | 35 +++++++ .../CollectionAlreadyExistsException.cs | 14 +++ .../Exceptions/CollectionInsertException.cs | 18 ++++ .../FormBusCollection.Designer.cs | 36 ++++++- .../TrolleybusProject/FormBusCollection.cs | 57 ++++++++--- 13 files changed, 472 insertions(+), 85 deletions(-) create mode 100644 TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs create mode 100644 TrolleybusProject/TrolleybusProject/CollectionInfo.cs create mode 100644 TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs create mode 100644 TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs create mode 100644 TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs index dcfd16e..0cb18ca 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/AbstractCompany.cs @@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _ /// public static int operator +(AbstractCompany company, DrawningBus bus) { - return company._collection.Insert(bus); + return company._collection.Insert(bus,new DrawiningBusEqutables()); } /// /// Перегрузка оператора удаления для класса @@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _ /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs new file mode 100644 index 0000000..963c790 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/DrawningBusCompareByType.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.Drawnings; + +namespace TrolleybusProject.CollectionGenericObjects; + +public class DrawningBusCompareByType : IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null && y == null) return 0; + + if (x == null || x.EntityBus == null) + { + return -1; + } + if (y == null || y.EntityBus == null) + { + return 1; + } + if (x.GetType().Name != y.GetType().Name) + { + return x.GetType().Name.CompareTo(y.GetType().Name); + } + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs index 166273f..99c9e4a 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -21,20 +21,20 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// true - вставка прошла удачно, false - вставка не удалась - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление объекта в коллекцию на конкретную позицию /// /// Добавляемый объект /// Позиция /// true - вставка прошла удачно, false - вставка не удалась -int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление объекта из коллекции с конкретной позиции /// /// Позиция /// true - удаление прошло удачно, false - удаление не удалось - T? Remove(int position); + T? Remove(int position); /// /// Получение объекта по позиции /// @@ -51,4 +51,9 @@ int Insert(T obj, int position); /// /// Поэлементый вывод элементов коллекции IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs index a72d856..b9a1bba 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/ListGenericObjects.cs @@ -1,8 +1,10 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Drawnings; using TrolleybusProject.Exceptions; namespace TrolleybusProject.CollectionGenericObjects; @@ -48,27 +50,48 @@ public class ListGenericObjects : ICollectionGenericObjects return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (Count + 1 > _maxCount) + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + + _collection.Add(obj); + return Count; + } + + public int Insert(T obj, int position, IEqualityComparer? comparer = null) + { + if (Count == _maxCount) { throw new CollectionOverflowException(Count); } - _collection.Add(obj); - return 1; - } - public int Insert(T obj, int position) - { - if (position < 0 || position > Count) + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } + + if (comparer != null) + { + for (int i = 0; i < Count; i++) { - throw new PositionOutOfCollectionException(position); + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } } - if (Count + 1 > _maxCount) - { - throw new CollectionOverflowException(Count); - } - _collection.Insert(position, obj); - return 1; + } + + _collection.Insert(position, obj); + return position; } public T? Remove(int position) { @@ -89,6 +112,10 @@ public class ListGenericObjects : ICollectionGenericObjects } } + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs index b37471f..f2ab9f9 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TrolleybusProject.Drawnings; using TrolleybusProject.Exceptions; + namespace TrolleybusProject.CollectionGenericObjects; internal class MassiveGenericObjects : ICollectionGenericObjects @@ -51,13 +53,26 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + return _collection[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -66,12 +81,27 @@ internal class MassiveGenericObjects : ICollectionGenericObjects return i; } } - throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + + if (comparer != null) + { + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(_collection[i], obj)) + { + throw new CollectionInsertException(obj); + } + } + } + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -117,4 +147,13 @@ internal class MassiveGenericObjects : ICollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + List value = new List(_collection); + value.Sort(comparer); + value.CopyTo(_collection, 0); + } + + } diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs index 27fb31c..cc1a24b 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using System; +using ProjectTrolleybus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -15,12 +16,12 @@ public class StorageCollection /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> _storages; + readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// - public List Keys => _storages.Keys.ToList(); + public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл @@ -42,7 +43,7 @@ public class StorageCollection /// public StorageCollection() { - _storages = new Dictionary>(); + _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -51,29 +52,36 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (_storages.ContainsKey(name) && name == "") - { + CollectionInfo collectionInfo = new(name, collectionType, string.Empty); + if (name == null || _storages.ContainsKey(collectionInfo)) return; + switch (collectionType) + { + case CollectionType.None: + return; + case CollectionType.Massive: + _storages[collectionInfo] = new MassiveGenericObjects(); + return; + case CollectionType.List: + _storages[collectionInfo] = new ListGenericObjects(); + return; + default: + break; } - if (collectionType == CollectionType.Massive) - { - _storages[name] = new MassiveGenericObjects(); - } - else - { - _storages[name] = new ListGenericObjects(); - } } - /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { - _storages.Remove(name); -} + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) + { + _storages.Remove(collectionInfo); + } + } /// /// Доступ к коллекции /// @@ -83,11 +91,12 @@ public class StorageCollection { get { - if (name == "") + CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); + if (_storages.ContainsKey(collectionInfo)) { - return null; + return _storages[collectionInfo]; } - return _storages[name]; + return null; } } @@ -102,10 +111,13 @@ public class StorageCollection { File.Delete(filename); } + using (StreamWriter writer = new(filename)) + + { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> value in _storages) { writer.Write(Environment.NewLine); // не сохраняем пустые коллекции @@ -141,42 +153,42 @@ public class StorageCollection { throw new FileNotFoundException("Файл не существует!"); } - using (StreamReader reader = new(filename)) + + using (StreamReader sr = new(filename)) { - string line = reader.ReadLine(); + string? line = sr.ReadLine(); + if (line == null || line.Length == 0) { throw new ArgumentException("В файле нет данных"); } - if (!line.Equals(_collectionKey)) + + if (line != _collectionKey) { - throw new InvalidDataException("В файле неверные данные"); + throw new InvalidDataException("В файле неверные данные"); } + _storages.Clear(); - while ((line = reader.ReadLine()) != null) + + while ((line = sr.ReadLine()) != null) { - string[] record = line.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - if (collection == null) - { - throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, - StringSplitOptions.RemoveEmptyEntries); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Не удалось определить тип коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Не удалось создать коллекцию"); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBus() is T boat) + if (elem?.CreateDrawningBus() is T bus) { try { - if (collection.Insert(boat) < 0) + if (collection.Insert(bus) < 0) { throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); @@ -189,10 +201,9 @@ public class StorageCollection } } - _storages.Add(record[0], collection); + _storages.Add(collectionInfo, collection); } } - } /// diff --git a/TrolleybusProject/TrolleybusProject/CollectionInfo.cs b/TrolleybusProject/TrolleybusProject/CollectionInfo.cs new file mode 100644 index 0000000..ece6558 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/CollectionInfo.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.CollectionGenericObjects; + +namespace TrolleybusProject; +/// +/// Класс, хранящиий информацию по коллекции +/// +public class CollectionInfo : IEquatable +{ + /// + /// Название + /// + public string Name { get; private set; } + /// + /// Тип + /// + public CollectionType CollectionType { get; private set; } + /// + /// Описание + /// + public string Description { get; private set; } + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separator = "-"; + /// + /// Конструктор + /// + /// Название + /// Тип + /// Описание + public CollectionInfo(string name, CollectionType collectionType, string + description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + /// + /// Создание объекта из строки + /// + /// Строка + /// Объект или null + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, + StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) + { + return null; + } + return new CollectionInfo(strs[0], + (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? + strs[2] : string.Empty); + } + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + public override int GetHashCode() + { + return Name.GetHashCode(); + } +} diff --git a/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs b/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs new file mode 100644 index 0000000..ff0c4cc --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Drawnings/DrawiningBusEqutables.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TrolleybusProject.Entities; + +namespace TrolleybusProject.Drawnings; + +internal class DrawiningBusEqutables: IEqualityComparer +{ + public bool Equals(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return false; + } + if (y == null || y.EntityBus == null) + { + return false; + } + if (x.GetType().Name != y.GetType().Name) + { + return false; + } + if (x.EntityBus.Speed != y.EntityBus.Speed) + { + return false; + } + if (x.EntityBus.Weight != y.EntityBus.Weight) + { + return false; + } + if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) + { + return false; + } + if (x is DrawningTrolleybus && y is DrawningTrolleybus) + { + if (((EntityTrolleybus)x.EntityBus).AdditionalColor != + ((EntityTrolleybus)y.EntityBus).AdditionalColor) + { + return false; + } + if (((EntityTrolleybus)x.EntityBus).Roga != + ((EntityTrolleybus)y.EntityBus).Roga) + { + return false; + } + if (((EntityTrolleybus)x.EntityBus).Otsek != + ((EntityTrolleybus)y.EntityBus).Otsek) + { + return false; + } + + if (((EntityTrolleybus)x.EntityBus).Doors != + ((EntityTrolleybus)y.EntityBus).Doors) + { + return false; + } + } + return true; + } + public int GetHashCode([DisallowNull] DrawningBus obj) + { + return obj.GetHashCode(); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs new file mode 100644 index 0000000..81716a7 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TrolleybusProject.Drawnings; + +public class DrawningBusCompareByColor: IComparer +{ + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) + { + return 1; + } + + if (y == null || y.EntityBus == null) + { + return -1; + } + var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name); + if (bodycolorCompare != 0) + { + return bodycolorCompare; + } + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) + { + return speedCompare; + } + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + +} diff --git a/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..7e8b4a0 --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; +using TrolleybusProject; + +namespace ProjectTrolleybus.Exceptions; +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) + { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..d97edcb --- /dev/null +++ b/TrolleybusProject/TrolleybusProject/Exceptions/CollectionInsertException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { } + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInsertException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs index aa68b52..bd66250 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.Designer.cs @@ -55,6 +55,8 @@ LoadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonByType = new Button(); + ByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -71,7 +73,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(904, 33); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(300, 623); + groupBoxTools.Size = new Size(300, 702); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -88,7 +90,9 @@ // // panelCompanyTools // + panelCompanyTools.Controls.Add(buttonByType); panelCompanyTools.Controls.Add(buttonRefresh); + panelCompanyTools.Controls.Add(ByColor); panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonDelTrolleybus); @@ -96,7 +100,7 @@ panelCompanyTools.Enabled = false; panelCompanyTools.Location = new Point(0, 397); panelCompanyTools.Name = "panelCompanyTools"; - panelCompanyTools.Size = new Size(294, 259); + panelCompanyTools.Size = new Size(294, 305); panelCompanyTools.TabIndex = 9; // // buttonRefresh @@ -250,7 +254,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 33); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(904, 623); + pictureBox.Size = new Size(904, 702); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -314,11 +318,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonByType + // + buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonByType.Location = new Point(6, 259); + buttonByType.Name = "buttonByType"; + buttonByType.Size = new Size(268, 34); + buttonByType.TabIndex = 8; + buttonByType.Text = "Сравнить по типу"; + buttonByType.UseVisualStyleBackColor = true; + buttonByType.Click += button1_Click; + // + // ByColor + // + ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + ByColor.Location = new Point(23, 215); + ByColor.Name = "ByColor"; + ByColor.Size = new Size(247, 38); + ByColor.TabIndex = 7; + ByColor.Text = "Сравнить по цвету"; + ByColor.UseVisualStyleBackColor = true; + ByColor.Click += ByColor_Click; + // // FormBusCollection // AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1204, 656); + ClientSize = new Size(1204, 735); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -366,5 +392,7 @@ private ToolStripMenuItem файлToolStripMenuItem; private ToolStripMenuItem save_ToolStripMenuItem; private ToolStripMenuItem load_ToolStripMenuItem; + private Button buttonByType; + private Button ByColor; } } \ No newline at end of file diff --git a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs index aae2f7e..218ce27 100644 --- a/TrolleybusProject/TrolleybusProject/FormBusCollection.cs +++ b/TrolleybusProject/TrolleybusProject/FormBusCollection.cs @@ -45,24 +45,26 @@ public partial class FormBusCollection : Form } private void SetBus(DrawningBus bus) { + if (_company == null || bus == null) + { + return; + } try { - if (_company == null || bus == null) - { - return; - } - if (_company + bus != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave()); - } - + int addingObject = (_company + bus); + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}"); + pictureBox.Image = _company.Show(); } catch (CollectionOverflowException ex) { - MessageBox.Show(ex.Message); - _logger.LogError($"Ошибка: {ex.Message}"); + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); + } + catch (CollectionInsertException) + { + MessageBox.Show("Такой объект уже существует"); + _logger.LogError("Ошибка:обьект повторяется {0}", bus); } } @@ -156,7 +158,7 @@ public partial class FormBusCollection : Form private void buttonCollectionAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || - (!radioButtonList.Checked && !radioButtonMassive.Checked)) + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -184,7 +186,7 @@ public partial class FormBusCollection : Form listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -281,6 +283,31 @@ public partial class FormBusCollection : Form } + private void button1_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByType()); + } + + private void ByColor_Click(object sender, EventArgs e) + { + CompareBus(new DrawningBusCompareByColor()); + } + + /// + /// Сортировка по сравнителю + /// + /// Сравнитель объектов + private void CompareBus(IComparer comparer) + { + if (_company == null) + { + return; + } + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } + + } -- 2.25.1 From 38b39ba55d1b24bba55753e699236d396ffab3d7 Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Mon, 10 Jun 2024 04:53:32 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BC=D0=B0=D1=81=D1=81=D0=B8=D0=B2?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MassiveGenericObjects.cs | 70 ++++++++----------- .../StorageCollection.cs | 3 +- .../Drawnings/DrawningBusCompareByColor.cs | 10 ++- 3 files changed, 37 insertions(+), 46 deletions(-) diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs index f2ab9f9..d58ec9d 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/MassiveGenericObjects.cs @@ -63,15 +63,10 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public int Insert(T obj, IEqualityComparer? comparer = null) { - if (comparer != null) + int index = Array.IndexOf(_collection, null); + if (_collection.Contains(obj, comparer)) { - for (int i = 0; i < Count; i++) - { - if (comparer.Equals(_collection[i], obj)) - { - throw new CollectionInsertException(obj); - } - } + throw new CollectionInsertException(obj); } for (int i = 0; i < Count; i++) { @@ -84,53 +79,45 @@ internal class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0 || position >= Count) + if (_collection.Contains(obj, comparer)) { + throw new CollectionInsertException(obj); + } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); - } - if (comparer != null) - { - for (int i = 0; i < Count; i++) - { - if (comparer.Equals(_collection[i], obj)) - { - throw new CollectionInsertException(obj); - } - } - } - - if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; return position; } - int index = position + 1; - while (index < _collection.Length) + + int temp = position + 1; + while (temp < Count) { - if (_collection[index] == null) + if (_collection[temp] == null) { - _collection[index] = obj; - return index; + _collection[temp] = obj; + return temp; } - ++index; + temp++; } - index = position - 1; - while (index >= 0) + + temp = position - 1; + while (temp > 0) { - if (_collection[index] == null) + if (_collection[temp] == null) { - _collection[index] = obj; - return index; + _collection[temp] = obj; + return temp; } - --index; + temp--; } + throw new CollectionOverflowException(Count); } - public T? Remove(int position) { if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); @@ -150,10 +137,11 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public void CollectionSort(IComparer comparer) { - List value = new List(_collection); - value.Sort(comparer); - value.CopyTo(_collection, 0); + if (_collection?.Length > 0) + { + Array.Sort(_collection, comparer); + Array.Reverse(_collection); + } } - - } + diff --git a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs index cc1a24b..5fbb369 100644 --- a/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs +++ b/TrolleybusProject/TrolleybusProject/CollectionGenericObjects/StorageCollection.cs @@ -211,8 +211,7 @@ public class StorageCollection /// /// /// - private static ICollectionGenericObjects? - CreateCollection(CollectionType collectionType) + private static ICollectionGenericObjects?CreateCollection(CollectionType collectionType) { return collectionType switch { diff --git a/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs index 81716a7..287782e 100644 --- a/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs +++ b/TrolleybusProject/TrolleybusProject/Drawnings/DrawningBusCompareByColor.cs @@ -10,14 +10,18 @@ public class DrawningBusCompareByColor: IComparer { public int Compare(DrawningBus? x, DrawningBus? y) { - if (x == null || x.EntityBus == null) + if (x == null && y == null) { - return 1; + return 0; + } + if (x == null || x.EntityBus== null) + { + return -1; } if (y == null || y.EntityBus == null) { - return -1; + return 1; } var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name); if (bodycolorCompare != 0) -- 2.25.1 From 7c4680b0f1fc008760edf3eb97122f1da4e0826d Mon Sep 17 00:00:00 2001 From: Anastasia Yazykova Date: Mon, 10 Jun 2024 11:42:46 +0400 Subject: [PATCH 5/5] =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B1=D0=B5=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TrolleybusProject/MovementStrategy/ObjectParameters.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/TrolleybusProject/TrolleybusProject/MovementStrategy/ObjectParameters.cs b/TrolleybusProject/TrolleybusProject/MovementStrategy/ObjectParameters.cs index ee1b6f9..07c7c30 100644 --- a/TrolleybusProject/TrolleybusProject/MovementStrategy/ObjectParameters.cs +++ b/TrolleybusProject/TrolleybusProject/MovementStrategy/ObjectParameters.cs @@ -63,6 +63,5 @@ namespace TrolleybusProject.MovementStrategy _height = height; } - } } -- 2.25.1