From 438b1653bcfcfc12cc81b03915adb1c4f9582936 Mon Sep 17 00:00:00 2001 From: Glliza Date: Tue, 14 May 2024 01:23:22 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 21 ++- .../MassiveGenericObjects.cs | 62 ++++---- .../StorageCollection.cs | 134 ++++++++---------- .../Exceptions/CollectionOverflowException.cs | 24 ++++ .../Exceptions/ObjectNotFoundException.cs | 23 +++ .../PositionOutOfCollectionException.cs | 23 +++ .../ProjectAirbus/FormBusCollection.cs | 32 +++-- ProjectAirbus/ProjectAirbus/Program.cs | 23 ++- .../ProjectAirbus/ProjectAirbus.csproj | 11 ++ ProjectAirbus/ProjectAirbus/nlog.config | 14 ++ 10 files changed, 241 insertions(+), 126 deletions(-) create mode 100644 ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectAirbus/ProjectAirbus/nlog.config diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs index c6312af..23592c8 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectAirbus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -52,7 +53,7 @@ internal class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } @@ -61,12 +62,9 @@ internal class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора - if (_collection.Count > _maxCount) - { - return -1; - } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); - return _collection.Count; + return Count; } public int Insert(T obj, int position) @@ -75,11 +73,8 @@ internal class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции // TODO вставка по позиции - if (_collection.Count > _maxCount) - { - return -1; - } - if (position >= Count || position < 0) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); return position; } @@ -89,7 +84,7 @@ internal class ListGenericObjects : ICollectionGenericObjects // TODO проверка позиции // TODO удаление объекта из списка - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs index 44d82ad..2e2c84e 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectAirbus.Exceptions; + namespace ProjectAirbus.CollectionGenericObjects; @@ -50,7 +52,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= _collection.Length || position < 0) return null; + if (position < 0 || position >= MaxCount) + { + throw new PositionOutOfCollectionException(position); + } return _collection[position]; } @@ -58,17 +63,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects { // TODO вставка в свободное место набора - int index = 0; - while (index < _collection.Length) + for (int i = 0; i < MaxCount; ++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(Count); } public int Insert(T obj, int position) @@ -79,35 +82,32 @@ public class MassiveGenericObjects : ICollectionGenericObjects // если нет после, ищем до // TODO вставка - if (position >= _collection.Length || position < 0) - return -1; + if (position < 0 || position >= MaxCount) + { + throw new PositionOutOfCollectionException(Count); + } if (_collection[position] == null) { _collection[position] = obj; return position; } - int index = position + 1; - while (index < _collection.Length) + for (int i = position + 1; i < _collection.Length; ++i) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return position; } - ++index; } - index = position - 1; - while (index >= 0) + for (int i = 0; i < position; ++i) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return position; } - --index; } - return -1; - + throw new CollectionOverflowException(Count); } public T Remove(int position) @@ -115,11 +115,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null - if (position >= _collection.Length || position < 0) - return null; - T obj = _collection[position]; + if (position < 0 || position >= MaxCount) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); + } + T remove = _collection[position]; _collection[position] = null; - return obj; + return remove; } public IEnumerable GetItems() diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs index f973fe9..9857c27 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectAirbus.Drawning; +using ProjectAirbus.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -96,36 +97,35 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; - } + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + } if (File.Exists(filename)) { File.Delete(filename); } - StringBuilder sb = new(); - sb.Append(_collectionKey); - foreach (KeyValuePair> value in - _storages) + using StreamWriter wr = new StreamWriter(filename); + + wr.Write(_collectionKey); + + foreach (KeyValuePair> value in _storages) { - sb.Append(Environment.NewLine); - // не сохраняем пустые коллекции + wr.Write(Environment.NewLine); if (value.Value.Count == 0) { continue; } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); - + wr.Write(value.Key); + wr.Write(_separatorForKeyValue); + wr.Write(value.Value.GetCollectionType); + wr.Write(_separatorForKeyValue); + wr.Write(value.Value.MaxCount); + wr.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -133,14 +133,10 @@ public class StorageCollection { continue; } - sb.Append(data); - sb.Append(_separatorItems); + wr.Write(data); + wr.Write(_separatorItems); } } - using FileStream fs = new(filename, FileMode.Create); - byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - fs.Write(info, 0, info.Length); - return true; } /// @@ -148,74 +144,68 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузкеданных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } - string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader fs = File.OpenText(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string str = fs.ReadLine(); + if (str == null || str.Length == 0) { - bufferTextFromFile += temp.GetString(b); + throw new Exception("В файле нет данных"); } - } - string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, - StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].Equals(_collectionKey)) - { - //если нет такой записи, то это не те данные - return false; - } - _storages.Clear(); - foreach (string data in strs) - { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (!str.StartsWith(_collectionKey)) { - continue; + throw new Exception("В файле неверные данные"); } - CollectionType collectionType = - (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = - StorageCollection.CreateCollection(collectionType); - if (collection == null) + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) { - return false; - } - 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) + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) { - if (collection.Insert(bus) == -1) + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + throw new Exception("Не удалось определить тип коллекции:" + 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) { - return false; + try + { + if (collection.Insert(bus) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } + _storages.Add(record[0], collection); } - _storages.Add(record[0], collection); } - return true; } - /// - /// Создание коллекции по типу - /// - /// - /// - private static ICollectionGenericObjects? + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch diff --git a/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..5b06d64 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/CollectionOverflowException.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 ProjectAirbus.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/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..0c702b1 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirbus.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/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..decc98b --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAirbus.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/ProjectAirbus/ProjectAirbus/FormBusCollection.cs b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs index 6919cbf..b4b37fa 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusCollection.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs @@ -1,4 +1,5 @@ -using ProjectAirbus.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectAirbus.CollectionGenericObjects; using ProjectAirbus.Drawning; using System; using System.Collections.Generic; @@ -24,13 +25,19 @@ namespace ProjectAirbus /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBusCollection() + public FormBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -234,13 +241,16 @@ namespace ProjectAirbus { 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); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -249,16 +259,16 @@ namespace ProjectAirbus { 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); 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/ProjectAirbus/ProjectAirbus/Program.cs b/ProjectAirbus/ProjectAirbus/Program.cs index 34ef3f3..10a29f9 100644 --- a/ProjectAirbus/ProjectAirbus/Program.cs +++ b/ProjectAirbus/ProjectAirbus/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace ProjectAirbus { internal static class Program @@ -10,8 +15,22 @@ namespace ProjectAirbus { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ServiceCollection services = new(); + ConfigureServices(services); ApplicationConfiguration.Initialize(); - Application.Run(new FormBusCollection()); + + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + } } - } } \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj index 244387d..ea8f9a8 100644 --- a/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj +++ b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/nlog.config b/ProjectAirbus/ProjectAirbus/nlog.config new file mode 100644 index 0000000..2c84659 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file