diff --git a/Cruiser/Cruiser.csproj b/Cruiser/Cruiser.csproj index 13ee123..22da6bf 100644 --- a/Cruiser/Cruiser.csproj +++ b/Cruiser/Cruiser.csproj @@ -23,4 +23,16 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Cruiser/Exceptions/CruiserNotFoundException.cs b/Cruiser/Exceptions/CruiserNotFoundException.cs new file mode 100644 index 0000000..28689ab --- /dev/null +++ b/Cruiser/Exceptions/CruiserNotFoundException.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 +{ + internal class CruiserNotFoundException : ApplicationException + { + public CruiserNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public CruiserNotFoundException() : base() { } + public CruiserNotFoundException(string message) : base(message) { } + public CruiserNotFoundException(string message, Exception exception) : base(message, exception) { } + protected CruiserNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } + +} \ No newline at end of file diff --git a/Cruiser/Exceptions/StorageOverflowException.cs b/Cruiser/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..d00fabd --- /dev/null +++ b/Cruiser/Exceptions/StorageOverflowException.cs @@ -0,0 +1,20 @@ +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 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/Cruiser/FormCruiserCollection.Designer.cs b/Cruiser/FormCruiserCollection.Designer.cs index 79ce8b8..1fd64c8 100644 --- a/Cruiser/FormCruiserCollection.Designer.cs +++ b/Cruiser/FormCruiserCollection.Designer.cs @@ -177,14 +177,14 @@ // SaveToolStripMenuItem // SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - SaveToolStripMenuItem.Size = new Size(180, 22); + SaveToolStripMenuItem.Size = new Size(133, 22); SaveToolStripMenuItem.Text = "Сохранить"; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // // UploadToolStripMenuItem // UploadToolStripMenuItem.Name = "UploadToolStripMenuItem"; - UploadToolStripMenuItem.Size = new Size(180, 22); + UploadToolStripMenuItem.Size = new Size(133, 22); UploadToolStripMenuItem.Text = "Загрузить"; UploadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // diff --git a/Cruiser/FormCruiserCollection.cs b/Cruiser/FormCruiserCollection.cs index eafc0b1..e4c63b6 100644 --- a/Cruiser/FormCruiserCollection.cs +++ b/Cruiser/FormCruiserCollection.cs @@ -11,6 +11,9 @@ using System.Windows.Forms; using Cruiser.Drawing; using Cruiser.Generics; using Cruiser.MovementStrategy; +using Cruiser.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace Cruiser { @@ -24,12 +27,17 @@ namespace Cruiser /// private readonly CruisersGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormCruiserCollection() + public FormCruiserCollection(ILogger logger) { InitializeComponent(); _storage = new CruisersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -65,6 +73,7 @@ namespace Cruiser } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } /// /// Удаление набора @@ -79,8 +88,10 @@ namespace Cruiser } if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; //добавил для удаления повторяющегося кода + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -105,21 +116,31 @@ namespace Cruiser { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Добавление круизера не удалось (индекс вне границ)"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Добавление круизера не удалось (нет хранилища)"); return; } - if ((obj + cruiser)) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowCruiser(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + if ((obj + cruiser)) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Добавление круизера успешно {listBoxStorages.SelectedItem.ToString()}"); + pictureBoxCollection.Image = obj.ShowCruiser(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } + } + catch (ApplicationException ex) + { + MessageBox.Show(ex.Message); } } /// @@ -131,28 +152,42 @@ namespace Cruiser { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Удаление круизера не удалось (индекс вне границ)"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Удаление круизера не удалось (нет хранилища)"); return; } if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { + _logger.LogWarning($"Удаление круизера не удалось (выбран вариант 'Нет')"); return; } int pos = Convert.ToInt32(textBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowCruiser(); - } - else + if (obj - pos != null) + { + _logger.LogInformation($"Удаление круизера успешно {listBoxStorages.SelectedItem.ToString()} {pos}"); + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowCruiser(); + } + else + { + _logger.LogWarning($"Удаление круизера не удалось(обьект не найден)"); + MessageBox.Show("Не удалось удалить объект"); + } + } + catch (CruiserNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Удаление круизера не удалось {ex.Message}"); + MessageBox.Show(ex.Message); } + } /// /// Обновление рисунка по набору diff --git a/Cruiser/Generics/CruisersGenericCollection.cs b/Cruiser/Generics/CruisersGenericCollection.cs index a527800..4d059e4 100644 --- a/Cruiser/Generics/CruisersGenericCollection.cs +++ b/Cruiser/Generics/CruisersGenericCollection.cs @@ -128,20 +128,16 @@ namespace Cruiser.Generics { int Ix = 0; int Iy = 0; - int i = 0; foreach (var cruiser in _collection.GetCruisers()) { - cruiser._pictureHeight = _pictureHeight;// добавил для починки отрисовки на форме коллекций - cruiser._pictureWidth = _pictureWidth;// добавил для починки отрисовки на форме коллекций - _collection[i]?.SetPosition(Ix, Iy); - _collection[i]?.DrawTransport(g); + cruiser?.SetPosition(Ix, Iy); // починил, для починки удаления + cruiser?.DrawTransport(g); Ix += _placeSizeWidth; if (Ix + _placeSizeHeight > _pictureWidth) { Ix = 0; - Iy = _placeSizeHeight; + Iy += _placeSizeHeight; // починил, т.к. отрисовывалось максимум 8 кораблей } - i++; } } } diff --git a/Cruiser/Generics/CruisersGenericStorage.cs b/Cruiser/Generics/CruisersGenericStorage.cs index 5541640..1191391 100644 --- a/Cruiser/Generics/CruisersGenericStorage.cs +++ b/Cruiser/Generics/CruisersGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Cruiser.Drawing; using Cruiser.MovementStrategy; +using System.IO; namespace Cruiser.Generics { @@ -105,7 +106,7 @@ namespace Cruiser.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } string dataStr = data.ToString(); using (StreamWriter writer = new StreamWriter(filename)) @@ -124,18 +125,18 @@ namespace Cruiser.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) { string checker = reader.ReadLine(); if (checker == null) { - return false; + throw new NullReferenceException("Нет данных для загрузки"); } if (!checker.StartsWith("CruiserStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _cruiserStorages.Clear(); string strs; @@ -156,9 +157,13 @@ namespace Cruiser.Generics DrawingCruiser? cruiser = data?.CreateDrawingCruiser(_separatorForObject, _pictureWidth, _pictureHeight); if (cruiser != null) { - if (collection + cruiser == false) + try { - return false; + bool? tmp = collection + cruiser; + } + catch (ApplicationException ex) + { + throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}"); } } diff --git a/Cruiser/Generics/SetGeneric.cs b/Cruiser/Generics/SetGeneric.cs index 39d2da4..daa55fc 100644 --- a/Cruiser/Generics/SetGeneric.cs +++ b/Cruiser/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using Cruiser.Exceptions; +using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; @@ -40,12 +41,13 @@ namespace Cruiser.Generics /// /// Добавляемый лайнер /// - public bool Insert(T cruiser) + public bool Insert(T cruiser) //починил код, работал неправильно { - if (_places.Count + 1 <= _maxCount) + if (_places.Count >= _maxCount) { - _places.Insert(0, cruiser); + throw new StorageOverflowException(_places.Count); } + _places.Insert(0, cruiser); return true; } /// @@ -57,7 +59,7 @@ namespace Cruiser.Generics { if (position < 0 || position > _places.Count) { - return false; + throw new CruiserNotFoundException(position); } _places[position] = null; return true; @@ -68,14 +70,18 @@ namespace Cruiser.Generics /// Добавляемый автомобиль /// Позиция /// - public bool Insert(T cruiser, int position) + public bool Insert(T cruiser, int position) //починил код, работал неправильно { - if (_places.Count + 1 <= _maxCount && _places.Count >= position) + if (_places.Count >= _maxCount) { - _places.Insert(position, cruiser); - return true; + throw new StorageOverflowException(_places.Count); } - return false; + if (position < 0 || position > _places.Count) + { + throw new CruiserNotFoundException(position); + } + _places.Insert(position, cruiser); + return true; } public T? this[int position] { diff --git a/Cruiser/Program.cs b/Cruiser/Program.cs index 2672862..bf7bb81 100644 --- a/Cruiser/Program.cs +++ b/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 @@ -10,8 +15,32 @@ 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 FormCruiserCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + 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); + }); + } } } } \ No newline at end of file diff --git a/Cruiser/appsettings.json b/Cruiser/appsettings.json new file mode 100644 index 0000000..283f56e --- /dev/null +++ b/Cruiser/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", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Cruiser" + } + } +} \ No newline at end of file