From 0e7878555f57aab8b589f61357170c9770ee42e0 Mon Sep 17 00:00:00 2001 From: sardq Date: Sun, 3 Dec 2023 00:08:41 +0400 Subject: [PATCH] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../HoistingCrane/CraneNotFoundException.cs | 14 ++++ .../HoistingCrane/CranesGenericCollection.cs | 4 - .../HoistingCrane/CranesGenericStorage.cs | 17 ++-- .../HoistingCrane/FormCraneCollection.cs | 83 +++++++++++++------ .../HoistingCrane/HoistingCrane.csproj | 6 ++ HoistingCrane/HoistingCrane/Program.cs | 32 ++++++- HoistingCrane/HoistingCrane/SetGeneric.cs | 18 ++-- .../HoistingCrane/StorageOverflowException.cs | 14 ++++ HoistingCrane/HoistingCrane/appsettings.json | 20 +++++ 9 files changed, 161 insertions(+), 47 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/CraneNotFoundException.cs create mode 100644 HoistingCrane/HoistingCrane/StorageOverflowException.cs create mode 100644 HoistingCrane/HoistingCrane/appsettings.json diff --git a/HoistingCrane/HoistingCrane/CraneNotFoundException.cs b/HoistingCrane/HoistingCrane/CraneNotFoundException.cs new file mode 100644 index 0000000..deaa682 --- /dev/null +++ b/HoistingCrane/HoistingCrane/CraneNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace HoistingCrane.Exceptions +{ + [Serializable] + internal class CraneNotFoundException : ApplicationException + { + public CraneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public CraneNotFoundException() : base() { } + public CraneNotFoundException(string message) : base(message) { } + public CraneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected CraneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/HoistingCrane/HoistingCrane/CranesGenericCollection.cs b/HoistingCrane/HoistingCrane/CranesGenericCollection.cs index 3c325a0..6cbfcb0 100644 --- a/HoistingCrane/HoistingCrane/CranesGenericCollection.cs +++ b/HoistingCrane/HoistingCrane/CranesGenericCollection.cs @@ -41,10 +41,6 @@ namespace HoistingCrane.Generics public static bool operator -(CranesGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj == null) - { - return false; - } return collect?._collection.Remove(pos) ?? false; } /// Получение объекта IMoveableObject diff --git a/HoistingCrane/HoistingCrane/CranesGenericStorage.cs b/HoistingCrane/HoistingCrane/CranesGenericStorage.cs index 17c5742..7f3692a 100644 --- a/HoistingCrane/HoistingCrane/CranesGenericStorage.cs +++ b/HoistingCrane/HoistingCrane/CranesGenericStorage.cs @@ -1,6 +1,7 @@ using HoistingCrane.DrawningObjects; using HoistingCrane.Generics; using HoistingCrane.MovementStrategy; +using System.IO; using System.Text; namespace HoistingCrane @@ -40,7 +41,7 @@ namespace HoistingCrane } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter sw = new StreamWriter(filename)) @@ -55,7 +56,7 @@ namespace HoistingCrane { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) @@ -63,11 +64,11 @@ namespace HoistingCrane string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!cheker.StartsWith("CarStorage")) { - return false; + throw new FormatException("Неверный формат данных"); } _craneStorages.Clear(); string strs; @@ -76,11 +77,7 @@ namespace HoistingCrane { if (strs == null && firstinit) { - return false; - } - if (strs == null) - { - return false; + throw new Exception("Нет данных для загрузки"); } firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; @@ -94,7 +91,7 @@ namespace HoistingCrane int? result = collection + crane; if (result == null || result.Value == -1) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } diff --git a/HoistingCrane/HoistingCrane/FormCraneCollection.cs b/HoistingCrane/HoistingCrane/FormCraneCollection.cs index e9cb413..f21b480 100644 --- a/HoistingCrane/HoistingCrane/FormCraneCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCraneCollection.cs @@ -1,17 +1,22 @@ using HoistingCrane.DrawningObjects; +using HoistingCrane.Exceptions; using HoistingCrane.Generics; using HoistingCrane.MovementStrategy; +using Microsoft.Extensions.Logging; using System.Windows.Forms; +using System.Xml.Linq; namespace HoistingCrane { public partial class FormCraneCollection : Form { private readonly CranesGenericStorage _storage; - public FormCraneCollection() + private readonly ILogger _logger; + public FormCraneCollection(ILogger logger) { InitializeComponent(); _storage = new CranesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -34,15 +39,18 @@ namespace HoistingCrane { 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 (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } } } @@ -50,16 +58,19 @@ namespace HoistingCrane { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadObjects(); + _logger.LogInformation($"Файл загружен {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", + MessageBox.Show($"Не загрузилось {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } } } @@ -73,6 +84,7 @@ namespace HoistingCrane } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { @@ -85,11 +97,13 @@ namespace HoistingCrane { 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); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void ButtonAddCrane_Click(object sender, EventArgs e) @@ -101,22 +115,31 @@ namespace HoistingCrane var formCraneConfig = new FormCraneConfig(); formCraneConfig.AddEvent(crane => { - if (listBoxStorages.SelectedIndex != -1) + try { - var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]; - if (obj != null) + if (listBoxStorages.SelectedIndex != -1) { - if (obj + crane != -1) + var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]; + if (obj != null) { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowCars(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + if (obj + crane != 1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowCars(); + _logger.LogInformation("Объект добавлен"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } } } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); + } }); formCraneConfig.Show(); } @@ -133,20 +156,28 @@ namespace HoistingCrane { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowCars(); + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowCars(); + _logger.LogInformation("Объект удален"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (CraneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.Message); } } diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index b57c89e..f83b5d4 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -8,4 +8,10 @@ enable + + + + + + \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 141ac24..491e3d5 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace HoistingCrane { internal static class Program @@ -11,7 +16,32 @@ namespace HoistingCrane // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormCraneCollection()); + 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/HoistingCrane/HoistingCrane/SetGeneric.cs b/HoistingCrane/HoistingCrane/SetGeneric.cs index c55f728..0472837 100644 --- a/HoistingCrane/HoistingCrane/SetGeneric.cs +++ b/HoistingCrane/HoistingCrane/SetGeneric.cs @@ -1,4 +1,6 @@ -namespace HoistingCrane.Generics +using HoistingCrane.Exceptions; + +namespace HoistingCrane.Generics { /// Параметризованный набор объектов internal class SetGeneric @@ -20,22 +22,26 @@ /// Добавление объекта в набор public int Insert(T crane) { - if(crane==null) - return -1; + if (Count >= _maxCount) + throw new StorageOverflowException(Count); _places.Insert(0, crane); return 0; } public int Insert(T crane, int position) { - if (position < 0 || position >= _maxCount|| Count >= _maxCount) - return -1; + if (position < 0 || position >= _maxCount || Count >= _maxCount) + throw new CraneNotFoundException(position); + if (Count >= _maxCount) + throw new StorageOverflowException(Count); _places.Insert(position, crane); return position; } /// Удаление объекта из набора с конкретной позиции public bool Remove(int position) { - if ((position < 0) || (position > _maxCount)|| (_places[position] == null)) return false; + if (_places[position] == null) + throw new CraneNotFoundException(position); + if ((position < 0) || (position > _maxCount)) return false; _places[position] = null; return true; } diff --git a/HoistingCrane/HoistingCrane/StorageOverflowException.cs b/HoistingCrane/HoistingCrane/StorageOverflowException.cs new file mode 100644 index 0000000..03b1c3f --- /dev/null +++ b/HoistingCrane/HoistingCrane/StorageOverflowException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace HoistingCrane.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/HoistingCrane/HoistingCrane/appsettings.json b/HoistingCrane/HoistingCrane/appsettings.json new file mode 100644 index 0000000..3151e0f --- /dev/null +++ b/HoistingCrane/HoistingCrane/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": "HoistingCrane" + } + } +}