diff --git a/ArmoredVehicle/ArmoredVehicle.csproj b/ArmoredVehicle/ArmoredVehicle.csproj index 13ee123..19822d9 100644 --- a/ArmoredVehicle/ArmoredVehicle.csproj +++ b/ArmoredVehicle/ArmoredVehicle.csproj @@ -8,6 +8,30 @@ enable + + + + + + + Always + + + + + + + + + + + + + + + + + True diff --git a/ArmoredVehicle/FormMapWithSetMachine.Designer.cs b/ArmoredVehicle/FormMapWithSetMachine.Designer.cs index 1112daa..cfcbae4 100644 --- a/ArmoredVehicle/FormMapWithSetMachine.Designer.cs +++ b/ArmoredVehicle/FormMapWithSetMachine.Designer.cs @@ -158,7 +158,7 @@ this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ButtonDown.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonDown.BackgroundImage"))); this.ButtonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.ButtonDown.Location = new System.Drawing.Point(129, 790); + this.ButtonDown.Location = new System.Drawing.Point(129, 821); this.ButtonDown.Name = "ButtonDown"; this.ButtonDown.Size = new System.Drawing.Size(40, 36); this.ButtonDown.TabIndex = 17; @@ -170,7 +170,7 @@ this.ButtonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ButtonRight.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonRight.BackgroundImage"))); this.ButtonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.ButtonRight.Location = new System.Drawing.Point(172, 743); + this.ButtonRight.Location = new System.Drawing.Point(172, 774); this.ButtonRight.Name = "ButtonRight"; this.ButtonRight.Size = new System.Drawing.Size(40, 36); this.ButtonRight.TabIndex = 16; @@ -182,7 +182,7 @@ this.ButtonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ButtonLeft.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonLeft.BackgroundImage"))); this.ButtonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.ButtonLeft.Location = new System.Drawing.Point(89, 745); + this.ButtonLeft.Location = new System.Drawing.Point(89, 776); this.ButtonLeft.Name = "ButtonLeft"; this.ButtonLeft.Size = new System.Drawing.Size(40, 36); this.ButtonLeft.TabIndex = 15; @@ -194,7 +194,7 @@ this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ButtonUp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonUp.BackgroundImage"))); this.ButtonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; - this.ButtonUp.Location = new System.Drawing.Point(129, 695); + this.ButtonUp.Location = new System.Drawing.Point(129, 726); this.ButtonUp.Name = "ButtonUp"; this.ButtonUp.Size = new System.Drawing.Size(40, 36); this.ButtonUp.TabIndex = 14; @@ -273,14 +273,14 @@ // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - this.SaveToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(217, 34); this.SaveToolStripMenuItem.Text = "Сохранение "; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // LoadToolStripMenuItem // this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - this.LoadToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(217, 34); this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // diff --git a/ArmoredVehicle/FormMapWithSetMachine.cs b/ArmoredVehicle/FormMapWithSetMachine.cs index 72a02c4..33ce3d0 100644 --- a/ArmoredVehicle/FormMapWithSetMachine.cs +++ b/ArmoredVehicle/FormMapWithSetMachine.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -25,12 +26,18 @@ namespace ArmoredVehicle /// Объект от коллекции карт /// private readonly MapsCollection _mapsCollection; + /// + /// Логгер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMapWithSetMachine() + public FormMapWithSetMachine(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBoxImage.Width, pictureBoxImage.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -72,15 +79,18 @@ namespace ArmoredVehicle if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation($"Попытка добавить несуществующую карту: {textBoxNewMapName.Text}"); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}"); } /// @@ -91,6 +101,7 @@ namespace ArmoredVehicle private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Переход на карту: {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } /// @@ -102,6 +113,7 @@ namespace ArmoredVehicle { if (listBoxMaps.SelectedIndex == -1) { + _logger.LogInformation($"Попытка удалить несуществующую карту: {textBoxNewMapName.Text}"); return; } @@ -109,6 +121,7 @@ namespace ArmoredVehicle { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.LogInformation($"Удалена карта: {listBoxMaps.SelectedItem?.ToString()}"); } } @@ -122,7 +135,6 @@ namespace ArmoredVehicle FormMachineConfig formMachine = new(); formMachine.AddEvent(new(AddMachine)); formMachine.Show(); - } /// /// Добавление объекта @@ -130,24 +142,37 @@ namespace ArmoredVehicle /// private void AddMachine(DrawingArmoredVehicle machine) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + _logger.LogInformation($"Попытка добавления объекта на невыбранную карту"); + return; + } + if (machine == null) + { + MessageBox.Show("Необходимо выбрать объект перед добавлением!"); + _logger.LogInformation($"Не выбран объект для добавления на карту "); + return; + } + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(machine) != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Добавлен объект {machine} на карту "); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation($"Не удалось добавить объект {machine} на карту "); + } } - if(machine == null) + catch (StorageOverflowException ex) { - MessageBox.Show("Необходимо выбрать объект перед добавлением!"); - return; - } - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(machine) != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message); + MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } + } /// /// Удаление объекта @@ -165,14 +190,29 @@ namespace ArmoredVehicle return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("С карты удален объект {0}", pos); + } + else + { + _logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (MachineNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Произошла неизвестная ошибка: {0}", ex.Message); + MessageBox.Show($"Неизестная ошибка: {ex.Message}"); } } @@ -244,13 +284,16 @@ namespace ArmoredVehicle { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogWarning("Успешное сохранение карты в файл: {0}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка сохранения карты в файл: {0}", saveFileDialog.FileName); } } } @@ -263,17 +306,20 @@ namespace ArmoredVehicle { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _mapsCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadMaps(); + _logger.LogWarning("Успешная загрузка карты из файла: {0}", saveFileDialog.FileName); } - else + catch (LoadFileException ex) { - MessageBox.Show("Загрузка не удалась", "Результат", + MessageBox.Show($"Загрузка не удалась {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Ошибка загрузки карты из файла: {0}", saveFileDialog.FileName); } + } } } diff --git a/ArmoredVehicle/LoadFileException.cs b/ArmoredVehicle/LoadFileException.cs new file mode 100644 index 0000000..87c1790 --- /dev/null +++ b/ArmoredVehicle/LoadFileException.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ArmoredVehicle +{ + internal class LoadFileException : ApplicationException + { + public LoadFileException() : base() { } + public LoadFileException(string message) : base(message) { } + public LoadFileException(string message, Exception exception) : base(message, exception) { } + protected LoadFileException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ArmoredVehicle/MachineNotFoundException.cs b/ArmoredVehicle/MachineNotFoundException.cs new file mode 100644 index 0000000..58dcd31 --- /dev/null +++ b/ArmoredVehicle/MachineNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ArmoredVehicle +{ + [Serializable] + internal class MachineNotFoundException : ApplicationException + { + public MachineNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public MachineNotFoundException() : base() { } + public MachineNotFoundException(string message) : base(message) { } + public MachineNotFoundException(string message, Exception exception) : base(message, exception) { } + protected MachineNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ArmoredVehicle/MapWithSetMachineGeneric.cs b/ArmoredVehicle/MapWithSetMachineGeneric.cs index 30fcace..de88146 100644 --- a/ArmoredVehicle/MapWithSetMachineGeneric.cs +++ b/ArmoredVehicle/MapWithSetMachineGeneric.cs @@ -57,7 +57,7 @@ /// public static int operator +(MapWithSetMachineGeneric map, T machine) { - return map._setMachines.Insert(machine); + return map._setMachines.Insert(machine); } /// /// Перегрузка оператора вычитания diff --git a/ArmoredVehicle/MapsCollection.cs b/ArmoredVehicle/MapsCollection.cs index dde6dbf..0222b42 100644 --- a/ArmoredVehicle/MapsCollection.cs +++ b/ArmoredVehicle/MapsCollection.cs @@ -101,21 +101,11 @@ namespace ArmoredVehicle } } /// - /// Метод записи информации в файл - /// - /// Строка, которую следует записать - /// Поток для записи - private static void WriteToFile(string text, FileStream stream) - { - byte[] info = new UTF8Encoding(true).GetBytes(text); - stream.Write(info, 0, info.Length); - } - /// /// Сохранение информации по машинам в хранилище в файл /// /// Путь и имя файла /// - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -129,7 +119,7 @@ namespace ArmoredVehicle fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; + } /// @@ -137,11 +127,11 @@ namespace ArmoredVehicle /// /// /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new LoadFileException($"Файл {filename} не найден"); } string bufferTextFromFile = ""; using (StreamReader sr = new(filename)) @@ -149,7 +139,7 @@ namespace ArmoredVehicle string checkMap = sr.ReadLine(); if (!checkMap.Contains("MapsCollection")) { - return false; + throw new LoadFileException($"Неверный формат данных в файле {filename}"); } bufferTextFromFile = sr.ReadLine(); _mapStorages.Clear(); @@ -175,8 +165,6 @@ namespace ArmoredVehicle bufferTextFromFile = sr.ReadLine(); } } - return true; } - } } diff --git a/ArmoredVehicle/Program.cs b/ArmoredVehicle/Program.cs index 2c658ff..e3db197 100644 --- a/ArmoredVehicle/Program.cs +++ b/ArmoredVehicle/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + + namespace ArmoredVehicle { internal static class Program @@ -8,10 +14,31 @@ namespace ArmoredVehicle [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 FormMapWithSetMachine()); + 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 => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "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/ArmoredVehicle/SetMachineGeneric.cs b/ArmoredVehicle/SetMachineGeneric.cs index 675f409..f455bde 100644 --- a/ArmoredVehicle/SetMachineGeneric.cs +++ b/ArmoredVehicle/SetMachineGeneric.cs @@ -35,7 +35,7 @@ public int Insert(T machine) { if (Count + 1 <= _maxCount) return Insert(machine, 0); - else return -1; + else throw new StorageOverflowException(_maxCount); } /// /// Добавление объекта в набор на конкретную позицию @@ -45,13 +45,10 @@ /// public int Insert(T machine, int position) { - if (position >= _maxCount && position < 0) - { - return -1; - } + if(position >= _maxCount) throw new StorageOverflowException(_maxCount); _places.Insert(position, machine); - + return position; } /// @@ -71,9 +68,9 @@ return result; } - return null; + else throw new MachineNotFoundException(position); } - return null; + else throw new MachineNotFoundException(position); } /// /// Получение объекта из набора по позиции diff --git a/ArmoredVehicle/StorageOverflowException.cs b/ArmoredVehicle/StorageOverflowException.cs new file mode 100644 index 0000000..27897b6 --- /dev/null +++ b/ArmoredVehicle/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 ArmoredVehicle +{ + [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/ArmoredVehicle/appsettings.Designer.json b/ArmoredVehicle/appsettings.Designer.json new file mode 100644 index 0000000..8171e05 --- /dev/null +++ b/ArmoredVehicle/appsettings.Designer.json @@ -0,0 +1,36 @@ +namespace ArmoredVehicle +{ + partial class appsettings + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/ArmoredVehicle/nlog.config b/ArmoredVehicle/nlog.config new file mode 100644 index 0000000..5c71e85 --- /dev/null +++ b/ArmoredVehicle/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file