From ba8685e9dcee82060f81318f13b34d4c02dac031 Mon Sep 17 00:00:00 2001 From: gettterot Date: Sat, 20 Apr 2024 07:48:17 +0400 Subject: [PATCH] =?UTF-8?q?7=20=D0=BB=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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 32 +++++++++------- .../MassiveGenericObjects.cs | 25 ++++++------ .../StorageCollection.cs | 38 +++++++++++-------- .../Exceptions/CollectionOverflowException.cs | 20 ++++++++++ .../Exceptions/ObjectNotFoundException.cs | 21 ++++++++++ .../PositionOutOfCollectionException.cs | 21 ++++++++++ .../ProjectLiner/FormLinerCollection.cs | 28 ++++++++++---- ProjectLiner/ProjectLiner/Program.cs | 27 ++++++++++++- ProjectLiner/ProjectLiner/ProjectLiner.csproj | 11 ++++++ ProjectLiner/ProjectLiner/serilog.config | 13 +++++++ 10 files changed, 185 insertions(+), 51 deletions(-) create mode 100644 ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectLiner/ProjectLiner/serilog.config diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index 0e75629..c70f706 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; +using System.Collections.Generic; /// /// Параметризованный набор объектов @@ -10,12 +12,12 @@ public class ListGenericObjects : ICollectionGenericObjects /// /// Список объектов, которые храним /// - private readonly Dictionary _collection; + private readonly List _collection; /// /// Максимально допустимое число объектов в списке /// private int _maxCount; - public int Count => _collection.Keys.Count; + public int Count => _collection.Count; public int MaxCount { get @@ -43,27 +45,31 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } public int Insert(T obj) { - if (Count > _maxCount) return -1; - _collection[Count-1] = obj; + if (Count == _maxCount) throw new CollectionOverflowException(); + _collection.Add(obj); return Count; } + public int Insert(T obj, int position) { - if (Count > _maxCount) return -1; - _collection[position] = obj; - return 1; + if (Count == _maxCount) throw new CollectionOverflowException(); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + _collection.Insert(position, obj); + return position; } - public T? Remove(int position) + + public T Remove(int position) { - if (_collection.ContainsKey(position)) return null; - T? temp = _collection[position]; - _collection.Remove(position); - return temp; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; } public IEnumerable GetItems() diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index 8c51a0a..cd419af 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@  +using ProjectLiner.Exceptions; + namespace ProjectLiner.CollectionGenericObjects { /// @@ -50,8 +52,7 @@ namespace ProjectLiner.CollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) - return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); return _collection[position]; } @@ -65,12 +66,13 @@ namespace ProjectLiner.CollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(); } public int Insert(T obj, int position) { - if (position >= Count || position < 0) return -1; + + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); if (_collection[position] == null) { _collection[position] = obj; @@ -96,21 +98,16 @@ namespace ProjectLiner.CollectionGenericObjects } --temp; } - return -1; + throw new CollectionOverflowException(); } public T? Remove(int position) { - if (position < 0 || position >= Count) - { - return null; - } - - //if (_collection[position] == null) return null; - - T? temp = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + T? myObject = _collection[position]; + if (myObject == null) throw new ObjectNotFoundException(); _collection[position] = null; - return temp; + return myObject; } public IEnumerable GetItems() diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs index 08bacf4..abe8305 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; /// /// Класс-хранилище коллекций @@ -90,10 +91,10 @@ 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); @@ -128,7 +129,6 @@ public class StorageCollection sw.Write(_separatorItems); } } - return true; } /// @@ -136,26 +136,24 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"{filename} не существует"); } using (FileStream fs = new(filename, FileMode.Open)) { using StreamReader sr = new StreamReader(fs); - - string str = sr.ReadLine(); - if (str == null || str.Length == 0) + string line = sr.ReadLine(); + if (line == null || line.Length == 0) { - return false; + throw new Exception("Файл не подходит"); } - - if (!str.Equals(_collectionKey)) + if (!line.Equals(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); @@ -171,7 +169,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -181,14 +179,22 @@ public class StorageCollection { if (elem?.CreateDrawningCommonLiner() is T commonLiner) { - if (collection.Insert(commonLiner) == -1) - return false; + try + { + if (collection.Insert(commonLiner) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: "); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - return true; } /// diff --git a/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..bab1071 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.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 ProjectLiner.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) { } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs b/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..6462346 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLiner.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/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..83917a5 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectLiner.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +public 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) { } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index 8208c72..6d5b9a5 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -1,4 +1,5 @@  +using Microsoft.Extensions.Logging; using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; using System.Windows.Forms; @@ -18,12 +19,17 @@ public partial class FormLinerCollection : Form /// private AbstractCompany? _company = null; /// + /// Логгер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormLinerCollection() + public FormLinerCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// /// Выбор компании @@ -233,13 +239,16 @@ public partial class FormLinerCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -253,14 +262,19 @@ public partial class FormLinerCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + foreach (var collection in _storageCollection.Keys) + { + listBoxCollection.Items.Add(collection); + } RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ProjectLiner/ProjectLiner/Program.cs b/ProjectLiner/ProjectLiner/Program.cs index e3f64ca..8076eac 100644 --- a/ProjectLiner/ProjectLiner/Program.cs +++ b/ProjectLiner/ProjectLiner/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; + namespace ProjectLiner { internal static class Program @@ -11,7 +16,27 @@ namespace ProjectLiner // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormLinerCollection()); + + ServiceCollection services = new(); + ConfigureService(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// DI + /// + /// + private static void ConfigureService(ServiceCollection services) + { + services + .AddSingleton() + .AddLogging(option => { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("serilog.config"); + }); + + } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/ProjectLiner.csproj b/ProjectLiner/ProjectLiner/ProjectLiner.csproj index 244387d..bf72d90 100644 --- a/ProjectLiner/ProjectLiner/ProjectLiner.csproj +++ b/ProjectLiner/ProjectLiner/ProjectLiner.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/serilog.config b/ProjectLiner/ProjectLiner/serilog.config new file mode 100644 index 0000000..54e4ba6 --- /dev/null +++ b/ProjectLiner/ProjectLiner/serilog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file