From ba8685e9dcee82060f81318f13b34d4c02dac031 Mon Sep 17 00:00:00 2001 From: gettterot Date: Sat, 20 Apr 2024 07:48:17 +0400 Subject: [PATCH 1/3] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=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 -- 2.25.1 From 7ac785ccfd3b55745e3272b972ac59c4afc432d0 Mon Sep 17 00:00:00 2001 From: gettterot Date: Wed, 15 May 2024 09:37:25 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D0=BD=20Logger,=20=D0=B0=20=D1=82=D0=B0=D0=BA=D0=B6?= =?UTF-8?q?=D0=B5=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20=D1=81=20=D1=83?= =?UTF-8?q?=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=D0=BC=20=D0=BB=D0=B0?= =?UTF-8?q?=D0=B9=D0=BD=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 7 +- .../ProjectLiner/Entities/EntityLiner.cs | 1 - .../FormLinerCollection.Designer.cs | 8 +- .../ProjectLiner/FormLinerCollection.cs | 80 +++++++++++++------ ProjectLiner/ProjectLiner/Program.cs | 36 +++++---- ProjectLiner/ProjectLiner/ProjectLiner.csproj | 6 +- ProjectLiner/ProjectLiner/serilog.config | 13 --- ProjectLiner/ProjectLiner/serilog.json | 19 +++++ 8 files changed, 111 insertions(+), 59 deletions(-) delete mode 100644 ProjectLiner/ProjectLiner/serilog.config create mode 100644 ProjectLiner/ProjectLiner/serilog.json diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index c70f706..e1dc795 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -45,8 +45,11 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); - if (_collection[position] == null) throw new ObjectNotFoundException(); + // Проверка позиции + if (position >= Count || position < 0) + { + throw new PositionOutOfCollectionException(position); + } return _collection[position]; } public int Insert(T obj) diff --git a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs index 0b44be7..cb1a862 100644 --- a/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs +++ b/ProjectLiner/ProjectLiner/Entities/EntityLiner.cs @@ -77,5 +77,4 @@ public class EntityLiner: EntityCommonLiner Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7])); } - } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs index ad3a8cc..15c3bdb 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs @@ -75,7 +75,7 @@ // buttonCreateCompany // buttonCreateCompany.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point); - buttonCreateCompany.Location = new Point(8, 520); + buttonCreateCompany.Location = new Point(7, 495); buttonCreateCompany.Margin = new Padding(5); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(257, 38); @@ -96,13 +96,13 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 43); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(266, 405); + panelStorage.Size = new Size(266, 370); panelStorage.TabIndex = 7; // // buttonCollectionDel // buttonCollectionDel.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point); - buttonCollectionDel.Location = new Point(5, 348); + buttonCollectionDel.Location = new Point(3, 314); buttonCollectionDel.Margin = new Padding(5); buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Size = new Size(257, 38); @@ -180,7 +180,7 @@ comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(20, 458); + comboBoxSelectorCompany.Location = new Point(23, 419); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(242, 49); comboBoxSelectorCompany.TabIndex = 0; diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index 6d5b9a5..7446d28 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging; using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; using System.Windows.Forms; namespace ProjectLiner; @@ -58,19 +59,23 @@ public partial class FormLinerCollection : Form /// private void SetLiner(DrawningCommonLiner liner) { - if (_company == null || liner == null) + try { - return; + if (_company == null || liner == null) + { + return; + } + if (_company + liner != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + liner.GetDataForSave()); + } } - - if (_company + liner != -1) + catch (CollectionOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -81,26 +86,43 @@ public partial class FormLinerCollection : Form /// private void ButtonRemoveLiner_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition?.Text) || _company == null) + if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null) { return; } + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } + try + { + int pos = Convert.ToInt32(maskedTextBox1.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление объекта по индексу " + pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить объект из коллекции по индексу " + pos); + } + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } + /// /// Передача объекта в другую форму /// @@ -118,14 +140,19 @@ public partial class FormLinerCollection : Form { liner = _company.GetRandomObject(); counter--; - if (counter <= 0) break; + if (counter <= 0) + { + break; + } } if (liner == null) { return; } - FormLiner form = new FormLiner(); - form.SetLiner = liner; + FormLiner form = new() + { + SetLiner = liner + }; form.ShowDialog(); } /// @@ -153,6 +180,7 @@ public partial class FormLinerCollection : Form if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } CollectionType collectionType = CollectionType.None; @@ -166,6 +194,7 @@ public partial class FormLinerCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция типа " + collectionType + " с названием " + textBoxCollectionName.Text); } /// /// Удаление коллекции @@ -184,6 +213,7 @@ public partial class FormLinerCollection : Form return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } /// @@ -271,10 +301,12 @@ public partial class FormLinerCollection : Form listBoxCollection.Items.Add(collection); } RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } catch (Exception ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectLiner/ProjectLiner/Program.cs b/ProjectLiner/ProjectLiner/Program.cs index 8076eac..68aced0 100644 --- a/ProjectLiner/ProjectLiner/Program.cs +++ b/ProjectLiner/ProjectLiner/Program.cs @@ -1,7 +1,7 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; -using System; +using Serilog; namespace ProjectLiner { @@ -15,28 +15,36 @@ namespace ProjectLiner { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); + ApplicationConfiguration.Initialize(); ServiceCollection services = new(); - ConfigureService(services); + ConfigureServices(services); using ServiceProvider serviceProvider = services.BuildServiceProvider(); Application.Run(serviceProvider.GetRequiredService()); } /// - /// DI + /// Êîíôèãóðàöèÿ ñåðâèñà DI /// /// - private static void ConfigureService(ServiceCollection services) + private static void ConfigureServices(ServiceCollection services) { - services - .AddSingleton() - .AddLogging(option => { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("serilog.config"); - }); - - + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/ProjectLiner.csproj b/ProjectLiner/ProjectLiner/ProjectLiner.csproj index bf72d90..5e663e8 100644 --- a/ProjectLiner/ProjectLiner/ProjectLiner.csproj +++ b/ProjectLiner/ProjectLiner/ProjectLiner.csproj @@ -11,6 +11,10 @@ + + + + @@ -29,7 +33,7 @@ - + Always diff --git a/ProjectLiner/ProjectLiner/serilog.config b/ProjectLiner/ProjectLiner/serilog.config deleted file mode 100644 index 54e4ba6..0000000 --- a/ProjectLiner/ProjectLiner/serilog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/serilog.json b/ProjectLiner/ProjectLiner/serilog.json new file mode 100644 index 0000000..21a527e --- /dev/null +++ b/ProjectLiner/ProjectLiner/serilog.json @@ -0,0 +1,19 @@ +{ + "Serilog": { + "Using": [ + "Serilog.Sinks.File" + ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log" + } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1 From 392189d5b2c044f0c001fd40fed96c7037753210 Mon Sep 17 00:00:00 2001 From: gettterot Date: Thu, 16 May 2024 08:27:33 +0400 Subject: [PATCH 3/3] =?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=D1=81=D0=B4=D0=B0=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 42 +- .../LinerSharingService.cs | 107 ++-- .../ListGenericObjects.cs | 154 ++--- .../MassiveGenericObjects.cs | 37 +- .../StorageCollection.cs | 372 +++++------ .../FormLinerCollection.Designer.cs | 2 +- .../ProjectLiner/FormLinerCollection.cs | 586 +++++++++--------- .../ProjectLiner/FormLinerCollection.resx | 3 + 8 files changed, 689 insertions(+), 614 deletions(-) diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs index b8f6cd8..c85dc44 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs @@ -1,9 +1,12 @@ using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; namespace ProjectLiner.CollectionGenericObjects { /// - /// Абстракция компании, хранящий коллекцию лайнеров + /// Абстракция компании, хранящий коллекцию автомобилей /// public abstract class AbstractCompany { @@ -15,7 +18,7 @@ namespace ProjectLiner.CollectionGenericObjects /// /// Размер места (высота) /// - protected readonly int _placeSizeHeight = 110; + protected readonly int _placeSizeHeight = 150; /// /// Ширина окна @@ -28,21 +31,21 @@ namespace ProjectLiner.CollectionGenericObjects protected readonly int _pictureHeight; /// - /// Коллекция лайнеров + /// Коллекция автомобилей /// protected ICollectionGenericObjects? _collection = null; /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight); /// /// Конструктор /// /// Ширина окна /// Высота окна - /// Коллекция лайнеров + /// Коллекция автомобилей public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { _pictureWidth = picWidth; @@ -55,12 +58,11 @@ namespace ProjectLiner.CollectionGenericObjects /// Перегрузка оператора сложения для класса /// /// Компания - /// Добавляемый объект + /// Добавляемый объект /// - - public static int operator +(AbstractCompany company, DrawningCommonLiner airplan) + public static int operator +(AbstractCompany company, DrawningCommonLiner airplane) { - return company._collection.Insert(airplan); + return company._collection.Insert(airplane); } /// @@ -71,7 +73,7 @@ namespace ProjectLiner.CollectionGenericObjects /// public static DrawningCommonLiner operator -(AbstractCompany company, int position) { - return company._collection.Remove(position) ; + return company._collection.Remove(position); } /// @@ -81,7 +83,14 @@ namespace ProjectLiner.CollectionGenericObjects public DrawningCommonLiner? GetRandomObject() { Random rnd = new(); - return _collection?.Get(rnd.Next(GetMaxCount)); + try + { + return _collection?.Get(rnd.Next(GetMaxCount)); + } + catch (ObjectNotFoundException) + { + return null; + } } /// @@ -97,8 +106,15 @@ namespace ProjectLiner.CollectionGenericObjects SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningCommonLiner? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningCommonLiner? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) + { + continue; + } } return bitmap; diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs index ad2d528..0d43197 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/LinerSharingService.cs @@ -1,64 +1,67 @@ using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; -namespace ProjectLiner.CollectionGenericObjects; - -/// -/// Реализация абстрактной компании - лайнер -/// -public class LinerSharingService : AbstractCompany +namespace ProjectLiner.CollectionGenericObjects { - /// - /// Конструктор - /// - /// Ширина - /// Высота - /// Коллекция - public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) - { - } - protected override void DrawBackgound(Graphics g) + public class LinerSharingService : AbstractCompany { - Pen pen = new(Color.Black, 4); - for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) { - for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) + } + + protected override void DrawBackgound(Graphics g) + { + Pen pen = new(Color.Black, 4); + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { - g.DrawLine(pen, i * _placeSizeWidth, (int)(j * _placeSizeHeight * 1.3), - i * _placeSizeWidth + _placeSizeWidth - 40, (int)(j * _placeSizeHeight * 1.3)); + for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) + { + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, + i * _placeSizeWidth + _placeSizeWidth - 40, j * _placeSizeHeight); + } + g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); + } + } + + protected override void SetObjectsPosition() + { + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + + int curWidth = width - 1; + int curHeight = 0; + + for (int i = 0; i < (_collection?.Count ?? 0); i++) + { + try + { + if (_collection.Get(i) != null) + { + _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5); + } + + if (curWidth > 0) + curWidth--; + else + { + curWidth = width - 1; + curHeight++; + } + if (curHeight > height) + { + return; + } + } + catch (ObjectNotFoundException) + { + break; + } } - g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); } } - - protected override void SetObjectsPosition() - { - int width = _pictureWidth / _placeSizeWidth; - int height = _pictureHeight / _placeSizeHeight; - - int curWidth = width - 1; - int curHeight = 0; - - for (int i = 0; i < (_collection?.Count ?? 0); i++) - { - if (_collection?.Get(i) != null) - { - _collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 10, (int)(curHeight * _placeSizeHeight * 1.3)); - } - - if (curWidth > 0) - curWidth--; - else - { - curWidth = width - 1; - curHeight++; - } - if (curHeight > height) - { - return; - } - } - } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index e1dc795..d37225b 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -1,85 +1,97 @@ -using ProjectLiner.CollectionGenericObjects; + +using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Exceptions; -using System.Collections.Generic; -/// -/// Параметризованный набор объектов -/// -/// Параметр: ограничение - ссылочный тип -public class ListGenericObjects : ICollectionGenericObjects - where T : class +namespace ProjectLiner.CollectionGenericObjects { /// - /// Список объектов, которые храним + /// Параметризованный набор объектов /// - private readonly List _collection; - /// - /// Максимально допустимое число объектов в списке - /// - private int _maxCount; - public int Count => _collection.Count; - public int MaxCount + /// Параметр: ограничение - ссылочный тип + public class ListGenericObjects : ICollectionGenericObjects + where T : class { - get + /// + /// Список объектов, которые храним + /// + private readonly List _collection; + + /// + /// Максимально допустимое число объектов в списке + /// + private int _maxCount; + + public int Count => _collection.Count; + + public int MaxCount { - return _maxCount; + get + { + return _maxCount; + } + + set + { + if (value > 0) + { + _maxCount = value; + } + } } - set + public CollectionType GetCollectionType => CollectionType.List; + + /// + /// Конструктор + /// + public ListGenericObjects() { - if (value > 0) + _collection = new(); + } + + public T? Get(int position) + { + if (position >= Count || position < 0) + throw new PositionOutOfCollectionException(position); + + return _collection[position]; + } + + public int Insert(T obj) + { + if (Count >= _maxCount) + throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; + } + + public int Insert(T obj, int position) + { + if (Count == _maxCount) + throw new CollectionOverflowException(Count); + if (position < 0 || position > Count) + throw new PositionOutOfCollectionException(position); ; + _collection.Insert(position, obj); + return position; + } + + public T? Remove(int position) + { + if (position < 0 || position > Count) + throw new PositionOutOfCollectionException(position); + + T? temp = _collection[position]; + _collection.RemoveAt(position); + return temp; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) { - _maxCount = value; + yield return _collection[i]; } } } - - public CollectionType GetCollectionType => CollectionType.List; - - /// - /// Конструктор - /// - public ListGenericObjects() - { - _collection = new(); - } - public T? Get(int position) - { - // Проверка позиции - if (position >= Count || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - return _collection[position]; - } - public int Insert(T obj) - { - if (Count == _maxCount) throw new CollectionOverflowException(); - _collection.Add(obj); - return Count; - } - - public int Insert(T obj, int position) - { - 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) - { - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); - T obj = _collection[position]; - _collection.RemoveAt(position); - return obj; - } - - public IEnumerable GetItems() - { - for (int i = 0; i < _collection.Count; ++i) - { - yield return _collection[i]; - } - } -} \ No newline at end of file +} diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index cd419af..99f8a17 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,7 @@  using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; namespace ProjectLiner.CollectionGenericObjects { @@ -14,7 +16,7 @@ namespace ProjectLiner.CollectionGenericObjects /// Массив объектов, которые храним /// private T?[] _collection; - + public int Count => _collection.Length; public int MaxCount @@ -52,7 +54,10 @@ namespace ProjectLiner.CollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + if (position < 0 || position >= Count) + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); return _collection[position]; } @@ -66,18 +71,20 @@ namespace ProjectLiner.CollectionGenericObjects return i; } } - throw new CollectionOverflowException(); + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { + if (position >= Count || position < 0) + throw new PositionOutOfCollectionException(position); - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); if (_collection[position] == null) { _collection[position] = obj; return position; } + int temp = position + 1; while (temp < Count) { @@ -86,28 +93,34 @@ namespace ProjectLiner.CollectionGenericObjects _collection[temp] = obj; return temp; } - ++temp; + temp++; } + temp = position - 1; - while (temp >= 0) + while (temp > 0) { if (_collection[temp] == null) { _collection[temp] = obj; return temp; } - --temp; + temp--; } - throw new CollectionOverflowException(); + + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); - T? myObject = _collection[position]; - if (myObject == null) throw new ObjectNotFoundException(); + 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 myObject; + return temp; } public IEnumerable GetItems() diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs index abe8305..c434e79 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs @@ -1,214 +1,226 @@ -using ProjectLiner.CollectionGenericObjects; +using System.Data; +using System.IO; +using System.Text; using ProjectLiner.Drawnings; using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; -/// -/// Класс-хранилище коллекций -/// -/// -public class StorageCollection - where T : DrawningCommonLiner +namespace ProjectLiner.CollectionGenericObjects { /// - /// Словарь (хранилище) с коллекциями + /// Класс-хранилище коллекций /// - readonly Dictionary> _storages; - - /// - /// Возвращение списка названий коллекций - /// - public List Keys => _storages.Keys.ToList(); - - /// - /// Ключевое слово, с которого должен начинаться файл - /// - private readonly string _collectionKey = "CollectionsStorage"; - - /// - /// Разделитель для записи ключа и значения элемента словаря - /// - private readonly string _separatorForKeyValue = "|"; - - /// - /// Разделитель для записей коллекции данных в файл - /// - private readonly string _separatorItems = ";"; - - /// - /// Конструктор - /// - public StorageCollection() + /// + public class StorageCollection + where T : DrawningCommonLiner { - _storages = new Dictionary>(); + /// + /// Словарь (хранилище) с коллекциями + /// + readonly Dictionary> _storages; - } - /// - /// Добавление коллекции в хранилище - /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) - { - if (name == null || _storages.ContainsKey(name)) { return; } - switch (collectionType) + /// + /// Возвращение списка названий коллекций + /// + public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// + /// Конструктор + /// + public StorageCollection() { - case CollectionType.None: + _storages = new Dictionary>(); + } + + /// + /// Добавление коллекции в хранилище + /// + /// Название коллекции + /// тип коллекции + public void AddCollection(string name, CollectionType collectionType) + { + if (name == null || _storages.ContainsKey(name)) return; - case CollectionType.Massive: - _storages[name] = new MassiveGenericObjects(); - return; - case CollectionType.List: - _storages[name] = new ListGenericObjects(); - return; - } - } - /// - /// Удаление коллекции - /// - /// Название коллекции - public void DelCollection(string name) - { - if (_storages.ContainsKey(name)) - _storages.Remove(name); - } - /// - /// Доступ к коллекции - /// - /// Название коллекции - /// - public ICollectionGenericObjects? this[string name] - { - get - { - if (name == null || !_storages.ContainsKey(name)) { return null; } - return _storages[name]; - } - } - /// - /// Сохранение информации по лайнерам в хранилище в файл - /// - /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public void SaveData(string filename) - { - if (_storages.Count == 0) - throw new Exception("В хранилище отсутствуют коллекции для сохранения"); - - 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); - if (value.Value.Count == 0) + switch (collectionType) { - continue; - } - - sw.Write(value.Key); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.GetCollectionType); - sw.Write(_separatorForKeyValue); - sw.Write(value.Value.MaxCount); - sw.Write(_separatorForKeyValue); - - foreach (T? item in value.Value.GetItems()) - { - string data = item?.GetDataForSave() ?? string.Empty; - if (string.IsNullOrEmpty(data)) - { - continue; - } - - sw.Write(data); - sw.Write(_separatorItems); + case CollectionType.None: + return; + case CollectionType.Massive: + _storages[name] = new MassiveGenericObjects(); + return; + case CollectionType.List: + _storages[name] = new ListGenericObjects(); + return; } } - } - /// - /// Загрузка информации по лайнерам в хранилище из файла - /// - /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public void LoadData(string filename) - { - if (!File.Exists(filename)) + /// + /// Удаление коллекции + /// + /// Название коллекции + public void DelCollection(string name) { - throw new FileNotFoundException($"{filename} не существует"); + if (_storages.ContainsKey(name)) + _storages.Remove(name); } - using (FileStream fs = new(filename, FileMode.Open)) + /// + /// Доступ к коллекции + /// + /// Название коллекции + /// + public ICollectionGenericObjects? this[string name] { - using StreamReader sr = new StreamReader(fs); - string line = sr.ReadLine(); - if (line == null || line.Length == 0) + get { - throw new Exception("Файл не подходит"); + if (name == null || !_storages.ContainsKey(name)) + return null; + + return _storages[name]; } - if (!line.Equals(_collectionKey)) + } + + /// + /// Сохранение информации по самолетам в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public void SaveData(string filename) + { + if (_storages.Count == 0) + throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения"); + + if (File.Exists(filename)) + File.Delete(filename); + + + using (StreamWriter sw = new(filename)) { - throw new Exception("В файле неверные данные"); - } - _storages.Clear(); - - while (!sr.EndOfStream) - { - string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + sw.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) { - 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?.CreateDrawningCommonLiner() is T commonLiner) + sw.Write(Environment.NewLine); + if (value.Value.Count == 0) { - try + continue; + } + + sw.Write(value.Key); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.GetCollectionType); + sw.Write(_separatorForKeyValue); + sw.Write(value.Value.MaxCount); + sw.Write(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) { - if (collection.Insert(commonLiner) == -1) - { - throw new Exception("Объект не удалось добавить в коллекцию: "); - } - } - catch (CollectionOverflowException ex) - { - throw new Exception("Коллекция переполнена", ex); + continue; } + + sw.Write(data); + sw.Write(_separatorItems); } } - _storages.Add(record[0], collection); } } - } - /// - /// Создание коллекции по типу - /// - /// - /// - private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) - { - return collectionType switch + /// + /// Загрузка информации по самолетам в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public void LoadData(string filename) { - CollectionType.Massive => new MassiveGenericObjects(), - CollectionType.List => new ListGenericObjects(), - _ => null, - }; + if (!File.Exists(filename)) + { + throw new FileNotFoundException("Файл не существует"); + } + + using (StreamReader sr = new(filename)) + { + string str = sr.ReadLine(); + if (str == null || str.Length == 0) + { + throw new FileFormatException("В файле нет данных"); + } + + if (!str.Equals(_collectionKey)) + { + throw new FileFormatException("В файле неверные данные"); + } + _storages.Clear(); + + while (!sr.EndOfStream) + { + string[] record = sr.ReadLine().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) + { + throw new InvalidOperationException("Не удалось создать коллекцию"); + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningCommonLiner() is T airplane) + { + try + { + if (collection.Insert(airplane) == -1) + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex) + { + throw new OverflowException("Коллекция переполнена", ex); + } + } + } + _storages.Add(record[0], collection); + } + } + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } -} \ No newline at end of file +} diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs index 15c3bdb..eb6b44c 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.Designer.cs @@ -249,7 +249,7 @@ button3.TabIndex = 4; button3.Text = "Удаление Лайнера"; button3.UseVisualStyleBackColor = true; - button3.Click += ButtonRemoveLiner_Click; + button3.Click += ButtonRemoveCommonLiner_Click; // // button4 // diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.cs b/ProjectLiner/ProjectLiner/FormLinerCollection.cs index 7446d28..a96fe40 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.cs +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.cs @@ -1,313 +1,329 @@ - -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; using ProjectLiner.Exceptions; +using ProjectLiner.CollectionGenericObjects; +using ProjectLiner.Exceptions; using System.Windows.Forms; -namespace ProjectLiner; -/// -/// Форма работы с компанией и ее коллекцией -/// -public partial class FormLinerCollection : Form +namespace ProjectLiner { /// - /// Хранилише коллекций + /// Форма работы с компанией и ее коллекцией /// - private readonly StorageCollection _storageCollection; - /// - /// Компания - /// - private AbstractCompany? _company = null; - /// - /// Логгер - /// - private readonly ILogger _logger; - /// - /// Конструктор - /// - public FormLinerCollection(ILogger logger) + public partial class FormLinerCollection : Form { - InitializeComponent(); - _storageCollection = new(); - _logger = logger; - } - /// - /// Выбор компании - /// - /// - /// - private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) - { - panelCompanyTools.Enabled = false; - } - /// - /// Добавление лайнера - /// - /// - /// - private void ButtonAddCommonLiner_Click(object sender, EventArgs e) - { - FormLinerConfig form = new(); - form.Show(); - form.AddEvent(SetLiner); - } + /// + /// Хранилише коллекций + /// + private readonly StorageCollection _storageCollection; - /// - /// Добавление Лайнера в коллекцию - /// - /// - private void SetLiner(DrawningCommonLiner liner) - { - try + /// + /// Компания + /// + private AbstractCompany? _company = null; + + /// + /// Логер + /// + private readonly ILogger _logger; + + /// + /// Конструктор + /// + public FormLinerCollection(ILogger logger) { - if (_company == null || liner == null) + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); + } + + /// + /// Выбор компании + /// + /// + /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + panelCompanyTools.Enabled = false; + } + + /// + /// Добавление самолета + /// + /// + /// + private void ButtonAddCommonLiner_Click(object sender, EventArgs e) + { + FormLinerConfig form = new(); + form.Show(); + form.AddEvent(SetLiner); + } + + /// + /// Добавление самолета в коллекцию + /// + /// + private void SetLiner(DrawningCommonLiner CommonLiner) + { + try + { + if (_company == null || CommonLiner == null) + { + return; + } + + if (_company + CommonLiner != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: {0}", CommonLiner.GetDataForSave()); + } + } + catch (CollectionOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + + /// + /// Удаление объекта + /// + /// + /// + private void ButtonRemoveCommonLiner_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null) { return; } - if (_company + liner != -1) + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + liner.GetDataForSave()); + return; } - } - catch (CollectionOverflowException ex) - { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } - /// - /// Удаление объекта - /// - /// - /// - private void ButtonRemoveLiner_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null) - { - return; - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - - try - { - int pos = Convert.ToInt32(maskedTextBox1.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Удаление объекта по индексу " + pos); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogInformation("Не удалось удалить объект из коллекции по индексу " + pos); - } - } - catch (ObjectNotFoundException ex) - { - MessageBox.Show(ex.Message); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - catch (PositionOutOfCollectionException ex) - { - MessageBox.Show(ex.Message); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } - - /// - /// Передача объекта в другую форму - /// - /// - /// - private void ButtonGoToCheck_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - DrawningCommonLiner? liner = null; - int counter = 100; - while (liner == null) - { - liner = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } - } - if (liner == null) - { - return; - } - FormLiner form = new() - { - SetLiner = liner - }; - form.ShowDialog(); - } - /// - /// Перерисовка коллекции - /// - /// - /// - private void ButtonRefresh_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - - pictureBox.Image = _company.Show(); - - } - /// - /// Добавление коллекции - /// - /// - /// - private void ButtonCollectionAdd_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) - { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); - return; - } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); - _logger.LogInformation("Добавлена коллекция типа " + collectionType + " с названием " + textBoxCollectionName.Text); - } - /// - /// Удаление коллекции - /// - /// - /// - private void ButtonCollectionDel_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - } - /// - /// Обновление списка в listBoxCollection - /// - private void RerfreshListBoxItems() - { - listBoxCollection.Items.Clear(); - for (int i = 0; i < _storageCollection.Keys?.Count; ++i) - { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) - { - listBoxCollection.Items.Add(colName); - } - } - } - /// - /// Создание компании - /// - /// - /// - private void ButtonCreateCompany_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - ICollectionGenericObjects? collection = - _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) - { - MessageBox.Show("Коллекция не проинициализирована"); - return; - } - switch (comboBoxSelectorCompany.Text) - { - case "Хранилище": - _company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection); - break; - } - panelCompanyTools.Enabled = true; - RerfreshListBoxItems(); - } - - /// - /// Обработка нажатия "Сохранение" - /// - /// - /// - private void saveToolStripMenuItem_Click(object sender, EventArgs e) - { - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { try { - _storageCollection.SaveData(saveFileDialog.FileName); - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } - } - - /// - /// Обработка нажатия "Загрузка" - /// - /// - /// - private void loadToolStripMenuItem_Click(object sender, EventArgs e) - { - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - try - { - _storageCollection.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - foreach (var collection in _storageCollection.Keys) + int pos = Convert.ToInt32(maskedTextBox1.Text); + if (_company - pos != null) { - listBoxCollection.Items.Add(collection); + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удалён объект по позиции {0}", pos); } - RerfreshListBoxItems(); - _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - catch (Exception ex) + catch (PositionOutOfCollectionException ex) { - MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message); _logger.LogError("Ошибка: {Message}", ex.Message); } + catch (ObjectNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + + /// + /// Передача объекта в другую форму + /// + /// + /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + try + { + DrawningCommonLiner? plane = null; + int counter = 100; + while (plane == null) + { + plane = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (plane == null) + { + return; + } + + FormLiner form = new() + { + SetLiner = plane + }; + form.ShowDialog(); + } + catch (ObjectNotFoundException) + { + _logger.LogError("Ошибка при передаче объекта на FormLiner"); + } + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } + + /// + /// Добавление коллекции + /// + /// + /// + private void ButtonCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + { + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции"); + return; + } + + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + collectionType = CollectionType.Massive; + else if (radioButtonList.Checked) + collectionType = CollectionType.List; + + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RefreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType); + } + + /// + /// Удаление коллекции + /// + /// + /// + private void ButtonCollectionDel_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedItems == null || listBoxCollection.SelectedIndex < 0) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RefreshListBoxItems(); + _logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text); + } + + /// + /// Обновление списка в listBoxCollection + /// + private void RefreshListBoxItems() + { + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + { + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) + listBoxCollection.Items.Add(colName); + } + } + + /// + /// Создание компании + /// + /// + /// + private void ButtonCreateCompany_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + if (collection == null) + { + MessageBox.Show("Коллекция не проинициализирована"); + return; + } + + switch (comboBoxSelectorCompany.Text) + { + case "Хранилище": + _company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text); + _logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text); + break; + } + + panelCompanyTools.Enabled = true; + RefreshListBoxItems(); + } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } + + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormLinerCollection.resx b/ProjectLiner/ProjectLiner/FormLinerCollection.resx index 1b18cc5..5982093 100644 --- a/ProjectLiner/ProjectLiner/FormLinerCollection.resx +++ b/ProjectLiner/ProjectLiner/FormLinerCollection.resx @@ -126,4 +126,7 @@ 519, 17 + + 25 + \ No newline at end of file -- 2.25.1