diff --git a/DumpTruck/DumpTruck.csproj b/DumpTruck/DumpTruck.csproj index 13ee123..9f00cf6 100644 --- a/DumpTruck/DumpTruck.csproj +++ b/DumpTruck/DumpTruck.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/DumpTruck/Exceptions/StorageOverflowException.cs b/DumpTruck/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..dd9bc69 --- /dev/null +++ b/DumpTruck/Exceptions/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 DumpTruck.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/DumpTruck/Exceptions/TruckNotFoundException.cs b/DumpTruck/Exceptions/TruckNotFoundException.cs new file mode 100644 index 0000000..c71851d --- /dev/null +++ b/DumpTruck/Exceptions/TruckNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace DumpTruck.Exceptions +{ + [Serializable] + internal class TruckNotFoundException : ApplicationException + { + public TruckNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public TruckNotFoundException() : base() { } + public TruckNotFoundException(string message) : base(message) { } + public TruckNotFoundException(string message, Exception exception) : base(message, exception) { } + protected TruckNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/DumpTruck/FormTruckCollection.cs b/DumpTruck/FormTruckCollection.cs index b5a1d22..88158a7 100644 --- a/DumpTruck/FormTruckCollection.cs +++ b/DumpTruck/FormTruckCollection.cs @@ -10,6 +10,8 @@ using System.Windows.Forms; using DumpTruck.Generics; using DumpTruck.DrawingObjects; using DumpTruck.MovementStrategy; +using DumpTruck.Exceptions; +using Microsoft.Extensions.Logging; namespace DumpTruck { @@ -23,13 +25,19 @@ namespace DumpTruck /// private readonly TrucksGenericStorage _storage; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormTruckCollection() + public FormTruckCollection(ILogger logger) { InitializeComponent(); _storage = new TrucksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() @@ -66,6 +74,7 @@ namespace DumpTruck } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// /// Выбор набора @@ -87,10 +96,13 @@ namespace DumpTruck { 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}"); } } @@ -105,16 +117,26 @@ namespace DumpTruck var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Не удалось добавить объект: набор пуст"); return; } - if (obj + truck != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowTrucks(); + if (obj + truck != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowTrucks(); + _logger.LogInformation($"Объект добавлен {truck}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (ApplicationException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } } @@ -122,6 +144,7 @@ namespace DumpTruck { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Не удалось добавить объект: не выбран набор"); return; } var formTruckConfig = new FormTruckConfig(); @@ -133,11 +156,13 @@ namespace DumpTruck { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Не удалось удалить объект: не выбран набор"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Не удалось удалить объект: набор пуст"); return; } if (MessageBox.Show("Удалить объект?", "Удаление", @@ -146,18 +171,27 @@ namespace DumpTruck return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowTrucks(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } - } + try + { + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowTrucks(); + _logger.LogInformation($"Удален объект на позиции: {pos}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } + } + catch (TruckNotFoundException ex) + { + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось удалить объект: {ex.Message}"); + } + } - private void buttonRefreshCollection_Click(object sender, EventArgs e) + private void buttonRefreshCollection_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) { @@ -179,14 +213,16 @@ namespace DumpTruck { 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("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -200,16 +236,19 @@ namespace DumpTruck { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Result", 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}"); } } } diff --git a/DumpTruck/Generics/SetGeneric.cs b/DumpTruck/Generics/SetGeneric.cs index d8fa3af..9e828c5 100644 --- a/DumpTruck/Generics/SetGeneric.cs +++ b/DumpTruck/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using DumpTruck.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -51,7 +52,10 @@ namespace DumpTruck.Generics /// public int Insert(T truck, int position) { - if (position < 0 || position > Count || Count >= _maxCount) return -1; + if (position < 0 || position > Count) + throw new TruckNotFoundException(position); + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); _places.Insert(position, truck); return position; } @@ -62,7 +66,7 @@ namespace DumpTruck.Generics /// public bool Remove(int position) { - if (position < 0 || position >= Count) return false; + if (position < 0 || position >= Count) throw new TruckNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/DumpTruck/Generics/TrucksGenericCollection.cs b/DumpTruck/Generics/TrucksGenericCollection.cs index c2b7d77..dd49384 100644 --- a/DumpTruck/Generics/TrucksGenericCollection.cs +++ b/DumpTruck/Generics/TrucksGenericCollection.cs @@ -74,15 +74,11 @@ namespace DumpTruck.Generics /// /// /// - public static T? operator -(TrucksGenericCollection collect, int pos) + public static bool operator -(TrucksGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } - return obj; - } + return collect._collection.Remove(pos); + } /// /// Получение объекта IMoveableObject /// diff --git a/DumpTruck/Generics/TrucksGenericStorage.cs b/DumpTruck/Generics/TrucksGenericStorage.cs index e299c2c..e514e76 100644 --- a/DumpTruck/Generics/TrucksGenericStorage.cs +++ b/DumpTruck/Generics/TrucksGenericStorage.cs @@ -87,7 +87,7 @@ namespace DumpTruck.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -105,33 +105,32 @@ namespace DumpTruck.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using StreamWriter sw = new(filename); sw.Write($"TruckStorage{Environment.NewLine}{data}"); - return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!str.StartsWith("TruckStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _truckStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -143,21 +142,20 @@ namespace DumpTruck.Generics } TrucksGenericCollection < DrawingTruck, DrawningObjectTruck > collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) + foreach (string elem in set.Reverse()) { DrawingTruck? truck = elem?.CreateDrawingTruck(_separatorForObject, _pictureWidth, _pictureHeight); if (truck != null) { if (collection + truck == -1) { - return false; - } + throw new Exception("Ошибка добавления в коллекцию"); + } } } _truckStorages.Add(record[0], collection); } } - return true; } } } diff --git a/DumpTruck/Program.cs b/DumpTruck/Program.cs index 7cab292..dd0836b 100644 --- a/DumpTruck/Program.cs +++ b/DumpTruck/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace DumpTruck { internal static class Program @@ -11,7 +16,28 @@ namespace DumpTruck // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormTruckCollection()); - } - } + 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/DumpTruck/appsettings.json b/DumpTruck/appsettings.json new file mode 100644 index 0000000..bce76f7 --- /dev/null +++ b/DumpTruck/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": "DumpTruck" + } + } +} \ No newline at end of file