diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 8e8a1da..67fc9f7 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectContainerShip.Drawnings; +using ProjectContainerShip.Exceptions; namespace ProjectContainerShip.CollectionGenericObjects; /// @@ -95,8 +96,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningShip? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningShip? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException) { }; } return bitmap; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 0d261d8..11b35d1 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -27,7 +27,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - int Insert (T obj, int position); + bool Insert (T obj, int position); /// /// Удаление объекта из коллекции с конктретной позиции diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index 140aea1..a076684 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectContainerShip.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -49,42 +50,41 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - else - { - return null; - } - + if (position < 0 || position >= _collection.Count) + throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) { return -1; } - _collection.Add(obj); - return Count; - + if (_collection.Count + 1 <= _maxCount) + { + _collection.Add(obj); + return _collection.Count - 1; + } + return -1; + throw new CollectionOverflowException(MaxCount); } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { - if (position < 0 || position >= Count || Count == _maxCount) - { - return -1; - } + if (_collection.Count + 1 > _maxCount || position < 0 || position >= _collection.Count) + return false; + if (_collection.Count + 1 > MaxCount) + throw new CollectionOverflowException(MaxCount); + if (position < 0 || position >= MaxCount) + throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - - return position; - + return true; } public T Remove(int position) { - if (position >= Count || position < 0) return null; - T? obj = _collection[position]; + if (position < 0 || position >= _collection.Count) + return null; + throw new PositionOutOfCollectionException(position); + T temp = _collection[position]; _collection.RemoveAt(position); - return obj; + return temp; } public IEnumerable GetItems() diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index b188f28..3e7854d 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectContainerShip.CollectionGenericObjects; +using ProjectContainerShip.Exceptions; + +namespace ProjectContainerShip.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -48,60 +50,64 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - - return null; + if (position < 0 || position >= _collection.Length) + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + return _collection[position]; } public int Insert(T obj) { - return Insert(obj, 0); + for (int i = 0; i < _collection.Length; i++) + { + if (_collection[i] == null) + { + _collection[i] = obj; + return i; + } + } + return -1; + throw new CollectionOverflowException(_collection.Length); } - public int Insert(T obj, int position) + public bool Insert(T obj, int position) { - if (position < 0 || position >= Count) - { - return -1; - } - if (_collection[position] == null) + if (position < 0 || position >= _collection.Length) // проверка позиции + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) // Попытка вставить на указанную позицию { _collection[position] = obj; - return position; + return true; } - - for (int i = position + 1; i < Count; i++) + for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной { if (_collection[i] == null) { _collection[i] = obj; - return i; + return true; } } - for (int i = position - 1; i >= 0; i--) + for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной { if (_collection[i] == null) { _collection[i] = obj; - return i; + return true; } } - - return -1; + throw new CollectionOverflowException(_collection.Length); } public T Remove(int position) { - if (position < 0 || position >= Count) - { - return null; - } - T obj = _collection[position]; + if (position < 0 || position >= _collection.Length) // проверка позиции + throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + T temp = _collection[position]; _collection[position] = null; - return obj; + return temp; } public IEnumerable GetItems() diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs index cee3398..2c56570 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs @@ -1,4 +1,5 @@ using ProjectContainerShip.Drawnings; +using ProjectContainerShip.Exceptions; namespace ProjectContainerShip.CollectionGenericObjects; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index e66e577..4d3928b 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectContainerShip.Drawnings; +using ProjectContainerShip.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -157,11 +158,15 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + /// + /// Загрузка информации по кораблям в хранилище из файла + /// + /// Путь и имя файла + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) @@ -169,7 +174,7 @@ public class StorageCollection string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - return false; + throw new FormatException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -182,7 +187,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -190,17 +195,24 @@ public class StorageCollection string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningShip() is T boat) + if (elem?.CreateDrawningShip() is T ship) { - if (collection.Insert(boat) == -1) - return false; + try + { + if (collection.Insert(ship) == -1) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - - return true; } /// diff --git a/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..586d959 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal 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/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..93f264f --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..6ea9fc5 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectContainerShip.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/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs index 8126fc4..5436814 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -1,6 +1,8 @@ using ProjectContainerShip.CollectionGenericObjects; using ProjectContainerShip.Drawnings; using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using ProjectContainerShip.Exceptions; namespace ProjectContainerShip @@ -20,15 +22,22 @@ namespace ProjectContainerShip /// private readonly StorageCollection _storageCollection; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } + #region Работа с компанией /// /// Выбор компании /// @@ -57,21 +66,31 @@ namespace ProjectContainerShip /// Добавление лодки в коллекцию /// /// + /// + /// Метод установки корабля в компанию + /// private void SetShip(DrawningShip? ship) { - if (_company == null || ship == null) - { + if (_company == null) return; - } - - if (_company + ship != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + ship != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавление корабля {ship} в коллекцию", ship); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship); + } } - else + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("Ошибка переполнения коллекции"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -91,17 +110,34 @@ namespace ProjectContainerShip { return; } + try + { + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удаление корабля по индексу {pos}", pos); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos); + } + } + catch (ObjectNotFoundException ex) + { + + MessageBox.Show("Ошибка: отсутствует объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + catch (PositionOutOfCollectionException ex) + { + + MessageBox.Show("Ошибка: неправильная позиция"); + _logger.LogError("Ошибка: {Message}", ex.Message); + } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } } /// @@ -152,7 +188,8 @@ namespace ProjectContainerShip pictureBox.Image = _company.Show(); } - + #endregion + #region Работа с коллекцией /// /// Добавление коллекции /// @@ -163,6 +200,7 @@ namespace ProjectContainerShip if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } CollectionType collectionType = CollectionType.None; @@ -176,6 +214,7 @@ namespace ProjectContainerShip } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); RefreshListBoxItems(); } @@ -203,16 +242,15 @@ namespace ProjectContainerShip /// private void ButtonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; - } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); RefreshListBoxItems(); } @@ -241,11 +279,13 @@ namespace ProjectContainerShip case "Хранилище": _company = new ShipSharingService(pictureBox.Width, pictureBox.Height, collection); break; + default: + return; } - panelCompanyTools.Enabled = true; RefreshListBoxItems(); } + #endregion /// /// Обработка нажатия "Сохранение" @@ -254,15 +294,17 @@ namespace ProjectContainerShip /// private void saveToolStripMenuItem_Click(object sender, EventArgs e) { - 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); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -276,14 +318,17 @@ namespace ProjectContainerShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); RefreshListBoxItems(); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectContainerShip/ProjectContainerShip/Program.cs b/ProjectContainerShip/ProjectContainerShip/Program.cs index 4f76f20..ccbabc9 100644 --- a/ProjectContainerShip/ProjectContainerShip/Program.cs +++ b/ProjectContainerShip/ProjectContainerShip/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace ProjectContainerShip { internal static class Program @@ -11,7 +16,28 @@ namespace ProjectContainerShip // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormShipCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "C:\\Users\\\\Desktop\\\\\\1 \\2\\OOP\\Lab\\ProjectContainerShip\\ProjectContainerShip\\appSetting.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/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj b/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj index 244387d..008562e 100644 --- a/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj +++ b/ProjectContainerShip/ProjectContainerShip/ProjectContainerShip.csproj @@ -8,6 +8,16 @@ enable + + + + + + + + + + True @@ -23,4 +33,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectContainerShip/ProjectContainerShip/appSetting.json b/ProjectContainerShip/ProjectContainerShip/appSetting.json new file mode 100644 index 0000000..d39f3a5 --- /dev/null +++ b/ProjectContainerShip/ProjectContainerShip/appSetting.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } +} \ No newline at end of file