From ce84c8d6be9d009091c57c9e8a7194dd4ab5b7e4 Mon Sep 17 00:00:00 2001 From: zw1st <144824777+zw1st@users.noreply.github.com> Date: Mon, 10 Jun 2024 10:11:49 +0400 Subject: [PATCH] LabWork6 --- .../AbstractCompany.cs | 13 +- .../Cruiser/CollectionGenericObjects/Docs.cs | 14 ++- .../ListGenericObjects.cs | 24 +--- .../MassiveGenericObjects.cs | 57 +++++---- .../StorageCollection.cs | 31 +++-- Cruiser/Cruiser/Cruiser.csproj | 12 ++ .../Exceptions/CollectionOverflowException.cs | 18 +++ .../Exceptions/ObjectNotFoundException.cs | 19 +++ .../PositionOutOfCollectionException.cs | 18 +++ Cruiser/Cruiser/FormShipCollection.cs | 113 ++++++++++++------ Cruiser/Cruiser/Program.cs | 27 ++++- 11 files changed, 241 insertions(+), 105 deletions(-) create mode 100644 Cruiser/Cruiser/Exceptions/CollectionOverflowException.cs create mode 100644 Cruiser/Cruiser/Exceptions/ObjectNotFoundException.cs create mode 100644 Cruiser/Cruiser/Exceptions/PositionOutOfCollectionException.cs diff --git a/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs b/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs index 4495e2f..e17901a 100644 --- a/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs +++ b/Cruiser/Cruiser/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using Cruiser.Drawings; +using Cruiser.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -37,7 +38,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, которое можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeHeight * _placeSizeWidth); + private int GetMaxCount => (_pictureWidth - 70) * ((_pictureHeight - 20) / 2) / (_placeSizeHeight * _placeSizeWidth); /// /// Конструктор @@ -95,8 +96,14 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawingShip? obj = _collection?.Get(i); - obj?.DrawTransport(g); + try { + DrawingShip? obj = _collection?.Get(i); + obj?.DrawTransport(g); + } + catch (ObjectNotFoundException) + { + + } } return bitmap; } diff --git a/Cruiser/Cruiser/CollectionGenericObjects/Docs.cs b/Cruiser/Cruiser/CollectionGenericObjects/Docs.cs index 89db831..a6c8c2d 100644 --- a/Cruiser/Cruiser/CollectionGenericObjects/Docs.cs +++ b/Cruiser/Cruiser/CollectionGenericObjects/Docs.cs @@ -1,4 +1,5 @@ using Cruiser.Drawings; +using Cruiser.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -34,14 +35,19 @@ public class Docs : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (nowHeight > _pictureHeight) + if (nowHeight > (_pictureHeight / _placeSizeHeight) * _placeSizeHeight) { return; } - if (_collection?.Get(i) != null) + try { - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(nowWidth, nowHeight); + if (_collection?.Get(i) != null) + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(nowWidth, nowHeight); + } + } + catch (ObjectNotFoundException) { } if (nowWidth < _pictureWidth - _placeSizeWidth - 35) nowWidth += _placeSizeWidth; diff --git a/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs b/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs index 6bf28f1..5689d25 100644 --- a/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs +++ b/Cruiser/Cruiser/CollectionGenericObjects/ListGenericObjects.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; - +using Cruiser.Exceptions; namespace Cruiser.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects @@ -49,40 +49,28 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= Count) - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) - { - return -1; - } + if (Count == _maxCount) throw new CollectionOverflowException(); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (Count == _maxCount) - { - return -1; - } - if (position >= Count || position < 0) - { - 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) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); T temp = _collection[position]; _collection.RemoveAt(position); return temp; diff --git a/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs b/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs index 5cf2293..b818bd9 100644 --- a/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Cruiser/Cruiser/CollectionGenericObjects/MassiveGenericObjects.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; - +using Cruiser.Exceptions; namespace Cruiser.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects @@ -46,11 +46,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 || position < Count) - { - return _collection[position]; - } - return null; + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) throw new ObjectNotFoundException(); + return _collection[position]; } public int Insert(T obj) @@ -63,46 +61,47 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(); } public int Insert(T obj, int position) { - if (position >= _collection.Length || position < 0) + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + if (_collection[position] == null) { - return -1; + _collection[position] = obj; + return position; } - if (_collection[position] != null) + int temp = position + 1; + while (temp < Count) { - return -1; - } - - for (int i = position; i < _collection.Length; i++) - { - if (_collection[i] == null) + if (_collection[temp] == null) { - _collection[i] = obj; - return i; + _collection[temp] = obj; + return temp; } + ++temp; } - for (int i = 0; i < position; i++) + temp = position - 1; + while (temp >= 0) { - _collection[i] = obj; - return i; + if (_collection[temp] == null) + { + _collection[temp] = obj; + return temp; + } + --temp; } - - return -1; + throw new CollectionOverflowException(); } public T? Remove(int position) { - if (position > _collection.Length || position < 0) - { - return null; - } - T? obj = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(); + T? myObject = _collection[position]; + if (myObject == null) throw new ObjectNotFoundException(); _collection[position] = null; - return obj; + return myObject; } public IEnumerable GetItems() diff --git a/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs b/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs index 5cdfbfc..935a800 100644 --- a/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs +++ b/Cruiser/Cruiser/CollectionGenericObjects/StorageCollection.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Cruiser.Drawings; using Cruiser.Entities; +using Cruiser.Exceptions; namespace Cruiser.CollectionGenericObjects; public class StorageCollection where T : DrawingShip @@ -48,11 +50,11 @@ public class StorageCollection where T : DrawingShip /// /// Путь и имя файла /// 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)) { @@ -89,7 +91,6 @@ public class StorageCollection where T : DrawingShip using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } /// @@ -97,11 +98,11 @@ public class StorageCollection where T : DrawingShip /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } string bufferTextFromFile = ""; using (FileStream fs = new(filename, FileMode.Open)) @@ -117,12 +118,11 @@ public class StorageCollection where T : DrawingShip StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!strs[0].Equals(_collectionKey)) { - //если нет такой записи, то это не те данные - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); foreach (string data in strs) @@ -139,7 +139,7 @@ public class StorageCollection where T : DrawingShip StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, @@ -148,15 +148,22 @@ public class StorageCollection where T : DrawingShip { if (elem?.CreateDrawingShip() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(ship) == -1) + { + throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new DataException("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; + } /// diff --git a/Cruiser/Cruiser/Cruiser.csproj b/Cruiser/Cruiser/Cruiser.csproj index 663fdb8..8cc71a4 100644 --- a/Cruiser/Cruiser/Cruiser.csproj +++ b/Cruiser/Cruiser/Cruiser.csproj @@ -8,4 +8,16 @@ enable + + + + + + + + + + + + \ No newline at end of file diff --git a/Cruiser/Cruiser/Exceptions/CollectionOverflowException.cs b/Cruiser/Cruiser/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..89472ec --- /dev/null +++ b/Cruiser/Cruiser/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Cruiser.Exceptions; + +[Serializable] +public class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое колличество: " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/Cruiser/Cruiser/Exceptions/ObjectNotFoundException.cs b/Cruiser/Cruiser/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..0fe01ba --- /dev/null +++ b/Cruiser/Cruiser/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 Cruiser.Exceptions; + +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) + { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/Cruiser/Cruiser/Exceptions/PositionOutOfCollectionException.cs b/Cruiser/Cruiser/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..c3890c6 --- /dev/null +++ b/Cruiser/Cruiser/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Cruiser.Exceptions; + +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} diff --git a/Cruiser/Cruiser/FormShipCollection.cs b/Cruiser/Cruiser/FormShipCollection.cs index 00208ff..3717582 100644 --- a/Cruiser/Cruiser/FormShipCollection.cs +++ b/Cruiser/Cruiser/FormShipCollection.cs @@ -1,5 +1,8 @@ using Cruiser.CollectionGenericObjects; using Cruiser.Drawings; +using Cruiser.Exceptions; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; namespace Cruiser; @@ -7,27 +10,34 @@ public partial class FormShipCollection : Form { private readonly StorageCollection _storageCollection; private AbstractCompany? _company = null; - public FormShipCollection() + private readonly ILogger _logger; + public FormShipCollection(ILogger logger) { _storageCollection = new(); InitializeComponent(); + _logger = logger; } private void SetShip(DrawingShip? ship) { - if (_company == null || ship == null) + try { - return; - } + if (_company == null || ship == null) + { + return; + } + if (_company + ship != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: {0}", ship.GetDataForSave()); + } - if (_company + ship != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = _company.Show(); } - else + catch (CollectionOverflowException) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: В коллекции превышено допустимое количество"); } } @@ -55,21 +65,33 @@ public partial class FormShipCollection : Form { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos == 1) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = _company.Show(); + _logger.LogInformation("Удалён объект по позиции {0}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (PositionOutOfCollectionException) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка при удалении по позиции {pos}"); + _logger.LogError("Ошибка при удалении по позиции {0}", pos); + } + catch (ObjectNotFoundException) + { + MessageBox.Show($"Ошибка: Не найден объект по позиции {pos}"); + _logger.LogError("Ошибка: Не найден объект по позиции {0}", pos); } } @@ -79,27 +101,28 @@ public partial class FormShipCollection : Form { return; } - DrawingShip? ship = null; - int counter = 100; - while (ship == null) + try { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 100) + DrawingShip? ship = null; + int counter = 100; + while(ship == null) { - break; + ship = _company.GetRandomObject(); + counter--; + if (counter <= 0) break; } + if (ship == null) + { + return; + } + FormCruiser form = new FormCruiser(); + form.SetShip = ship; + form.ShowDialog(); } - if (ship == null) + catch (ObjectNotFoundException) { - return; + _logger.LogError("Ошибка при передаче на FormCruiser"); } - - FormCruiser form = new() - { - SetShip = ship - }; - form.ShowDialog(); } private void ButtonRefresh_Click(object sender, EventArgs e) @@ -132,6 +155,7 @@ public partial class FormShipCollection : Form _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RefreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType); } private void ButtonCollectionDel_Click(object sender, EventArgs e) @@ -149,6 +173,7 @@ public partial class FormShipCollection : Form _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RefreshListBoxItems(); + _logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text); } private void RefreshListBoxItems() { @@ -182,6 +207,8 @@ public partial class FormShipCollection : Form { case "Хранилище": _company = new Docs(pictureBoxCollection.Width, pictureBoxCollection.Height, collection); + _logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text); + _logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text); break; } @@ -193,15 +220,18 @@ public partial class FormShipCollection : 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("Не сохранилось", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -210,16 +240,23 @@ public partial class FormShipCollection : 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); + } + _logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName); RefreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось сохранить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } - } diff --git a/Cruiser/Cruiser/Program.cs b/Cruiser/Cruiser/Program.cs index 15dbcaa..d6c76d4 100644 --- a/Cruiser/Cruiser/Program.cs +++ b/Cruiser/Cruiser/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace Cruiser { internal static class Program @@ -11,7 +16,27 @@ namespace Cruiser // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + ServiceCollection services = new(); + ConfigureService(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + private static void ConfigureService(ServiceCollection services) + { + services + .AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + var config = new ConfigurationBuilder() + .AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + option.AddSerilog(Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(config) + .CreateLogger()); + }); + + } } } \ No newline at end of file