From 4d7de3bca3b4bd0b47d0e26c12d63f8e93ed8a45 Mon Sep 17 00:00:00 2001 From: KirillFilippow Date: Fri, 22 Dec 2023 13:47:31 +0400 Subject: [PATCH] Laba07 --- .../ContainerGenericCollection.cs | 10 +- .../ContainerShip/ContainerGenericStorage.cs | 40 ++++---- .../ContainerShip/ContainerShip.csproj | 10 ++ .../ContainerShipNotFoundException.cs | 19 ++++ .../ContainerShip/EntityContainerShip.cs | 2 +- .../ContainerShip/FormContainerCollection.cs | 94 +++++++++---------- .../FormContainerShip.Designer.cs | 1 - .../ContainerShip/FormContainerShip.cs | 7 +- ContainerShip/ContainerShip/Program.cs | 30 +++++- ContainerShip/ContainerShip/SetGeneric.cs | 46 +++++++-- .../ContainerShip/StorageOverflowException.cs | 18 ++++ ContainerShip/ContainerShip/appsettings.json | 20 ++++ 12 files changed, 206 insertions(+), 91 deletions(-) create mode 100644 ContainerShip/ContainerShip/ContainerShipNotFoundException.cs create mode 100644 ContainerShip/ContainerShip/StorageOverflowException.cs create mode 100644 ContainerShip/ContainerShip/appsettings.json diff --git a/ContainerShip/ContainerShip/ContainerGenericCollection.cs b/ContainerShip/ContainerShip/ContainerGenericCollection.cs index bf103c3..20c9396 100644 --- a/ContainerShip/ContainerShip/ContainerGenericCollection.cs +++ b/ContainerShip/ContainerShip/ContainerGenericCollection.cs @@ -67,7 +67,7 @@ namespace ProjectContainerShip.Generics { return -1; } - return collect?._collection.Insert(obj); + return collect?._collection.Insert(obj) ?? -1; } /// /// Перегрузка оператора вычитания @@ -75,15 +75,15 @@ namespace ProjectContainerShip.Generics /// /// /// - public static bool operator -(ContainerGenericCollection collect, int + public static T operator -(ContainerGenericCollection collect, int pos) { - T? obj = collect._collection[pos]; + T obj = collect._collection[pos]; if (obj != null) { - return collect._collection.Remove(pos); + collect?._collection.Remove(pos); } - return false; + return obj; } /// /// Получение объекта IMoveableObject diff --git a/ContainerShip/ContainerShip/ContainerGenericStorage.cs b/ContainerShip/ContainerShip/ContainerGenericStorage.cs index a80c909..ab3ab87 100644 --- a/ContainerShip/ContainerShip/ContainerGenericStorage.cs +++ b/ContainerShip/ContainerShip/ContainerGenericStorage.cs @@ -1,4 +1,5 @@ -using ProjectContainerShip.DrawningObjects; +using ContainerShip.Exceptions; +using ProjectContainerShip.DrawningObjects; using ProjectContainerShip.Generics; using ProjectContainerShip.MovementStrategy; using System; @@ -99,15 +100,14 @@ namespace ProjectContainerShip /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); - foreach (KeyValuePair> record in _shipStorages) + foreach (KeyValuePair> record in _shipStorages) { StringBuilder records = new(); foreach (DrawningShip? elem in record.Value.GetShip) @@ -118,13 +118,12 @@ namespace ProjectContainerShip } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } + using (StreamWriter writer = new StreamWriter(filename)) { - writer.WriteLine("shipStorages"); - writer.Write(data.ToString()); - return true; + writer.Write($"shipStorage{Environment.NewLine}{data}"); } } /// @@ -132,22 +131,22 @@ namespace ProjectContainerShip /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) { string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } - if (!cheker.StartsWith("shipStorages")) + if (!cheker.StartsWith("shipStorage")) { - return false; + throw new Exception("Неверный формат ввода"); } _shipStorages.Clear(); string strs; @@ -156,11 +155,11 @@ namespace ProjectContainerShip { if (strs == null && firstinit) { - return false; + throw new Exception("Нет данных для загрузки"); } if (strs == null) { - return false; + break; } firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; @@ -171,16 +170,19 @@ namespace ProjectContainerShip data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight); if (ship != null) { - int? result = collection + ship; - if (result == null || result.Value == -1) + try { _ = collection + ship; } + catch (ContainerShipNotFoundException e) { - return false; + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } _shipStorages.Add(name, collection); } - return true; } } } diff --git a/ContainerShip/ContainerShip/ContainerShip.csproj b/ContainerShip/ContainerShip/ContainerShip.csproj index ce86fc6..09f7210 100644 --- a/ContainerShip/ContainerShip/ContainerShip.csproj +++ b/ContainerShip/ContainerShip/ContainerShip.csproj @@ -27,4 +27,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/ContainerShip/ContainerShip/ContainerShipNotFoundException.cs b/ContainerShip/ContainerShip/ContainerShipNotFoundException.cs new file mode 100644 index 0000000..3755108 --- /dev/null +++ b/ContainerShip/ContainerShip/ContainerShipNotFoundException.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 ContainerShip.Exceptions +{ + [Serializable] internal class ContainerShipNotFoundException : ApplicationException + { + public ContainerShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public ContainerShipNotFoundException() : base() { } + public ContainerShipNotFoundException(string message) : base(message) { } + public ContainerShipNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ContainerShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/ContainerShip/ContainerShip/EntityContainerShip.cs b/ContainerShip/ContainerShip/EntityContainerShip.cs index 08c9c55..3242270 100644 --- a/ContainerShip/ContainerShip/EntityContainerShip.cs +++ b/ContainerShip/ContainerShip/EntityContainerShip.cs @@ -22,7 +22,7 @@ namespace ProjectContainerShip.Entities /// public bool Container { get; private set; } /// - /// Инициализация полей объекта-класса контейнеровоза + /// Инициализация полей объекта-класса контейнеровоз /// /// Скорость /// Вес diff --git a/ContainerShip/ContainerShip/FormContainerCollection.cs b/ContainerShip/ContainerShip/FormContainerCollection.cs index 850768a..5541a6d 100644 --- a/ContainerShip/ContainerShip/FormContainerCollection.cs +++ b/ContainerShip/ContainerShip/FormContainerCollection.cs @@ -2,6 +2,7 @@ using ProjectContainerShip.DrawningObjects; using ProjectContainerShip.Generics; using ProjectContainerShip.MovementStrategy; +using Microsoft.Extensions.Logging; namespace ProjectContainerShip { @@ -15,12 +16,17 @@ namespace ProjectContainerShip /// private readonly ContainerGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormContainerCollection() + public FormContainerCollection(ILogger logger) { InitializeComponent(); _storage = new ContainerGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -42,13 +48,6 @@ namespace ProjectContainerShip index < listBoxStorages.Items.Count) { listBoxStorages.SelectedIndex = index; - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; - if (obj == null) - { - return; - } - pictureBoxCollection.Image = obj.ShowContainer(); } } /// @@ -62,10 +61,12 @@ namespace ProjectContainerShip { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } /// /// Выбор набора @@ -87,14 +88,16 @@ namespace ProjectContainerShip { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, - MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } /// @@ -111,21 +114,23 @@ namespace ProjectContainerShip var form = new FormContainerConfig(); form.AddEvent(ship => { - if (listBoxStorages.SelectedIndex != -1) + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { - var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]; - if (obj != null) - { - if (obj + ship != 1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowContainer(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + ship; + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowContainer(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } }); form.Show(); @@ -139,6 +144,7 @@ namespace ProjectContainerShip { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? @@ -157,10 +163,11 @@ namespace ProjectContainerShip { MessageBox.Show("Объект удален"); pictureBoxCollection.Image = obj.ShowContainer(); + _logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}"); } else { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Не удалось удалить объект"); _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}"); } } /// @@ -191,15 +198,16 @@ namespace ProjectContainerShip { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } @@ -212,27 +220,17 @@ namespace ProjectContainerShip { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); - if (listBoxStorages.SelectedIndex == -1) - { - return; - } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; - if (obj == null) - { - return; - } - pictureBoxCollection.Image = obj.ShowContainer(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось загрузить наборы с ошибкой: {ex.Message}"); } } } diff --git a/ContainerShip/ContainerShip/FormContainerShip.Designer.cs b/ContainerShip/ContainerShip/FormContainerShip.Designer.cs index 238861c..0055b4b 100644 --- a/ContainerShip/ContainerShip/FormContainerShip.Designer.cs +++ b/ContainerShip/ContainerShip/FormContainerShip.Designer.cs @@ -172,7 +172,6 @@ Margin = new Padding(3, 4, 3, 4); Name = "FormContainerShip"; StartPosition = FormStartPosition.CenterScreen; - Load += FormContainerShip_Load; ((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).EndInit(); ResumeLayout(false); PerformLayout(); diff --git a/ContainerShip/ContainerShip/FormContainerShip.cs b/ContainerShip/ContainerShip/FormContainerShip.cs index 06dd873..a5c3984 100644 --- a/ContainerShip/ContainerShip/FormContainerShip.cs +++ b/ContainerShip/ContainerShip/FormContainerShip.cs @@ -13,7 +13,6 @@ namespace ProjectContainerShip /// - /// private DrawningShip? _drawingContainerShip; - /// /// /// @@ -71,12 +70,14 @@ namespace ProjectContainerShip { Random random = new(); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + //TODO ColorDialog dialog = new(); if (dialog.ShowDialog() == DialogResult.OK) { color = dialog.Color; } Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); + //TODO ColorDialog dialog2 = new(); if (dialog2.ShowDialog() == DialogResult.OK) { @@ -161,9 +162,5 @@ namespace ProjectContainerShip SelectedShip = _drawingContainerShip; DialogResult = DialogResult.OK; } - private void FormContainerShip_Load(object sender, EventArgs e) - { - - } } } diff --git a/ContainerShip/ContainerShip/Program.cs b/ContainerShip/ContainerShip/Program.cs index 78ae352..dcf06e9 100644 --- a/ContainerShip/ContainerShip/Program.cs +++ b/ContainerShip/ContainerShip/Program.cs @@ -1,5 +1,10 @@ using ProjectContainerShip; - +using System; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; namespace ProjectContainerShip { internal static class Program @@ -13,7 +18,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 FormContainerCollection()); + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build(); + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } } diff --git a/ContainerShip/ContainerShip/SetGeneric.cs b/ContainerShip/ContainerShip/SetGeneric.cs index bd65293..1ea0619 100644 --- a/ContainerShip/ContainerShip/SetGeneric.cs +++ b/ContainerShip/ContainerShip/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ContainerShip.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -41,16 +42,39 @@ namespace ProjectContainerShip.Generics /// public int Insert(T ship) { - return Insert(ship, 0); + if (_places.Count == 0) + { + _places.Add(ship); + return 0; + } + else + { + if (_places.Count < _maxCount) + { + _places.Add(ship); + for (int i = 0; i < _places.Count; i++) + { + T temp = _places[i]; + _places[i] = _places[_places.Count - 1]; + _places[_places.Count - 1] = temp; + } + return 0; + } + else + { + throw new StorageOverflowException(_places.Count); + } + } } - public int Insert(T ship, int position) + public bool Insert(T ship, int position) { if (position < 0 || position >= _maxCount) - return -1; + throw new ContainerShipNotFoundException(position); + if (Count >= _maxCount) - return -1; - _places.Insert(position, ship); - return position; + throw new StorageOverflowException(position); + _places.Insert(0, ship); + return true; } /// /// Удаление объекта из набора с конкретной позиции @@ -59,11 +83,13 @@ namespace ProjectContainerShip.Generics /// public bool Remove(int position) { - if (position < 0 || position >= _places.Count) + if (position < 0 || position > _maxCount || position >= Count) + throw new ContainerShipNotFoundException(); + if (_places[position] == null) { - return false; + throw new ContainerShipNotFoundException(); } - _places.RemoveAt(position); + _places[position] = null; return true; } /// diff --git a/ContainerShip/ContainerShip/StorageOverflowException.cs b/ContainerShip/ContainerShip/StorageOverflowException.cs new file mode 100644 index 0000000..e75ea86 --- /dev/null +++ b/ContainerShip/ContainerShip/StorageOverflowException.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 ContainerShip.Exceptions +{ + [Serializable] internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } + public StorageOverflowException() : base() { } + public StorageOverflowException(string message) : base(message) { } + public StorageOverflowException(string message, Exception exception) : base(message, exception) { } + protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ContainerShip/ContainerShip/appsettings.json b/ContainerShip/ContainerShip/appsettings.json new file mode 100644 index 0000000..f022b81 --- /dev/null +++ b/ContainerShip/ContainerShip/appsettings.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", "WithShipName", "WithThreadId" ], + "Properties": { + "Application": "ContainerShip" + } + } + } \ No newline at end of file