From 65cd145a4ef4dcf86a60e5e0d5089169bb00a5d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=9F=D1=83=D1=82?= =?UTF-8?q?=D0=B8=D0=BD=D1=86=D0=B5=D0=B2?= Date: Tue, 5 Dec 2023 19:23:48 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=207=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- RoadTrain/AppSettings.json | 20 +++++++ RoadTrain/FormTrainCollection.cs | 78 ++++++++++++++++--------- RoadTrain/Program.cs | 31 +++++++++- RoadTrain/RoadTrain.csproj | 11 ++++ RoadTrain/RoadTrainGenericCollection.cs | 5 +- RoadTrain/RoadTrainGenericStorage.cs | 29 +++++---- RoadTrain/SetGeneric.cs | 16 +++-- RoadTrain/StorageOverflowException.cs | 21 +++++++ RoadTrain/TrainNotFoundException.cs | 22 +++++++ 9 files changed, 185 insertions(+), 48 deletions(-) create mode 100644 RoadTrain/AppSettings.json create mode 100644 RoadTrain/StorageOverflowException.cs create mode 100644 RoadTrain/TrainNotFoundException.cs diff --git a/RoadTrain/AppSettings.json b/RoadTrain/AppSettings.json new file mode 100644 index 0000000..e7abdba --- /dev/null +++ b/RoadTrain/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": "RoadTrain" + } + } +} \ No newline at end of file diff --git a/RoadTrain/FormTrainCollection.cs b/RoadTrain/FormTrainCollection.cs index 438435c..5f6551f 100644 --- a/RoadTrain/FormTrainCollection.cs +++ b/RoadTrain/FormTrainCollection.cs @@ -1,5 +1,7 @@ -using RoadTrain.DrawningObjects; +using Microsoft.Extensions.Logging; +using RoadTrain.DrawningObjects; using RoadTrain.Generics; +using RoadTrain; using RoadTrain.MovementStrategy; using System; using System.Collections.Generic; @@ -16,11 +18,13 @@ namespace RoadTrain public partial class FormTrainCollection : Form { private readonly RoadTrainGenericStorage _storage; - public FormTrainCollection() + private readonly ILogger _logger; + public FormTrainCollection(ILogger logger) { InitializeComponent(); _storage = new RoadTrainGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -57,14 +61,17 @@ pictureBoxCollection.Height); { return; } - if (obj + train != -1) + try { + _ = obj + train; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowTrains(); + _logger.LogInformation($"Обьект добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Обьект не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); } } private void ButtonAddTrain_Click(object sender, EventArgs e) @@ -92,17 +99,25 @@ pictureBoxCollection.Height); return; } int pos = Convert.ToInt32(InputTextBox.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowTrains(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowTrains(); + _logger.LogInformation($"Обьект удален из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить обьект"); + _logger.LogWarning($"Обьект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch (TrainNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Обьект не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } - - } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -128,26 +143,29 @@ pictureBoxCollection.Height); { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Добавление набора неуспешно Не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } private void ButtonDelObject_Click(object sender, EventArgs e) { 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($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } - } private void ListBoxStorages_SelectedIndexChanged(object sender, EventArgs e) @@ -160,15 +178,16 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTrains() { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранено в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранено: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не удалось"); } } } @@ -177,16 +196,17 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTrains() { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadObjects(); + _logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); - + MessageBox.Show($"Не сохранено: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не удалось"); } } } diff --git a/RoadTrain/Program.cs b/RoadTrain/Program.cs index 8726baa..4546250 100644 --- a/RoadTrain/Program.cs +++ b/RoadTrain/Program.cs @@ -1,3 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using NLog.Extensions.Logging; +using System; + + namespace RoadTrain { internal static class Program @@ -11,7 +19,28 @@ namespace RoadTrain // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTrainCollection()); + 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); + }); } } } \ No newline at end of file diff --git a/RoadTrain/RoadTrain.csproj b/RoadTrain/RoadTrain.csproj index 13ee123..4cbeb71 100644 --- a/RoadTrain/RoadTrain.csproj +++ b/RoadTrain/RoadTrain.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/RoadTrain/RoadTrainGenericCollection.cs b/RoadTrain/RoadTrainGenericCollection.cs index 9914620..17a8626 100644 --- a/RoadTrain/RoadTrainGenericCollection.cs +++ b/RoadTrain/RoadTrainGenericCollection.cs @@ -75,10 +75,7 @@ namespace RoadTrain.Generics pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return obj; } /// diff --git a/RoadTrain/RoadTrainGenericStorage.cs b/RoadTrain/RoadTrainGenericStorage.cs index ec74361..183757b 100644 --- a/RoadTrain/RoadTrainGenericStorage.cs +++ b/RoadTrain/RoadTrainGenericStorage.cs @@ -93,7 +93,7 @@ namespace RoadTrain.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -112,7 +112,7 @@ namespace RoadTrain.Generics } if (data.Length == 0) { - return false; + throw new ArgumentException("Невалидная операция, нет данных для сохранения"); } string dataStr = data.ToString(); using (StreamWriter writer = new StreamWriter(filename)) @@ -120,29 +120,28 @@ namespace RoadTrain.Generics writer.WriteLine("TrainStorage"); writer.WriteLine(dataStr); } - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { 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 ArgumentException("Нет данных для загрузки"); } if (!checker.StartsWith("TrainStorage")) { - return false; + throw new InvalidDataException("Неверный формат данных"); } _trainStorages.Clear(); string strs; @@ -150,7 +149,7 @@ namespace RoadTrain.Generics while ((strs = reader.ReadLine()) != null) { if (strs == null && firstinit) - return false; + throw new ArgumentException("Нет данных для загрузки"); if (strs == null) break; if (strs == String.Empty) @@ -166,14 +165,24 @@ namespace RoadTrain.Generics { if (collection + train == -1) { - return false; + try + { + _ = collection + train; + } + catch (TrainNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } } } } _trainStorages.Add(name, collection); } - return true; } } } diff --git a/RoadTrain/SetGeneric.cs b/RoadTrain/SetGeneric.cs index 4dd6251..4438f8a 100644 --- a/RoadTrain/SetGeneric.cs +++ b/RoadTrain/SetGeneric.cs @@ -1,4 +1,5 @@ using System; +using RoadTrain; using System.Collections.Generic; using System.Linq; using System.Text; @@ -44,10 +45,10 @@ namespace RoadTrain.Generics public int Insert(T train, int position) { if (position < 0 || position >= _maxCount) - return -1; + throw new StorageOverflowException("Невалидная операция"); if (Count >= _maxCount) - return -1; + throw new StorageOverflowException(_maxCount); _places.Insert(position, train); return position; } @@ -58,7 +59,14 @@ namespace RoadTrain.Generics /// public bool Remove(int position) { - if ((position < 0) || (position > _maxCount)) return false; + if (position >= Count || position < 0) + { + throw new TrainNotFoundException("Невалидная операция"); + } + if (_places[position] == null) + { + throw new TrainNotFoundException(position); + } _places[position] = null; return true; } @@ -71,7 +79,7 @@ namespace RoadTrain.Generics { get { - if ((position < 0) || (position > _maxCount)) return null; + if ((position < 0) || (position >= Count)) return null; return _places[position]; } set diff --git a/RoadTrain/StorageOverflowException.cs b/RoadTrain/StorageOverflowException.cs new file mode 100644 index 0000000..abee299 --- /dev/null +++ b/RoadTrain/StorageOverflowException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace RoadTrain +{ + [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) { } + } +} \ No newline at end of file diff --git a/RoadTrain/TrainNotFoundException.cs b/RoadTrain/TrainNotFoundException.cs new file mode 100644 index 0000000..452e15a --- /dev/null +++ b/RoadTrain/TrainNotFoundException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace RoadTrain +{ + [Serializable] + internal class TrainNotFoundException : ApplicationException + { + public TrainNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public TrainNotFoundException() : base() { } + public TrainNotFoundException(string message) : base(message) { } + public TrainNotFoundException(string message, Exception exception) : + base(message, exception) + { } + protected TrainNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } + } +} \ No newline at end of file -- 2.25.1 From bcc99e559f9d4c3863a5598edd12e406b3ac732b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=9F=D1=83=D1=82?= =?UTF-8?q?=D0=B8=D0=BD=D1=86=D0=B5=D0=B2?= Date: Tue, 5 Dec 2023 20:02:05 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- RoadTrain/FormTrainCollection.cs | 2 +- RoadTrain/RoadTrainGenericStorage.cs | 1 + RoadTrain/SetGeneric.cs | 2 +- RoadTrain/StorageOverflowException.cs | 2 +- RoadTrain/TrainNotFoundException.cs | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/RoadTrain/FormTrainCollection.cs b/RoadTrain/FormTrainCollection.cs index 5f6551f..f933bc3 100644 --- a/RoadTrain/FormTrainCollection.cs +++ b/RoadTrain/FormTrainCollection.cs @@ -1,7 +1,7 @@ using Microsoft.Extensions.Logging; using RoadTrain.DrawningObjects; using RoadTrain.Generics; -using RoadTrain; +using RoadTrain.Exceptions; using RoadTrain.MovementStrategy; using System; using System.Collections.Generic; diff --git a/RoadTrain/RoadTrainGenericStorage.cs b/RoadTrain/RoadTrainGenericStorage.cs index 183757b..628b4ed 100644 --- a/RoadTrain/RoadTrainGenericStorage.cs +++ b/RoadTrain/RoadTrainGenericStorage.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using RoadTrain.DrawningObjects; using RoadTrain.MovementStrategy; +using RoadTrain.Exceptions; namespace RoadTrain.Generics diff --git a/RoadTrain/SetGeneric.cs b/RoadTrain/SetGeneric.cs index 4438f8a..41747fb 100644 --- a/RoadTrain/SetGeneric.cs +++ b/RoadTrain/SetGeneric.cs @@ -1,5 +1,5 @@ using System; -using RoadTrain; +using RoadTrain.Exceptions; using System.Collections.Generic; using System.Linq; using System.Text; diff --git a/RoadTrain/StorageOverflowException.cs b/RoadTrain/StorageOverflowException.cs index abee299..516ac95 100644 --- a/RoadTrain/StorageOverflowException.cs +++ b/RoadTrain/StorageOverflowException.cs @@ -5,7 +5,7 @@ using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -namespace RoadTrain +namespace RoadTrain.Exceptions { [Serializable] internal class StorageOverflowException : ApplicationException diff --git a/RoadTrain/TrainNotFoundException.cs b/RoadTrain/TrainNotFoundException.cs index 452e15a..5ea2298 100644 --- a/RoadTrain/TrainNotFoundException.cs +++ b/RoadTrain/TrainNotFoundException.cs @@ -5,7 +5,7 @@ using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -namespace RoadTrain +namespace RoadTrain.Exceptions { [Serializable] internal class TrainNotFoundException : ApplicationException -- 2.25.1