diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs index 8858335..24c77fa 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSelfPropelledArtilleryUnitCollection.cs @@ -3,6 +3,7 @@ using SelfPropelledArtilleryUnit.DrawningObjects; using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Generics; using SelfPropelledArtilleryUnit.MovementStrategy; +using Microsoft.Extensions.Logging; @@ -18,13 +19,18 @@ namespace SelfPropelledArtilleryUnit /// private readonly UstaGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormSelfPropelledArtilleryUnitCollection() + public FormSelfPropelledArtilleryUnitCollection(ILogger logger) { InitializeComponent(); _storage = new UstaGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -59,10 +65,13 @@ namespace SelfPropelledArtilleryUnit { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}"); + } /// /// Выбор набора @@ -84,14 +93,18 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } + string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); + } } /// @@ -110,21 +123,24 @@ namespace SelfPropelledArtilleryUnit formSelfPropelledArtilleryUnitConfig.AddEvent(usta => { - if (listBoxStorage.SelectedIndex != -1) + var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) { - var obj = _storage[listBoxStorage.SelectedItem?.ToString() ?? string.Empty]; - if (obj != null) - { - if (obj + usta != 1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowUsta(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } + _logger.LogWarning("Добавление пустого объекта"); + return; + } + try + { + _ = obj + usta; + + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowUsta(); + _logger.LogInformation($"Добавлен объект в набор {listBoxStorage.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {listBoxStorage.SelectedItem.ToString()}"); } }); @@ -141,6 +157,7 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorage.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? @@ -155,14 +172,24 @@ namespace SelfPropelledArtilleryUnit return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowUsta(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowUsta(); + _logger.LogInformation($"Удален объект из набора {listBoxStorage.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}"); + } } - else + catch (UstaNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {listBoxStorage.SelectedItem.ToString()}"); } } /// @@ -195,15 +222,16 @@ namespace SelfPropelledArtilleryUnit { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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}"); } } } @@ -216,14 +244,17 @@ namespace SelfPropelledArtilleryUnit { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Данные успешно загружены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs index 6bdd353..82731cf 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs @@ -1,19 +1,47 @@ using SelfPropelledArtilleryUnit; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; namespace ProjectUsta { + internal static class Program { - /// - /// The main entry point for the application. - /// [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 FormSelfPropelledArtilleryUnitCollection()); + 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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj index b57c89e..b5cbe31 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj @@ -8,4 +8,14 @@ enable + + + + + + + + + + \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs index 972be12..e7f9ac4 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs @@ -65,8 +65,13 @@ namespace SelfPropelledArtilleryUnit.Generics /// public bool Remove(int position) { - if ((position < 0) || (position > _maxCount)) return false; - _places.RemoveAt(position); + if (position < 0 || position > _maxCount || position >= Count) + throw new UstaNotFoundException(); + if (_places[position] == null) + { + throw new UstaNotFoundException(); + } + _places[position] = null; return true; } /// diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs new file mode 100644 index 0000000..d301e34 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace SelfPropelledArtilleryUnit.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/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs index 4de0d4f..7857c8d 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericCollection.cs @@ -57,14 +57,14 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// /// - public static int? operator +(UstaGenericCollection collect, T? + public static int operator +(UstaGenericCollection collect, T? obj) { if (obj == null) { return -1; } - return collect?._collection.Insert(obj); + return collect?._collection.Insert(obj) ?? -1; } /// /// Перегрузка оператора вычитания @@ -72,15 +72,15 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// /// - public static bool operator -(UstaGenericCollection collect, int + public static T operator -(UstaGenericCollection collect, int pos) { - T? obj = collect._collection[pos]; + T obj = collect._collection[pos]; if (obj != null) { - return collect._collection.Remove(pos); + collect?._collection.Remove(pos); } - return false; + return obj; } /// /// Получение объекта IMoveableObject diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs index 1844c98..ef36e8d 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaGenericStorage.cs @@ -6,6 +6,8 @@ using System.Text; using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.MovementStrategy; using SelfPropelledArtilleryUnit.DrawningObjects; +using SelfPropelledArtilleryUnit.Exceptions; + namespace SelfPropelledArtilleryUnit.Generics { @@ -100,7 +102,7 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -118,15 +120,13 @@ namespace SelfPropelledArtilleryUnit.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.Write($"UstaStorage{Environment.NewLine}{data}"); } - - return true; } /// @@ -134,11 +134,11 @@ namespace SelfPropelledArtilleryUnit.Generics /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) @@ -146,11 +146,11 @@ namespace SelfPropelledArtilleryUnit.Generics string cheker = reader.ReadLine(); if (cheker == null) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!cheker.StartsWith("UstaStorage")) { - return false; + throw new Exception("Неверный формат ввода"); } _ustaStorages.Clear(); string strs; @@ -159,11 +159,11 @@ namespace SelfPropelledArtilleryUnit.Generics { if (strs == null && firstinit) { - return false; + throw new Exception("Нет данных для загрузки"); } if (strs == null) { - return false; + break; } firstinit = false; string name = strs.Split(_separatorForKeyValue)[0]; @@ -174,16 +174,19 @@ namespace SelfPropelledArtilleryUnit.Generics data?.CreateDrawningUsta(_separatorForObject, _pictureWidth, _pictureHeight); if (usta != null) { - int? result = collection + usta; - if (result == null || result.Value == -1) + try { _ = collection + usta; } + catch (UstaNotFoundException e) { - return false; + throw e; + } + catch (StorageOverflowException e) + { + throw e; } } } _ustaStorages.Add(name, collection); } - return true; } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.cs new file mode 100644 index 0000000..6295c73 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/UstaNotFoundException.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 SelfPropelledArtilleryUnit +{ + [Serializable] internal class UstaNotFoundException : ApplicationException + { + public UstaNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public UstaNotFoundException() : base() { } + public UstaNotFoundException(string message) : base(message) { } + public UstaNotFoundException(string message, Exception exception) : base(message, exception) { } + protected UstaNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/appsettings.json b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/appsettings.json new file mode 100644 index 0000000..18b762e --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/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": "GasolineTanker" + } + } + } \ No newline at end of file