From fd88fea05fb072a4df0e6f45b5044c78ded64330 Mon Sep 17 00:00:00 2001 From: strwbrry1 Date: Wed, 15 May 2024 17:20:36 +0400 Subject: [PATCH] Lab 7 done --- Catamaran/Catamaran/BoatDelegate.cs | 12 --- Catamaran/Catamaran/Catamaran.csproj | 20 ++++ .../ArrayGenericObjects.cs | 30 +++--- .../ListGenericObjects.cs | 24 ++--- .../StorageCollection.cs | 31 ++++-- .../Exceptions/CollectionOverflowException.cs | 23 ++++ .../Exceptions/ObjectNotFoundException.cs | 19 ++++ .../Exceptions/PositionOutOfRangeException.cs | 19 ++++ Catamaran/Catamaran/FormBoatColletion.cs | 102 ++++++++++++------ Catamaran/Catamaran/FormBoatConfig.cs | 4 - Catamaran/Catamaran/Program.cs | 27 ++++- Catamaran/Catamaran/nlog.config | 13 +++ Catamaran/Catamaran/serilogConfig.json | 21 ++++ 13 files changed, 259 insertions(+), 86 deletions(-) delete mode 100644 Catamaran/Catamaran/BoatDelegate.cs create mode 100644 Catamaran/Catamaran/Exceptions/CollectionOverflowException.cs create mode 100644 Catamaran/Catamaran/Exceptions/ObjectNotFoundException.cs create mode 100644 Catamaran/Catamaran/Exceptions/PositionOutOfRangeException.cs create mode 100644 Catamaran/Catamaran/nlog.config create mode 100644 Catamaran/Catamaran/serilogConfig.json diff --git a/Catamaran/Catamaran/BoatDelegate.cs b/Catamaran/Catamaran/BoatDelegate.cs deleted file mode 100644 index 4c1fa91..0000000 --- a/Catamaran/Catamaran/BoatDelegate.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Catamaran.Drawings; - -namespace Catamaran -{ - public delegate void BoatDelegate(DrawingBoat boat); - -} diff --git a/Catamaran/Catamaran/Catamaran.csproj b/Catamaran/Catamaran/Catamaran.csproj index af03d74..b9acdea 100644 --- a/Catamaran/Catamaran/Catamaran.csproj +++ b/Catamaran/Catamaran/Catamaran.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True @@ -23,4 +34,13 @@ + + + Always + + + Always + + + \ No newline at end of file diff --git a/Catamaran/Catamaran/CollectionGenericObjects/ArrayGenericObjects.cs b/Catamaran/Catamaran/CollectionGenericObjects/ArrayGenericObjects.cs index 321e0bd..2f30173 100644 --- a/Catamaran/Catamaran/CollectionGenericObjects/ArrayGenericObjects.cs +++ b/Catamaran/Catamaran/CollectionGenericObjects/ArrayGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using Catamaran.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -49,7 +50,7 @@ namespace Catamaran.CollectionGenericObjects { return _collection[position]; } - return null; + throw new PositionOutOfRangeException(position) ; } public int Insert(T obj) @@ -62,31 +63,31 @@ namespace Catamaran.CollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position < Count || position >= 0) + if (position > Count || position < 0) { - if (_collection[position] == null) + throw new PositionOutOfRangeException(position); + } + if (_collection[position] == null) { _collection[position] = obj; return position; } - else + else + { + for (int i = 0; i < Count; i++) { - for (int i = 0; i < Count; i++) + if (_collection[i] == null) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[i] = obj; + return i; } } } - return -1; } @@ -94,8 +95,9 @@ namespace Catamaran.CollectionGenericObjects { if (position > Count || position < 0) { - return null; + throw new PositionOutOfRangeException(position); } + if (_collection[position] == null) throw new ObjectNotFoundException(); T? obj = _collection[position]; _collection[position] = null; return obj; diff --git a/Catamaran/Catamaran/CollectionGenericObjects/ListGenericObjects.cs b/Catamaran/Catamaran/CollectionGenericObjects/ListGenericObjects.cs index 69bf080..cf1cd2c 100644 --- a/Catamaran/Catamaran/CollectionGenericObjects/ListGenericObjects.cs +++ b/Catamaran/Catamaran/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using Catamaran.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -42,28 +43,27 @@ namespace Catamaran.CollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfRangeException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(); return _collection[position]; } public int Insert(T obj) { - if (Count + 1 > _maxCount) - { - return -1; - } + if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return 1; } public int Insert(T obj, int position) { - if (position < 0 || position > Count || Count + 1 > _maxCount) + if (position < 0 || position > Count) { - return -1; + throw new PositionOutOfRangeException(position); + } + if (Count + 1 > _maxCount) + { + throw new CollectionOverflowException(Count); } _collection.Insert(position, obj); return 1; @@ -73,7 +73,7 @@ namespace Catamaran.CollectionGenericObjects { if (position < 0 || position > Count) { - return null; + throw new PositionOutOfRangeException(position); } T? obj = _collection[position]; _collection.RemoveAt(position); diff --git a/Catamaran/Catamaran/CollectionGenericObjects/StorageCollection.cs b/Catamaran/Catamaran/CollectionGenericObjects/StorageCollection.cs index 7ca5dd6..2b93ec3 100644 --- a/Catamaran/Catamaran/CollectionGenericObjects/StorageCollection.cs +++ b/Catamaran/Catamaran/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using Catamaran.Drawings; +using Catamaran.Exceptions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -66,11 +67,11 @@ namespace Catamaran.CollectionGenericObjects } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -112,14 +113,13 @@ namespace Catamaran.CollectionGenericObjects } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует!"); } using (StreamReader reader = new(filename)) @@ -127,11 +127,11 @@ namespace Catamaran.CollectionGenericObjects string line = reader.ReadLine(); if (line == null || line.Length == 0) { - return false; + throw new ArgumentException("В файле нет данных"); } if (!line.Equals(_collectionKey)) { - return false; + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); @@ -147,7 +147,8 @@ namespace Catamaran.CollectionGenericObjects ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]); + } collection.MaxCount = Convert.ToInt32(record[2]); @@ -157,17 +158,25 @@ namespace Catamaran.CollectionGenericObjects { if (elem?.CreateDrawingBoat() is T boat) { - if (collection.Insert(boat) < 0) + try { - return false; + if (collection.Insert(boat) < 0) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + + } } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } + } } _storages.Add(record[0], collection); } } - return true; } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) diff --git a/Catamaran/Catamaran/Exceptions/CollectionOverflowException.cs b/Catamaran/Catamaran/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..0eec1f2 --- /dev/null +++ b/Catamaran/Catamaran/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Catamaran.Exceptions +{ + [Serializable] + internal class CollectionOverflowException : ApplicationException + { + public CollectionOverflowException(int count) : base("Превышено количество элементов коллекции: count" + count) { } + + public CollectionOverflowException() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Catamaran/Catamaran/Exceptions/ObjectNotFoundException.cs b/Catamaran/Catamaran/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c5c7adc --- /dev/null +++ b/Catamaran/Catamaran/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 Catamaran.Exceptions +{ + [Serializable] + internal class ObjectNotFoundException : ApplicationException + { + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Catamaran/Catamaran/Exceptions/PositionOutOfRangeException.cs b/Catamaran/Catamaran/Exceptions/PositionOutOfRangeException.cs new file mode 100644 index 0000000..e1354f1 --- /dev/null +++ b/Catamaran/Catamaran/Exceptions/PositionOutOfRangeException.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 Catamaran.Exceptions +{ + [Serializable] + internal class PositionOutOfRangeException : ApplicationException + { + public PositionOutOfRangeException(int i) : base("Не найден объект по позиции " + i) { } + public PositionOutOfRangeException() : base() { } + public PositionOutOfRangeException(string message) : base(message) { } + public PositionOutOfRangeException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Catamaran/Catamaran/FormBoatColletion.cs b/Catamaran/Catamaran/FormBoatColletion.cs index 76e13ba..138d893 100644 --- a/Catamaran/Catamaran/FormBoatColletion.cs +++ b/Catamaran/Catamaran/FormBoatColletion.cs @@ -1,6 +1,9 @@ using Catamaran.CollectionGenericObjects; using Catamaran.Drawings; +using Catamaran.Exceptions; +using Microsoft.Extensions.Logging; using System; +using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -19,10 +22,13 @@ namespace Catamaran private readonly StorageCollection _storageCollection; - public FormBoatColletion() + private readonly ILogger _logger; + + public FormBoatColletion(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -50,14 +56,17 @@ namespace Catamaran return; } - if (_company + boat >= 0) + try { + int addingObj = _company + boat; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}"); pictureBox.Image = _company.Show(); } - else + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Не удалось добавить объект {ex.Message}"); } } @@ -86,14 +95,22 @@ namespace Catamaran } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { + object delObj = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Удален объект по позиции {pos}"); pictureBox.Image = _company.Show(); } - else + catch (ObjectNotFoundException ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект по позиции {pos}"); + } + catch (PositionOutOfRangeException) + { + MessageBox.Show("Удаление вне рамкок коллекции"); + _logger.LogWarning($"Не удалось удалить объект по позиции {pos} - вне коллекции"); } } @@ -112,27 +129,34 @@ namespace Catamaran { return; } - - DrawingBoat? boat = null; - int counter = 100; - while (boat == null) + try { - boat = _company.GetRandomObject(); + DrawingBoat? boat = null; + int counter = 100; + while (boat == null) + { + boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) break; - } + counter--; - if (boat == null) - { - return; - } + if (counter <= 0) break; + } + if (boat == null) + { + throw new ObjectNotFoundException(); + } - FormCatamaran form = new() - { - SetBoat = boat - }; - form.ShowDialog(); + FormCatamaran form = new() + { + SetBoat = boat + }; + form.ShowDialog(); + } + catch (ObjectNotFoundException) + { + _logger.LogWarning($"Не удалось найти объект для отправки на тест"); + } + } private void RefreshListBoxItems() @@ -153,6 +177,7 @@ namespace Catamaran if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Неверно введены данные для создания коллекции"); return; } @@ -167,6 +192,7 @@ namespace Catamaran } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}"); RefreshListBoxItems(); } @@ -175,13 +201,16 @@ namespace Catamaran if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0) { MessageBox.Show("Не выбрана коллекция"); + _logger.LogWarning("Ошибка удаления коллекции - она не выбрана"); return; } + string temp = listBoxCollection.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation($"Удалена коллекция - {temp}"); RefreshListBoxItems(); } @@ -190,6 +219,7 @@ namespace Catamaran if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); + _logger.LogWarning("Ошибка создания компании - она не выбрана"); return; } @@ -197,6 +227,7 @@ namespace Catamaran if (collection == null) { MessageBox.Show("Коллекция не инициализирована"); + _logger.LogWarning("Ошибка инициализации коллекции"); return; } @@ -215,15 +246,18 @@ namespace Catamaran { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Успешно сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } + catch(Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка сохранения: {Message}", ex.Message); + } } } @@ -231,16 +265,20 @@ namespace Catamaran { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Успешно загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RefreshListBoxItems(); - } - else - { - MessageBox.Show("Ошибка загрузки", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка загрузки: {Message}", ex.Message); + } + } } } diff --git a/Catamaran/Catamaran/FormBoatConfig.cs b/Catamaran/Catamaran/FormBoatConfig.cs index 00aa38b..50fbda4 100644 --- a/Catamaran/Catamaran/FormBoatConfig.cs +++ b/Catamaran/Catamaran/FormBoatConfig.cs @@ -143,9 +143,5 @@ namespace Catamaran } } - private void panelWhite_Paint(object sender, PaintEventArgs e) - { - - } } } diff --git a/Catamaran/Catamaran/Program.cs b/Catamaran/Catamaran/Program.cs index f607f17..57f38c9 100644 --- a/Catamaran/Catamaran/Program.cs +++ b/Catamaran/Catamaran/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Catamaran { internal static class Program @@ -11,7 +16,27 @@ namespace Catamaran // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatColletion()); + + ServiceCollection services = new ServiceCollection(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + + Application.Run(serviceProvider.GetRequiredService()); + } + + public static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } \ No newline at end of file diff --git a/Catamaran/Catamaran/nlog.config b/Catamaran/Catamaran/nlog.config new file mode 100644 index 0000000..54e4ba6 --- /dev/null +++ b/Catamaran/Catamaran/nlog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Catamaran/Catamaran/serilogConfig.json b/Catamaran/Catamaran/serilogConfig.json new file mode 100644 index 0000000..a790fef --- /dev/null +++ b/Catamaran/Catamaran/serilogConfig.json @@ -0,0 +1,21 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "{Level:u4}: [{Timestamp:HH:mm:ss.fff}] - {Message:lj}{Exception}{NewLine}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Catamaran" + } + } + +} \ No newline at end of file