From 80990715907a6240c6ec768c0731ee2e124190b5 Mon Sep 17 00:00:00 2001 From: repka228 <54245562+repka228@users.noreply.github.com> Date: Tue, 7 May 2024 23:01:58 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BA=D0=BE=D0=BD=D0=B5=D1=86=207=20=D0=BB?= =?UTF-8?q?=D0=B0=D0=B1=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AccordionBus/AccordionBus/AccordionBus.csproj | 11 ++ .../ListGenericObjects.cs | 30 ++-- .../MassiveGenericObjects.cs | 65 ++++---- .../StorageCollection.cs | 155 +++++++++--------- .../Exceptions/CollectionOverflowException.cs | 22 +++ .../Exceptions/ObjectNotFoundException.cs | 19 +++ .../PositionOutOfCollectionException.cs | 18 ++ .../FormBusCollection.Designer.cs | 8 +- .../AccordionBus/FormBusCollection.cs | 36 ++-- .../AccordionBus/FormBusCollection.resx | 2 +- AccordionBus/AccordionBus/Program.cs | 26 ++- AccordionBus/AccordionBus/nlog.config | 14 ++ 12 files changed, 260 insertions(+), 146 deletions(-) create mode 100644 AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs create mode 100644 AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs create mode 100644 AccordionBus/AccordionBus/Exceptions/PositionOutOfCollectionException.cs create mode 100644 AccordionBus/AccordionBus/nlog.config diff --git a/AccordionBus/AccordionBus/AccordionBus.csproj b/AccordionBus/AccordionBus/AccordionBus.csproj index 676957c..081b21b 100644 --- a/AccordionBus/AccordionBus/AccordionBus.csproj +++ b/AccordionBus/AccordionBus/AccordionBus.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs index 1f8eae4..b807616 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectAccordionBus.CollectionGenericObjects; +using AccordionBus.Exceptions; +using ProjectAccordionBus.CollectionGenericObjects; using System; using System.Collections.Generic; using System.Linq; @@ -35,40 +36,33 @@ public class ListGenericObjects:ICollectionGenericObjects where T : class public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - else - { - return null; - } - + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) { return -1; } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (position < 0 || position >= Count || Count == _maxCount) - { - return -1; - } + if (position < 0 || position >= Count) + throw new PositionOutOfCollectionException(position); + + if (Count == _maxCount) + throw new CollectionOverflowException(Count); _collection.Insert(position, obj); return position; - } public T? Remove(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T? obj = _collection[position]; - _collection?.RemoveAt(position); + _collection.RemoveAt(position); return obj; } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index 076a5f1..5a65137 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using ProjectAccordionBus.CollectionGenericObjects; +using AccordionBus.Exceptions; +using ProjectAccordionBus.CollectionGenericObjects; using System; using System.Collections.Generic; using System.Linq; @@ -48,59 +49,63 @@ where T : class } public T? Get(int position) // получение с позиции { - if (position < 0 || position >= _collection.Length) // если позиция передано неправильно - return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) // вставка объекта на свободное место { - for(int i=0; i < _collection.Length; ++i) + for (int i = 0; i < Count; i++) { - if (_collection[i]==null) + if (_collection[i] == null) { _collection[i] = obj; return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) // вставка объекта на место { - if (position < 0 || position >= _collection.Length) // если позиция переданна неправильно - return -1; - if (_collection[position] == null)//если позиция пуста + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) { _collection[position] = obj; return position; } - else + + for (int i = position + 1; i < Count; i++) { - for(int i=position; i< _collection.Length; ++i) //ищем свободное место справа + if (_collection[i] == null) { - if(_collection[i]==null) - { - _collection[i] = obj; - return i; - } - } - for (int i = 0; i < position; ++i) // иначе слева - { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[i] = obj; + return i; } } - return -1; + for (int i = position - 1; i >= 0; i--) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + + throw new CollectionOverflowException(Count); } public T? Remove(int position) // удаление объекта, зануляя его { - if (position < 0 || position >= _collection.Length || _collection[position] == null) - return null; - T ?temp = _collection[position]; - _collection[position]=null; - return temp; + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) throw new ObjectNotFoundException(position); + T? obj = _collection[position]; + _collection[position] = null; + return obj; } public IEnumerable GetItems() diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs index 8bb393d..d02d5d9 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using AccordionBus.Drawnings; +using AccordionBus.Exceptions; using ProjectAccordionBus.CollectionGenericObjects; using System.Text; @@ -97,32 +98,33 @@ public class StorageCollection where T : DrawningBus /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) - return false; - - if (File.Exists(filename)) - File.Delete(filename); - - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter sw = new StreamWriter(fs); - sw.Write(_collectionKey); - foreach (KeyValuePair> value in _storages) { - sw.Write(Environment.NewLine); + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); + } + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder sb = new(); + sb.Append(_collectionKey); + foreach (KeyValuePair> value in + _storages) + { + sb.Append(Environment.NewLine); + // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } - - sw.Write(value.Key); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.MaxCount); - sw.Write(_separatorForKeyValue); - + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -130,79 +132,72 @@ public class StorageCollection where T : DrawningBus { continue; } - - sw.Write(data); - sw.Write(_separatorItems); + sb.Append(data); + sb.Append(_separatorItems); } } - return true; + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); } + /// /// Загрузка информации по самолетам в хранилище из файла /// /// Путь и имя файла /// 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 sr = new StreamReader(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + string? str; + str = sr.ReadLine(); + if (str == null || str.Length == 0) + throw new Exception("В файле нет данных"); + if (str != _collectionKey.ToString()) + throw new Exception("В файле неверные данные"); + _storages.Clear(); + while ((str = sr.ReadLine()) != null) { - bufferTextFromFile += temp.GetString(b); - } - } - 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) - { - continue; - } - CollectionType collectionType = - (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = - StorageCollection.CreateCollection(collectionType); - if (collection == 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 = str.Split(_separatorForKeyValue); + 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("Не удалось создать коллекцию"); + } + + 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; } /// /// Создание коллекции по типу @@ -210,14 +205,14 @@ public class StorageCollection where T : DrawningBus /// /// private static ICollectionGenericObjects? - CreateCollection(CollectionType collectionType) - { - return collectionType switch + CreateCollection(CollectionType collectionType) { - CollectionType.Massive => new MassiveGenericObjects(), - CollectionType.List => new ListGenericObjects(), - _ => null, - }; - } - + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } + diff --git a/AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs b/AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..6ec14b8 --- /dev/null +++ b/AccordionBus/AccordionBus/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 AccordionBus.Exceptions; + +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/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs b/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..a568e9e --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Exceptions; + +public 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/AccordionBus/AccordionBus/Exceptions/PositionOutOfCollectionException.cs b/AccordionBus/AccordionBus/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..9f8052a --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/PositionOutOfCollectionException.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; + +namespace AccordionBus.Exceptions; + +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/AccordionBus/AccordionBus/FormBusCollection.Designer.cs b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs index e794351..2815d9a 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.Designer.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs @@ -52,7 +52,7 @@ saveToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); - openFileDialog = new OpenFileDialog(); + loadFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); @@ -287,9 +287,9 @@ // saveFileDialog.Filter = "txt file|*.txt"; // - // openFileDialog + // loadFileDialog // - openFileDialog.FileName = "openFileDialog1"; + loadFileDialog.FileName = "openFileDialog1"; // // FormBusCollection // @@ -340,6 +340,6 @@ private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; - private OpenFileDialog openFileDialog; + private OpenFileDialog loadFileDialog; } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/FormBusCollection.cs b/AccordionBus/AccordionBus/FormBusCollection.cs index 302c4e7..cc33d05 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.cs @@ -1,6 +1,7 @@ using AccordionBus.CollectionGenericObjects; using AccordionBus.Drawnings; using AccordionBus.MovementStrategy; +using Microsoft.Extensions.Logging; using ProjectAccordionBus.CollectionGenericObjects; using System; using System.Collections.Generic; @@ -22,12 +23,17 @@ public partial class FormBusCollection : Form /// private AbstractCompany? _company = null; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormBusCollection() + public FormBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } private void SetBus(DrawningBus bus) @@ -209,16 +215,20 @@ public partial class FormBusCollection : Form private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { - if (openFileDialog.ShowDialog() == DialogResult.OK) + if (loadFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.SaveData(loadFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RefreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", + loadFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -227,14 +237,20 @@ public partial class FormBusCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); } } } } +} diff --git a/AccordionBus/AccordionBus/FormBusCollection.resx b/AccordionBus/AccordionBus/FormBusCollection.resx index 0bbe40d..207d4b6 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.resx +++ b/AccordionBus/AccordionBus/FormBusCollection.resx @@ -126,7 +126,7 @@ 247, 17 - + 376, 17 \ No newline at end of file diff --git a/AccordionBus/AccordionBus/Program.cs b/AccordionBus/AccordionBus/Program.cs index 0f1784d..b70e80b 100644 --- a/AccordionBus/AccordionBus/Program.cs +++ b/AccordionBus/AccordionBus/Program.cs @@ -1,8 +1,11 @@ using AccordionBus; -using System.Drawing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; namespace ProjectAccordionBus; + internal static class Program { /// @@ -11,9 +14,26 @@ internal static class Program [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, + // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBusCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = + services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + /// + /// DI + /// + /// + 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/AccordionBus/AccordionBus/nlog.config b/AccordionBus/AccordionBus/nlog.config new file mode 100644 index 0000000..63b7d65 --- /dev/null +++ b/AccordionBus/AccordionBus/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file