From 6f6529c9fecb980b45c98a9811d3917242bb8d20 Mon Sep 17 00:00:00 2001 From: Victoria_Isaeva Date: Thu, 2 May 2024 12:16:38 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9F=D1=80=D0=B5=D0=B4=D0=B2=D0=B0=D1=80?= =?UTF-8?q?=D0=B8=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 14 +- .../AerodromService.cs | 32 ++-- .../ProjectAirbus/FormBusCollection.cs | 139 ++++++++---------- ProjectAirbus/ProjectAirbus/Program.cs | 53 ++++--- .../ProjectAirbus/ProjectAirbus.csproj | 4 +- ProjectAirbus/ProjectAirbus/nlog.config | 15 -- .../ProjectAirbus/serilogConfig.json | 20 +++ 7 files changed, 142 insertions(+), 135 deletions(-) delete mode 100644 ProjectAirbus/ProjectAirbus/nlog.config create mode 100644 ProjectAirbus/ProjectAirbus/serilogConfig.json diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs index 390debd..2d2deee 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectAirbus.Drawnings; +using ProjectAirbus.Exceptions; namespace ProjectAirbus.CollectionGenericObjects; @@ -35,7 +36,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -96,8 +97,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningBus? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningBus? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } return bitmap; diff --git a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs index 6f6b55d..78f9491 100644 --- a/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs +++ b/ProjectAirbus/ProjectAirbus/CollectionGenericObjects/AerodromService.cs @@ -1,6 +1,7 @@ using ProjectAirbus.CollectionGenericObjects; using ProjectAirbus.Drawnings; using ProjectAirbus.CollectionGenericObjects; +using ProjectAirbus.Exceptions; namespace ProjectAirbus.CollectionGenericObjects; @@ -23,27 +24,17 @@ public class AerodromService : AbstractCompany protected override void DrawBackgound(Graphics g) { - Pen pen = new Pen(Color.LightBlue, 3); - int offsetX = 10; - int offsetY = -12; - int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; - numRows = 0; - while (y >= 0) + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; + Pen pen = new(Color.Black, 2); + for (int i = 0; i < width + 1; i++) { - int numCols = 0; - while (x + _placeSizeWidth <= _pictureWidth) + for (int j = 0; j < height + 1; ++j) { - numCols++; - g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y); - g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8); - locCoord.Add(new Tuple(x, y)); - x += _placeSizeWidth + 2; + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight); + g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight); } - numRows++; - x = 1 + offsetX; - y -= _placeSizeHeight + 5 + offsetY; } - } protected override void SetObjectsPosition() @@ -56,12 +47,13 @@ public class AerodromService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 35); + _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 20); } - + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (curWidth > 0) curWidth--; else diff --git a/ProjectAirbus/ProjectAirbus/FormBusCollection.cs b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs index 575fbb6..53e3b55 100644 --- a/ProjectAirbus/ProjectAirbus/FormBusCollection.cs +++ b/ProjectAirbus/ProjectAirbus/FormBusCollection.cs @@ -43,27 +43,25 @@ public partial class FormBusCollection : Form private void SetBus(DrawningBus? bus) { + if (_company == null || bus == null) + { + return; + } try { - if (_company == null || bus == null) - { - return; - } - if (_company + bus != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox1.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + bus.GetDataForSave()); - } + var res = _company + bus; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBox1.Image = _company.Show(); } - catch (ObjectNotFoundException) { } - catch (CollectionOverflowException ex) + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } - + /// /// Удаление объекта /// @@ -76,7 +74,8 @@ public partial class FormBusCollection : Form return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } @@ -84,17 +83,16 @@ public partial class FormBusCollection : Form int pos = Convert.ToInt32(maskedTextBox.Text); try { - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox1.Image = _company.Show(); - _logger.LogInformation("Удален объект по позиции" + pos); - } + var res = _company - pos; + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); + pictureBox1.Image = _company.Show(); } catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -109,29 +107,27 @@ public partial class FormBusCollection : Form { return; } + DrawningBus? bus = null; int counter = 100; - try + while (bus == null) { - while (bus == null) + bus = _company.GetRandomObject(); + counter--; + if (counter <= 0) { - bus = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } + break; } - FormAirbus form = new() - { - SetBus = bus - }; - form.ShowDialog(); } - catch (Exception ex) + if (bus == null) { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } + FormAirbus form = new() + { + SetBus = bus + }; + form.ShowDialog(); } /// @@ -156,31 +152,35 @@ public partial class FormBusCollection : Form /// private void buttonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); - _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } catch (Exception ex) { - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } + } /// /// Удаление коллекции @@ -189,30 +189,21 @@ public partial class FormBusCollection : Form /// private void buttonCollectionDel_Click(object sender, EventArgs e) { - // TODO прописать логику удаления элемента из коллекции - // нужно убедиться, что есть выбранная коллекция - // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись - // удалить и обновить ListBox if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - try + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); - } - catch (Exception ex) - { - _logger.LogError("Ошибка: {Message}", ex.Message); + return; } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } /// @@ -246,7 +237,8 @@ public partial class FormBusCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -257,6 +249,7 @@ public partial class FormBusCollection : Form { case "Хранилище": _company = new AerodromService(pictureBox1.Width, pictureBox1.Height, collection); + _logger.LogInformation("Компания создана"); break; } @@ -274,12 +267,11 @@ public partial class FormBusCollection : Form MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } - } } @@ -290,16 +282,15 @@ public partial class FormBusCollection : Form try { _storageCollection.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } - } } diff --git a/ProjectAirbus/ProjectAirbus/Program.cs b/ProjectAirbus/ProjectAirbus/Program.cs index ad75e93..d642473 100644 --- a/ProjectAirbus/ProjectAirbus/Program.cs +++ b/ProjectAirbus/ProjectAirbus/Program.cs @@ -1,35 +1,44 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using Serilog; -namespace ProjectAirbus +namespace ProjectAirbus; + +internal static class Program { - internal static class Program + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - ServiceCollection services = new(); - ConfigureServices(services); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); Application.Run(serviceProvider.GetRequiredService()); - } - private static void ConfigureServices(ServiceCollection services) + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => { - services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - } + 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}serilogConfig.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/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj index 42bc7dd..4c8629a 100644 --- a/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj +++ b/ProjectAirbus/ProjectAirbus/ProjectAirbus.csproj @@ -13,6 +13,8 @@ + + @@ -31,7 +33,7 @@ - + Always diff --git a/ProjectAirbus/ProjectAirbus/nlog.config b/ProjectAirbus/ProjectAirbus/nlog.config deleted file mode 100644 index fc13552..0000000 --- a/ProjectAirbus/ProjectAirbus/nlog.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProjectAirbus/ProjectAirbus/serilogConfig.json b/ProjectAirbus/ProjectAirbus/serilogConfig.json new file mode 100644 index 0000000..ffdff69 --- /dev/null +++ b/ProjectAirbus/ProjectAirbus/serilogConfig.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": "Airbus" + } + } +} \ No newline at end of file