diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs index 5809d5a..7aad03d 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; namespace ProjectLiner.CollectionGenericObjects; @@ -103,8 +104,15 @@ 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 (Exception) + { + continue; + } } return bitmap; } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs index deb83e4..b475557 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ - +using ProjectLiner.Exceptions; + namespace ProjectLiner.CollectionGenericObjects; /// @@ -20,7 +21,8 @@ public class ListGenericObjects : ICollectionGenericObjects public int Count => _collection.Count; - public int MaxCount { + public int MaxCount + { get { return _maxCount; @@ -44,42 +46,53 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position > _collection.Count) + try { - return null; + if (_collection[position] == null) throw new ObjectNotFoundException(position); + return _collection[position]; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); } - return _collection[position]; } public int Insert(T obj) { - return Insert(obj, _collection.Count); + return Insert(obj, Count); } public int Insert(T obj, int position) { - if (_maxCount == _collection.Count || position < 0 || position > _collection.Count) + if (Count >= _maxCount) { - return -1; + throw new CollectionOverflowException(Count); + } + if (position > _collection.Count || position < 0) + { + throw new PositionOutOfCollectionException(); } _collection.Insert(position, obj); - return _collection.Count; + return Count; } public T? Remove(int position) { - if (position < 0 || position > _collection.Count) + try { - return null; + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); } - T? obj = _collection[position]; - _collection.RemoveAt(position); - return obj; } public IEnumerable GetItems() { - for (int i = 0; i < _collection.Count; ++i) + for (int i = 0; i < Count; ++i) { yield return _collection[i]; } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs index 817befc..1fafd03 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,4 @@ - +using ProjectLiner.Exceptions; namespace ProjectLiner.CollectionGenericObjects; @@ -50,8 +50,18 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) return _collection[position]; - else return null; + try + { + if (_collection[position] == null) + { + throw new ObjectNotFoundException(); + } + return _collection[position]; + } + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); + } } public int Insert(T obj) @@ -61,16 +71,10 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Insert(T obj, int position) { - if (position < 0 || position >= Count) + if (position < 0 || position > _collection.Length - 1) { - return -1; + throw new PositionOutOfCollectionException(); } - if (_collection[position] == null) - { - _collection[position] = obj; - return position; - } - for (int i = position; i < Count; i++) { if (_collection[i] == null) @@ -87,23 +91,25 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position < 0 || position >= _collection.Count()) - { - return null; - } - - if (_collection[position] != null) + try { T obj = _collection[position]; + if (obj == null) + { + throw new ObjectNotFoundException(position); + } _collection[position] = null; return obj; } - return null; + catch (IndexOutOfRangeException) + { + throw new PositionOutOfCollectionException(position); + } } public IEnumerable GetItems() diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ShipSharingService.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ShipSharingService.cs index 016f957..69c5900 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/ShipSharingService.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/ShipSharingService.cs @@ -53,13 +53,19 @@ public class ShipSharingService : AbstractCompany int row = 1, col = 1; for (int i = 0; i < _collection?.Count; i++, col++) { - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5); - if (col == countInRow) + try { - col = 0; - row++ - ; + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(locCoord[row * countInRow - col].Item1 + 5, locCoord[row * countInRow - col].Item2 + 5); + if (col == countInRow) + { + col = 0; + row++; + } + } + catch (Exception) + { + continue; } } } diff --git a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs index 3aa3486..bf12f6b 100644 --- a/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectLiner/ProjectLiner/CollectionGenericObjects/StorageCollection.cs @@ -1,7 +1,9 @@ using ProjectLiner.Drawnings; +using ProjectLiner.Exceptions; namespace ProjectLiner.CollectionGenericObjects; + /// /// Класс-хранилище коллекций /// @@ -9,16 +11,6 @@ namespace ProjectLiner.CollectionGenericObjects; public class StorageCollection where T : DrawningShip { - /// - /// Словарь (хранилище) с коллекциями - /// - private Dictionary> _storages; - - /// - /// Возвращение списка названий коллекций - /// - public List Keys => _storages.Keys.ToList(); - /// /// Ключевое слово, с которого должен начинаться файл /// @@ -34,7 +26,15 @@ public class StorageCollection /// private readonly string _separatorItems = ";"; + /// + /// Словарь (хранилище) с коллекциями + /// + readonly Dictionary> _storages; + /// + /// Возвращение списка названий коллекций + /// + public List Keys => _storages.Keys.ToList(); /// /// Конструктор @@ -106,18 +106,16 @@ public class StorageCollection /// Сохранение информации по кораблям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { File.Delete(filename); } - using (StreamWriter writer = new StreamWriter(filename)) { @@ -125,38 +123,41 @@ public class StorageCollection foreach (KeyValuePair> value in _storages) { writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}"); + foreach (T? item in value.Value.GetItems()) - { + { string data = item?.GetDataForSave() ?? string.Empty; if (!string.IsNullOrEmpty(data)) { - writer.Write(data + _separatorItems); + writer.WriteLine(data); } } - writer.WriteLine(); } } - return true; + } - + /// /// Загрузка информации по кораблям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader reader = new StreamReader(filename)) { string line = reader.ReadLine(); - if (line == null || !line.Equals(_collectionKey)) + if (line == null) { - return false; + throw new ArgumentException("В файле нет данных"); + } + if (!line.Equals(_collectionKey)) + { + throw new InvalidDataException("В файле неверные данные"); } _storages.Clear(); @@ -173,8 +174,8 @@ public class StorageCollection CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) - { - return false; + { + throw new InvalidCastException("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -185,17 +186,21 @@ public class StorageCollection { if (elem?.CreateDrawningShip() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + collection.Insert(ship); } + catch (Exception ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } + } } _storages.Add(record[0], collection); line = reader.ReadLine(); } } - return true; } /// diff --git a/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..0313f74 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectLiner.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) { } +} \ 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..b640393 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectLiner.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) { } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a262e67 --- /dev/null +++ b/ProjectLiner/ProjectLiner/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,20 @@ +using System.Runtime.Serialization; + +namespace ProjectLiner.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) { } +} \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/FormShipCollection.cs b/ProjectLiner/ProjectLiner/FormShipCollection.cs index e27c942..040f3b8 100644 --- a/ProjectLiner/ProjectLiner/FormShipCollection.cs +++ b/ProjectLiner/ProjectLiner/FormShipCollection.cs @@ -1,6 +1,6 @@ -using ProjectLiner.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectLiner.CollectionGenericObjects; using ProjectLiner.Drawnings; -using System.Windows.Forms; namespace ProjectLiner; @@ -19,13 +19,19 @@ public partial class FormShipCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormShipCollection() + public FormShipCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -60,14 +66,19 @@ public partial class FormShipCollection : Form { return; } - if (_company + ship != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if ((_company + ship) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект: {entity}", ship.GetDataForSave()); + pictureBox.Image = _company.Show(); + } } - else + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -87,14 +98,17 @@ public partial class FormShipCollection : Form return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + DrawningShip ship = _company - pos; + _logger.LogInformation("Объект по позиции {pos} удаден", pos); MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -168,6 +182,7 @@ public partial class FormShipCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RefreshListBoxItems(); + _logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType); } /// @@ -179,13 +194,14 @@ public partial class FormShipCollection : Form { if (listBoxCollection.SelectedIndex < 0) { - MessageBox.Show("Сначала выберите коллекцию"); + MessageBox.Show("Коллекция не выбрана"); return; } if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } + _logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty); RefreshListBoxItems(); } @@ -224,6 +240,7 @@ public partial class FormShipCollection : Form if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); + _logger.LogInformation("Коллекция не проиннициализирована"); return; } @@ -231,8 +248,10 @@ public partial class FormShipCollection : Form { case "Хранилище": _company = new ShipSharingService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Создана компания типа шипшейринг, коллекция: {CollectionName}", listBoxCollection.SelectedItem); break; } + _logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem); panelCompanyTools.Enabled = true; RefreshListBoxItems(); } @@ -246,13 +265,16 @@ 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -266,15 +288,18 @@ public partial class FormShipCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - RefreshListBoxItems(); + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка {Message}", ex.Message); } + RefreshListBoxItems(); } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Program.cs b/ProjectLiner/ProjectLiner/Program.cs index a294868..42497f0 100644 --- a/ProjectLiner/ProjectLiner/Program.cs +++ b/ProjectLiner/ProjectLiner/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; +using Serilog.Sinks.File; +using Serilog.Configuration; +using Microsoft.Extensions.Configuration; + namespace ProjectLiner { internal static class Program @@ -11,7 +19,26 @@ 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 FormShipCollection()); + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Settings.json").Build(); + services.AddSingleton() + .AddLogging(builder => + { + builder.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/ProjectLiner.csproj b/ProjectLiner/ProjectLiner/ProjectLiner.csproj index 244387d..90f2e47 100644 --- a/ProjectLiner/ProjectLiner/ProjectLiner.csproj +++ b/ProjectLiner/ProjectLiner/ProjectLiner.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True @@ -23,4 +34,13 @@ + + + Always + + + Always + + + \ No newline at end of file diff --git a/ProjectLiner/ProjectLiner/Settings.json b/ProjectLiner/ProjectLiner/Settings.json new file mode 100644 index 0000000..5c034bc --- /dev/null +++ b/ProjectLiner/ProjectLiner/Settings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "shipLog.log", + "outputTemplate": "[{Timestamp:dd.MM.yyyy_HH:mm:ss.fff zzz}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ] + } +} \ No newline at end of file