diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/AddToCollectionException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/AddToCollectionException.cs new file mode 100644 index 0000000..ad5a2cc --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/AddToCollectionException.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 AddToCollectionException : ApplicationException + { + public AddToCollectionException() : base() { } + public AddToCollectionException(string message) : base(message) { } + public AddToCollectionException(string message, Exception exception) : base(message, exception) { } + protected AddToCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Extention.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Extention.cs deleted file mode 100644 index 148030c..0000000 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Extention.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace SelfPropelledArtilleryUnit -{ - internal class Extention - { - } -} diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSPAUCollection.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSPAUCollection.cs index c983750..3253b6f 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSPAUCollection.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/FormSPAUCollection.cs @@ -7,10 +7,14 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; using SelfPropelledArtilleryUnit.DrawningObjects; using SelfPropelledArtilleryUnit.MovementStrategy; using SelfPropelledArtilleryUnit.Generics; using static System.Windows.Forms.VisualStyles.VisualStyleElement; +using Serilog; +using System.Xml.Linq; +using ILogger = Serilog.ILogger; namespace SelfPropelledArtilleryUnit { @@ -19,18 +23,23 @@ namespace SelfPropelledArtilleryUnit /// public partial class FormSPAUCollection : Form { - readonly int countPlaces = 11; + readonly int countPlaces = 12; /// /// Набор объектов /// private readonly SPAUGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormSPAUCollection() + public FormSPAUCollection(ILogger logger) { InitializeComponent(); _storage = new SPAUGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение listBoxObjects @@ -64,10 +73,12 @@ namespace SelfPropelledArtilleryUnit if (string.IsNullOrEmpty(textBoxStorageName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Попытка добавить набор с пустым именем"); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}"); } /// @@ -90,12 +101,15 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } /// @@ -108,6 +122,7 @@ namespace SelfPropelledArtilleryUnit if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; @@ -125,6 +140,7 @@ namespace SelfPropelledArtilleryUnit { if (listBoxStorages.SelectedIndex == -1) { + _logger.LogWarning("Коллекция не выбрана"); return; } var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; @@ -133,16 +149,27 @@ namespace SelfPropelledArtilleryUnit return; } - int addedIndex = obj + sPAU; - if (addedIndex != -1 && addedIndex <= countPlaces) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowSPAUs(); + int addedIndex = obj + sPAU; + if (addedIndex != -1 && addedIndex <= countPlaces) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowSPAUs(); + _logger.LogInformation("Объект добавлен"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Неудачная попытка добавления"); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"Неудачная попытка добавления: {ex}"); } + } @@ -173,19 +200,31 @@ namespace SelfPropelledArtilleryUnit pos = Convert.ToInt32(maskedTextBoxNumber.Text); } - catch + catch(Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Неудачная попытка удаления: {ex}"); return; } - if (obj - pos) + + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowSPAUs(); + if (obj - pos) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowSPAUs(); + _logger.LogInformation("Объект удален"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Неудачная попытка удаления c позиции {pos}"); + } } - else + catch(SPAUNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Неудачная попытка удаления: {ex}"); } } /// @@ -216,15 +255,17 @@ 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("Успешное сохранение"); } - else + catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не сохранилось: {ex.Message}"); } } } @@ -240,12 +281,13 @@ namespace SelfPropelledArtilleryUnit if (_storage.LoadData(openFileDialog_.FileName)) { MessageBox.Show("Загрузка прошлa успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Успешная загрузка"); ReloadObjects(); } else { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Неудачная попытка загрузки"); } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs index 92aa644..2eba41a 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; +using System.Drawing; +using ILogger = Serilog.ILogger; namespace SelfPropelledArtilleryUnit { internal static class Program @@ -9,8 +15,27 @@ namespace SelfPropelledArtilleryUnit static void Main() { ApplicationConfiguration.Initialize(); - Application.Run(new FormSPAUCollection()); - //Application.Run(new FormSPAU()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + + Application.Run(serviceProvider.GetRequiredService()); + } } + private static void ConfigureServices(ServiceCollection services) + { + string currentTime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); + string logFileName = $"logs/spaulog-{currentTime}.txt"; + services.AddSingleton().AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .MinimumLevel.Information() + .WriteTo.File(logFileName) + .CreateLogger()); + }); + } + } } \ No newline at end of file diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ReadFileExeption.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ReadFileExeption.cs new file mode 100644 index 0000000..2a7e8f5 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/ReadFileExeption.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 ReadFileExeption : ApplicationException + { + public ReadFileExeption() : base() { } + public ReadFileExeption(string message) : base(message) { } + public ReadFileExeption(string message, Exception exception) : base(message, exception) { } + protected ReadFileExeption(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUGenericStorage.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUGenericStorage.cs index fb2ea2a..f93289d 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUGenericStorage.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUGenericStorage.cs @@ -116,7 +116,7 @@ namespace SelfPropelledArtilleryUnit.Generics } if (data.Length == 0) { - return false; + throw new ReadFileExeption("Невалиданя операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { @@ -142,11 +142,12 @@ namespace SelfPropelledArtilleryUnit.Generics string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new ReadFileExeption("Нет данных для загрузки"); } if (!str.StartsWith("SPAUStorage")) { - return false; + //если нет такой записи, то это не те данные + throw new ReadFileExeption("Неверный формат данных"); } _SPAUStorages.Clear(); @@ -156,7 +157,7 @@ namespace SelfPropelledArtilleryUnit.Generics { if (strs == null) { - return false; + throw new AddToCollectionException("Ошибка добавления в коллекцию"); } string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); @@ -173,7 +174,7 @@ namespace SelfPropelledArtilleryUnit.Generics { if ((collection + sPAU) == -1) { - return false; + throw new AddToCollectionException("Ошибка добавления в коллекцию"); } } } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUNotFoundException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUNotFoundException.cs new file mode 100644 index 0000000..6eb5785 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SPAUNotFoundException.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 SPAUNotFoundException : ApplicationException + { + public SPAUNotFoundException(int i) : base($"Не найден объект попозиции { i}") { } + public SPAUNotFoundException() : base() { } + public SPAUNotFoundException(string message) : base(message) { } + public SPAUNotFoundException(string message, Exception exception) : base(message, exception) { } + protected SPAUNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj index 13ee123..e37b3c3 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit.csproj @@ -8,6 +8,13 @@ enable + + + + + + + True diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs index f07b832..97ecf9b 100644 --- a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/SetGeneric.cs @@ -55,13 +55,14 @@ namespace SelfPropelledArtilleryUnit.Generics public int Insert(T spau, int position) { if (Count == _maxCount) - return -1; + throw new StorageOverflowException(Count); - if (position < 0 || spau == null) - return -1; - if (position >= _maxCount) - return -1; + if (spau == null) + throw new SPAUNotFoundException("Вставка невоможна, объект не найден"); + + if (position < 0 || position > _maxCount) + throw new SPAUNotFoundException(position); if (Count == 0) @@ -81,9 +82,8 @@ namespace SelfPropelledArtilleryUnit.Generics /// public bool Remove(int position) { - if (position < 0 || position >= Count) - return false; - + if (_places[position] == null) + throw new SPAUNotFoundException(position); _places.RemoveAt(position); return true; @@ -97,13 +97,13 @@ namespace SelfPropelledArtilleryUnit.Generics { get { - if (position < 0 || position >= _maxCount) + if (position < 0 || position >= Count) return null; return _places[position]; } set { - if (position < 0 || position >= _maxCount) + if (position < 0 || position > _maxCount) return; _places[position] = value; } diff --git a/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.cs new file mode 100644 index 0000000..9848120 --- /dev/null +++ b/SelfPropelledArtilleryUnit/SelfPropelledArtilleryUnit/StorageOverflowException.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 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) { } + } +}