From 4b53ad808a046a0fb61e3d4a716ec7110fde17bb Mon Sep 17 00:00:00 2001 From: dex_moth Date: Sun, 10 Dec 2023 11:45:41 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20?= =?UTF-8?q?=D0=B4=D0=B2=D0=B8=D0=B6=D0=B5=D1=82=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Airbus/Exceptions/AirbusNotFoundException.cs | 19 +++++ Airbus/Exceptions/StorageOverflowException.cs | 19 +++++ Airbus/FormAirbusCollection.cs | 82 ++++++++++++------- Airbus/FormPlane.Designer.cs | 4 +- Airbus/FormPlane.cs | 4 +- Airbus/Generics/AirbusGenericCollection.cs | 2 + Airbus/Generics/AirbusGenericStorage.cs | 25 ++++-- Airbus/Generics/SetGeneric.cs | 30 ++++--- Airbus/Program.cs | 30 ++++++- Airbus/ProjectAirbus.csproj | 23 ++++++ Airbus/nlog.config | 11 +++ Airbus/serilog.json | 20 +++++ 12 files changed, 215 insertions(+), 54 deletions(-) create mode 100644 Airbus/Exceptions/AirbusNotFoundException.cs create mode 100644 Airbus/Exceptions/StorageOverflowException.cs create mode 100644 Airbus/nlog.config create mode 100644 Airbus/serilog.json diff --git a/Airbus/Exceptions/AirbusNotFoundException.cs b/Airbus/Exceptions/AirbusNotFoundException.cs new file mode 100644 index 0000000..4f5ca49 --- /dev/null +++ b/Airbus/Exceptions/AirbusNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace ProjectAirbus.Exceptions +{ + [Serializable] + internal class AirbusNotFoundException : ApplicationException + { + public AirbusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AirbusNotFoundException() : base() { } + public AirbusNotFoundException(string message) : base(message) { } + public AirbusNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AirbusNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Airbus/Exceptions/StorageOverflowException.cs b/Airbus/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..9b19a6f --- /dev/null +++ b/Airbus/Exceptions/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace ProjectAirbus.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 context) : base(info, context) { } + } +} diff --git a/Airbus/FormAirbusCollection.cs b/Airbus/FormAirbusCollection.cs index 66bdaaf..6d63d93 100644 --- a/Airbus/FormAirbusCollection.cs +++ b/Airbus/FormAirbusCollection.cs @@ -7,9 +7,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using ProjectAirbus.Generics; using ProjectAirbus.Drawnings; -using ProjectAirbus.MovementStrategy; +using ProjectAirbus.Exceptions; +using System.Xml.Linq; namespace ProjectAirbus { @@ -17,11 +19,14 @@ namespace ProjectAirbus { // Набор объектов private readonly AirbusGenericStorage _storage; + // Логер + private readonly ILogger _logger; - public FormAirbusCollection() + public FormAirbusCollection(ILogger logger) { InitializeComponent(); _storage = new AirbusGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } // Обработка нажатия "Сохранение" @@ -29,13 +34,16 @@ namespace ProjectAirbus { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}"); } - else + catch (InvalidOperationException ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } } } @@ -45,15 +53,16 @@ namespace ProjectAirbus { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - //var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - //pictureBoxCollection.Image = obj.ShowAirbus(); + _storage.LoadData(openFileDialog.FileName); 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); } } ReloadObjects(); @@ -89,6 +98,7 @@ namespace ProjectAirbus } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text}"); } // выбрать набор @@ -104,10 +114,12 @@ namespace ProjectAirbus { return; } + 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); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удалён набор: {name}"); } } @@ -133,14 +145,23 @@ namespace ProjectAirbus } // меняем границы после закрытия конфига _airbus.ChangeBordersPicture(Width, Height); - if (obj + _airbus != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowAirbus(); + if (obj + _airbus != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowAirbus(); + _logger.LogInformation($"Добавлен объект: {_airbus.EntityAirbus.BodyColor}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } @@ -160,24 +181,29 @@ namespace ProjectAirbus { return; } - int pos = 0; try { - pos = Convert.ToInt32(maskedTextBoxNumber.Text); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowAirbus(); + _logger.LogInformation($"Удалён объект по позиции : {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - catch + catch (FormatException ex) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + MessageBox.Show("Неверный формат ввода"); + _logger.LogWarning("Неверный формат ввода"); } - if (obj - pos) + catch (Exception ex) { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowAirbus(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } diff --git a/Airbus/FormPlane.Designer.cs b/Airbus/FormPlane.Designer.cs index 0c30bbb..58b3332 100644 --- a/Airbus/FormPlane.Designer.cs +++ b/Airbus/FormPlane.Designer.cs @@ -1,6 +1,6 @@ namespace ProjectAirbus { - partial class FormPlane + partial class FormAirbus { /// /// Required designer variable. @@ -28,7 +28,7 @@ /// private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPlane)); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAirbus)); pictureAirBus = new PictureBox(); buttonUp = new Button(); buttonLeft = new Button(); diff --git a/Airbus/FormPlane.cs b/Airbus/FormPlane.cs index c236f95..580b594 100644 --- a/Airbus/FormPlane.cs +++ b/Airbus/FormPlane.cs @@ -4,7 +4,7 @@ using ProjectAirbus.Entities; namespace ProjectAirbus { - public partial class FormPlane : Form + public partial class FormAirbus : Form { private DrawningAirbus? _drawningAirbus; private AbstractStrategy? _abstractStrategy; @@ -12,7 +12,7 @@ namespace ProjectAirbus // Выбранный автомобиль public DrawningAirbus? SelectedAirbus { get; private set; } - public FormPlane() + public FormAirbus() { InitializeComponent(); _abstractStrategy = null; diff --git a/Airbus/Generics/AirbusGenericCollection.cs b/Airbus/Generics/AirbusGenericCollection.cs index cd3dc06..f6e41c8 100644 --- a/Airbus/Generics/AirbusGenericCollection.cs +++ b/Airbus/Generics/AirbusGenericCollection.cs @@ -12,6 +12,7 @@ namespace ProjectAirbus.Generics where T : DrawningAirbus where U : IMoveableObject { + public int count => _collection.Count; private readonly int _pictureWidth; private readonly int _pictureHeight; // Размер занимаемого места @@ -29,6 +30,7 @@ namespace ProjectAirbus.Generics _collection = new SetGeneric(width * height); } + public static int operator +(AirbusGenericCollection collect, T? obj) { if (obj != null) diff --git a/Airbus/Generics/AirbusGenericStorage.cs b/Airbus/Generics/AirbusGenericStorage.cs index 13c69fe..657691c 100644 --- a/Airbus/Generics/AirbusGenericStorage.cs +++ b/Airbus/Generics/AirbusGenericStorage.cs @@ -77,7 +77,9 @@ namespace ProjectAirbus.Generics public bool SaveData(string filename) { if (_airbusStorages.Count == 0) - return false; + { + throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); + } if (File.Exists(filename)) { @@ -92,6 +94,10 @@ namespace ProjectAirbus.Generics { StringBuilder records = new(); + if (record.Value.count <= 0) + { + throw new InvalidOperationException("Невалидная операция, нет данных для сохранения"); + } foreach (DrawningAirbus? elem in record.Value.GetAirbus) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); @@ -99,7 +105,6 @@ namespace ProjectAirbus.Generics sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}"); } } - return true; } @@ -108,7 +113,7 @@ namespace ProjectAirbus.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException($"Файл {filename} не найден"); } using (StreamReader sr = File.OpenText(filename)) @@ -118,21 +123,31 @@ namespace ProjectAirbus.Generics // пустая или не те данные if (curLine == null || curLine.Length == 0 || !curLine.StartsWith("AirbusStorage")) { - return false; + throw new ArgumentException("Неверный формат данных"); } // очищаем _airbusStorages.Clear(); // загружаем данные построчно curLine = sr.ReadLine(); + if (curLine == null || curLine.Length == 0) + { + throw new ArgumentException("Нет данных"); + } while (curLine != null) { // загружаем запись + if (!curLine.Contains(_separatorRecords)) + { + throw new ArgumentException("Коллекция пуста"); + } + string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); // загружаем набор AirbusGenericCollection collection = new(_pictureWidth, _pictureHeight); // record[0] - название набора, record[1] - куча объектов + string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) @@ -143,7 +158,7 @@ namespace ProjectAirbus.Generics { if (collection + airbus == -1) { - return false; + throw new InvalidOperationException("Невалидная операция, ошибка добавления в коллекцию"); } } } diff --git a/Airbus/Generics/SetGeneric.cs b/Airbus/Generics/SetGeneric.cs index aca1dce..653a523 100644 --- a/Airbus/Generics/SetGeneric.cs +++ b/Airbus/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectAirbus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -18,32 +19,30 @@ namespace ProjectAirbus.Generics public SetGeneric(int count) { - _maxCount = count; + //_maxCount = count; + _maxCount = 2; _places = new List(count); } // Добавление объекта в начало набора public int Insert(T airbus) { - if (_places.Count >= _maxCount) - { - return -1; - } - - _places.Insert(0, airbus); - return 0; + return Insert(airbus, 0); } // Добавление объекта в набор на конкретную позицию - public bool Insert(T airbus, int position) + public int Insert(T airbus, int position) { - if (Count >= _maxCount || position < 0 || position >= Count) + if (Count >= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (position < 0 || position >= _maxCount) + { + throw new IndexOutOfRangeException("Индекс вне границ коллекции"); } - _places.Insert(position, airbus); - return true; + return 0; } // Удаление объекта из набора с конкретной позиции @@ -51,10 +50,9 @@ namespace ProjectAirbus.Generics { if (position < 0 || position >= Count) { - return false; + throw new AirbusNotFoundException(position); } _places.RemoveAt(position); - return true; } diff --git a/Airbus/Program.cs b/Airbus/Program.cs index 99a94bc..dd186ff 100644 --- a/Airbus/Program.cs +++ b/Airbus/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectAirbus { internal static class Program @@ -11,7 +16,30 @@ namespace ProjectAirbus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormAirbusCollection()); + 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}serilog.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/Airbus/ProjectAirbus.csproj b/Airbus/ProjectAirbus.csproj index 13ee123..3cfa888 100644 --- a/Airbus/ProjectAirbus.csproj +++ b/Airbus/ProjectAirbus.csproj @@ -23,4 +23,27 @@ + + + + + + + + + + + + + + + Always + + + Always + + + + + \ No newline at end of file diff --git a/Airbus/nlog.config b/Airbus/nlog.config new file mode 100644 index 0000000..cccd4e0 --- /dev/null +++ b/Airbus/nlog.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Airbus/serilog.json b/Airbus/serilog.json new file mode 100644 index 0000000..74026dd --- /dev/null +++ b/Airbus/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/carlog.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "ProjectAirbus" + } + } +} \ No newline at end of file -- 2.25.1 From d95866ee896b210a91be28c3fe0433bf4150a64f Mon Sep 17 00:00:00 2001 From: dex_moth Date: Sun, 10 Dec 2023 12:27:15 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Airbus/FormAirbusCollection.Designer.cs | 6 +++--- Airbus/FormAirbusCollection.cs | 2 +- Airbus/FormAirbusCollection.resx | 2 +- Airbus/Generics/AirbusGenericCollection.cs | 6 +++--- Airbus/Generics/SetGeneric.cs | 3 +-- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/Airbus/FormAirbusCollection.Designer.cs b/Airbus/FormAirbusCollection.Designer.cs index c9c92ff..fa03c11 100644 --- a/Airbus/FormAirbusCollection.Designer.cs +++ b/Airbus/FormAirbusCollection.Designer.cs @@ -67,7 +67,7 @@ pictureBoxCollection.Location = new Point(0, 28); pictureBoxCollection.Margin = new Padding(3, 4, 3, 4); pictureBoxCollection.Name = "pictureBoxCollection"; - pictureBoxCollection.Size = new Size(631, 553); + pictureBoxCollection.Size = new Size(630, 556); pictureBoxCollection.TabIndex = 1; pictureBoxCollection.TabStop = false; // @@ -184,14 +184,14 @@ // SaveToolStripMenuItem // SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - SaveToolStripMenuItem.Size = new Size(224, 26); + SaveToolStripMenuItem.Size = new Size(166, 26); SaveToolStripMenuItem.Text = "Сохранить"; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; // // LoadToolStripMenuItem // LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - LoadToolStripMenuItem.Size = new Size(224, 26); + LoadToolStripMenuItem.Size = new Size(166, 26); LoadToolStripMenuItem.Text = "Загрузить"; LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // diff --git a/Airbus/FormAirbusCollection.cs b/Airbus/FormAirbusCollection.cs index 6d63d93..1cd01d6 100644 --- a/Airbus/FormAirbusCollection.cs +++ b/Airbus/FormAirbusCollection.cs @@ -98,7 +98,7 @@ namespace ProjectAirbus } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); - _logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text}"); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } // выбрать набор diff --git a/Airbus/FormAirbusCollection.resx b/Airbus/FormAirbusCollection.resx index 711778a..d9a3bc2 100644 --- a/Airbus/FormAirbusCollection.resx +++ b/Airbus/FormAirbusCollection.resx @@ -130,6 +130,6 @@ 462, 17 - 89 + 25 \ No newline at end of file diff --git a/Airbus/Generics/AirbusGenericCollection.cs b/Airbus/Generics/AirbusGenericCollection.cs index f6e41c8..346b222 100644 --- a/Airbus/Generics/AirbusGenericCollection.cs +++ b/Airbus/Generics/AirbusGenericCollection.cs @@ -15,9 +15,9 @@ namespace ProjectAirbus.Generics public int count => _collection.Count; private readonly int _pictureWidth; private readonly int _pictureHeight; - // Размер занимаемого места - private readonly int _placeSizeWidth = 89; - private readonly int _placeSizeHeight = 34; + // Размер занимаемого места 89х34 + private readonly int _placeSizeWidth = 189; + private readonly int _placeSizeHeight = 134; // коллекция private readonly SetGeneric _collection; diff --git a/Airbus/Generics/SetGeneric.cs b/Airbus/Generics/SetGeneric.cs index 653a523..deeacf5 100644 --- a/Airbus/Generics/SetGeneric.cs +++ b/Airbus/Generics/SetGeneric.cs @@ -19,8 +19,7 @@ namespace ProjectAirbus.Generics public SetGeneric(int count) { - //_maxCount = count; - _maxCount = 2; + _maxCount = count; _places = new List(count); } -- 2.25.1 From 42340ec4b681c348088120f9c68d1312c7c9a8f5 Mon Sep 17 00:00:00 2001 From: dex_moth Date: Fri, 15 Dec 2023 19:19:25 +0400 Subject: [PATCH 3/3] - nlog --- Airbus/ProjectAirbus.csproj | 3 --- Airbus/nlog.config | 11 ----------- 2 files changed, 14 deletions(-) delete mode 100644 Airbus/nlog.config diff --git a/Airbus/ProjectAirbus.csproj b/Airbus/ProjectAirbus.csproj index 3cfa888..ee7064d 100644 --- a/Airbus/ProjectAirbus.csproj +++ b/Airbus/ProjectAirbus.csproj @@ -36,9 +36,6 @@ - - Always - Always diff --git a/Airbus/nlog.config b/Airbus/nlog.config deleted file mode 100644 index cccd4e0..0000000 --- a/Airbus/nlog.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file -- 2.25.1