diff --git a/Project_DumpTruck/Project_DumpTruck/AppSettings.json b/Project_DumpTruck/Project_DumpTruck/AppSettings.json new file mode 100644 index 0000000..474e29f --- /dev/null +++ b/Project_DumpTruck/Project_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": "Project_DumpTruck" + } + } +} diff --git a/Project_DumpTruck/Project_DumpTruck/FormTruckCollection.cs b/Project_DumpTruck/Project_DumpTruck/FormTruckCollection.cs index 4aaa1d7..1ca9542 100644 --- a/Project_DumpTruck/Project_DumpTruck/FormTruckCollection.cs +++ b/Project_DumpTruck/Project_DumpTruck/FormTruckCollection.cs @@ -9,8 +9,11 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Project_DumpTruck.DrawningObjects; +using Project_DumpTruck.Exceptions; using Project_DumpTruck.Generics; using Project_DumpTruck.MovementStrategy; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace Project_DumpTruck @@ -21,12 +24,13 @@ namespace Project_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; } /// @@ -69,14 +73,17 @@ namespace Project_DumpTruck return; } - if (obj + truck != -1) + try { + _ = obj + truck; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowTrucks(); + _logger.LogInformation($"Обьект добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); } - else + catch(StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Обьект не добавлен в набор {listBoxStorages.SelectedItem.ToString()}"); } } @@ -105,16 +112,25 @@ namespace Project_DumpTruck return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowTrucks(); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowTrucks(); + _logger.LogInformation($"Обьект удален из набора {listBoxStorages.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Обьект не удален из набора {listBoxStorages.SelectedItem.ToString()}"); + } } - else + catch(TruckNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Обьект не найден: {ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}"); } - } private void buttonRefreshCollection_Click(object sender, EventArgs e) @@ -138,10 +154,12 @@ namespace Project_DumpTruck { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Добавление набора неуспешно Не все данные заполнены"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } /// @@ -164,14 +182,15 @@ namespace Project_DumpTruck { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning($"Удаление набора неуспешно"); return; } if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); } } @@ -184,15 +203,17 @@ namespace Project_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("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Сохранение в файл {saveFileDialog.FileName} не удалось"); } } } @@ -206,14 +227,17 @@ namespace Project_DumpTruck { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузка из файла {openFileDialog.FileName}"); } - else + catch(Exception ex) { - MessageBox.Show("Не удалось загрузить данные", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не удалось загрузить данные: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} не удалось"); } } } diff --git a/Project_DumpTruck/Project_DumpTruck/Program.cs b/Project_DumpTruck/Project_DumpTruck/Program.cs index 55c26db..261af40 100644 --- a/Project_DumpTruck/Project_DumpTruck/Program.cs +++ b/Project_DumpTruck/Project_DumpTruck/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using System; + namespace Project_DumpTruck { internal static class Program @@ -8,10 +14,30 @@ namespace Project_DumpTruck [STAThread] static void Main() { - // 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/Project_DumpTruck/Project_DumpTruck/Project_DumpTruck.csproj b/Project_DumpTruck/Project_DumpTruck/Project_DumpTruck.csproj index 13ee123..6161484 100644 --- a/Project_DumpTruck/Project_DumpTruck/Project_DumpTruck.csproj +++ b/Project_DumpTruck/Project_DumpTruck/Project_DumpTruck.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True @@ -23,4 +35,10 @@ + + + Always + + + \ No newline at end of file diff --git a/Project_DumpTruck/Project_DumpTruck/SetGeneric.cs b/Project_DumpTruck/Project_DumpTruck/SetGeneric.cs index 80a3a53..df608c7 100644 --- a/Project_DumpTruck/Project_DumpTruck/SetGeneric.cs +++ b/Project_DumpTruck/Project_DumpTruck/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using Project_DumpTruck.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -55,9 +56,12 @@ namespace Project_DumpTruck.Generics // Проверка позиции if (position < 0 || position >= _maxCount) { - return -1; + throw new StorageOverflowException("Невалидная операция"); } // Вставка по позиции + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); + _places.Insert(position, truck); return position; } @@ -69,8 +73,12 @@ namespace Project_DumpTruck.Generics public bool Remove(int position) { // TODO проверка позиции - if ((position < 0) || (position > Count)) return false; + if ((position < 0) || (position > Count)) throw new TruckNotFoundException("Невалидная операция"); // TODO удаление объекта из массива, присвоив элементу массива значение null + if (_places[position] == null) + { + throw new TruckNotFoundException(position); + } _places[position] = null; return true; } diff --git a/Project_DumpTruck/Project_DumpTruck/StorageOverflowException.cs b/Project_DumpTruck/Project_DumpTruck/StorageOverflowException.cs new file mode 100644 index 0000000..dee1ffa --- /dev/null +++ b/Project_DumpTruck/Project_DumpTruck/StorageOverflowException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Project_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/Project_DumpTruck/Project_DumpTruck/TruckNotFoundException.cs b/Project_DumpTruck/Project_DumpTruck/TruckNotFoundException.cs new file mode 100644 index 0000000..3b5ef81 --- /dev/null +++ b/Project_DumpTruck/Project_DumpTruck/TruckNotFoundException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Project_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/Project_DumpTruck/Project_DumpTruck/TrucksGenericStorage.cs b/Project_DumpTruck/Project_DumpTruck/TrucksGenericStorage.cs index 5873b6f..97468ab 100644 --- a/Project_DumpTruck/Project_DumpTruck/TrucksGenericStorage.cs +++ b/Project_DumpTruck/Project_DumpTruck/TrucksGenericStorage.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Project_DumpTruck.DrawningObjects; +using Project_DumpTruck.Exceptions; using Project_DumpTruck.MovementStrategy; namespace Project_DumpTruck.Generics @@ -106,7 +107,7 @@ namespace Project_DumpTruck.Generics } if (data.Length == 0) { - return false; + throw new ArgumentException("Невалиданя операция, нет данных для сохранения"); } using StreamWriter sw = new(filename); sw.Write($"TruckStorage{Environment.NewLine}{data}"); @@ -121,19 +122,18 @@ namespace Project_DumpTruck.Generics { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new ArgumentException("Нет данных для загрузки"); } if (!str.StartsWith("TruckStorage")) { - //если нет такой записи, то это не те данные - return false; + throw new InvalidDataException("Неверный формат данных"); } _truckStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -152,7 +152,18 @@ namespace Project_DumpTruck.Generics { if (collection + truck == -1) { - return false; + try + { + _ = collection + truck; + } + catch (TruckNotFoundException e) + { + throw e; + } + catch (StorageOverflowException e) + { + throw e; + } } } }