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..f933bc3 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.Exceptions; 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..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 @@ -93,7 +94,7 @@ namespace RoadTrain.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -112,7 +113,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 +121,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 +150,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 +166,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..41747fb 100644 --- a/RoadTrain/SetGeneric.cs +++ b/RoadTrain/SetGeneric.cs @@ -1,4 +1,5 @@ using System; +using RoadTrain.Exceptions; 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..516ac95 --- /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.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) { } + } +} \ No newline at end of file diff --git a/RoadTrain/TrainNotFoundException.cs b/RoadTrain/TrainNotFoundException.cs new file mode 100644 index 0000000..5ea2298 --- /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.Exceptions +{ + [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