diff --git a/Locomotives/Locomotives/FormMapWithSetLocomotives.Designer.cs b/Locomotives/Locomotives/FormMapWithSetLocomotives.Designer.cs index 02f8491..5126946 100644 --- a/Locomotives/Locomotives/FormMapWithSetLocomotives.Designer.cs +++ b/Locomotives/Locomotives/FormMapWithSetLocomotives.Designer.cs @@ -70,7 +70,7 @@ this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.buttonAddCar); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(950, 24); + this.groupBoxTools.Location = new System.Drawing.Point(462, 24); this.groupBoxTools.Name = "groupBoxTools"; this.groupBoxTools.Size = new System.Drawing.Size(223, 652); this.groupBoxTools.TabIndex = 0; @@ -243,7 +243,7 @@ this.pictureBoxLocomotives.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBoxLocomotives.Location = new System.Drawing.Point(0, 24); this.pictureBoxLocomotives.Name = "pictureBoxLocomotives"; - this.pictureBoxLocomotives.Size = new System.Drawing.Size(950, 652); + this.pictureBoxLocomotives.Size = new System.Drawing.Size(462, 652); this.pictureBoxLocomotives.TabIndex = 1; this.pictureBoxLocomotives.TabStop = false; // @@ -253,7 +253,7 @@ this.FileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Size = new System.Drawing.Size(1173, 24); + this.menuStrip1.Size = new System.Drawing.Size(685, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip"; // @@ -269,14 +269,14 @@ // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.SaveToolStripMenuItem.Text = "Сохранение"; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // LoadToolStripMenuItem // this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(141, 22); this.LoadToolStripMenuItem.Text = "Загрузка"; this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); // @@ -292,7 +292,7 @@ // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1173, 676); + this.ClientSize = new System.Drawing.Size(685, 676); this.Controls.Add(this.pictureBoxLocomotives); this.Controls.Add(this.groupBoxTools); this.Controls.Add(this.menuStrip1); diff --git a/Locomotives/Locomotives/FormMapWithSetLocomotives.cs b/Locomotives/Locomotives/FormMapWithSetLocomotives.cs index 7154750..a28f5a6 100644 --- a/Locomotives/Locomotives/FormMapWithSetLocomotives.cs +++ b/Locomotives/Locomotives/FormMapWithSetLocomotives.cs @@ -1,4 +1,5 @@ -namespace Locomotives +using Serilog; +namespace Locomotives { /// /// Форма для работы с набором объектов @@ -18,12 +19,14 @@ /// Объект от коллекции карт /// private readonly MapsCollection _mapsCollection; + private readonly ILogger _logger; /// /// Конструктор /// - public FormMapWithSetLocomotives() + public FormMapWithSetLocomotives(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBoxLocomotives.Width, pictureBoxLocomotives.Height); comboBoxSelectorMap.Items.Clear(); foreach (var elem in _mapsDict) @@ -72,8 +75,9 @@ return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); - textBoxNewMapName.Text = ""; ReloadMaps(); + _logger.Information($"Создана карта типа {comboBoxSelectorMap.Text} с названием {textBoxNewMapName.Text}"); + textBoxNewMapName.Text = ""; } /// /// Выбор карты @@ -83,6 +87,7 @@ private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.Information($"Выбрана карта с названием {listBoxMaps.SelectedItem}"); } /// /// Удаление карты @@ -99,6 +104,7 @@ { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); + _logger.Information($"Удалена карта с названием {listBoxMaps.SelectedItem}"); } MessageBox.Show("Карта удалена"); } @@ -111,19 +117,33 @@ private void ButtonAddLocomotive_Click(object sender, EventArgs e) { FormLocomotiveConfig formLocomotiveConfig = new(); - formLocomotiveConfig.AddEvent(new (AddLocomotive)); + formLocomotiveConfig.AddEvent(new(AddLocomotive)); formLocomotiveConfig.Show(); } private void AddLocomotive(DrawningLocomotive locomotive) { - if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive)) > -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive)) > -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.Information($"Добавлен новый объект на карту {listBoxMaps.SelectedItem}"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show($"Ошибка добавления: {ex.Message}"); + _logger.Warning($"Не удалось добавить объект: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.Warning($"Не удалось добавить объект: {ex.Message}"); } } /// @@ -146,16 +166,29 @@ return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) > -1) + try { - MessageBox.Show("Объект удален"); - pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos) > -1) + { + MessageBox.Show("Объект удален"); + pictureBoxLocomotives.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.Information($"Удалён объект с карты {listBoxMaps.SelectedItem}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LocomotiveNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.Warning($"Не удалось удалить объект: {ex.Message}"); + } + catch (Exception ex) + { + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); + _logger.Warning($"Не удалось удалить объект: {ex.Message}"); } - } /// /// Вывод набора @@ -223,15 +256,18 @@ { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + _mapsCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.Information($"Коллекция карт сохранена в файл по адресу {saveFileDialog.FileName}"); } - else + catch(Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Warning($"Ошибка сохранения файла по адресу {saveFileDialog.FileName}: {ex.Message}"); } } } @@ -244,16 +280,19 @@ { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); - ReloadMaps(); + _mapsCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadMaps(); + _logger.Information($"Коллекция карт загружена из файла по адресу {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось загрузить файл", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не удалось загрузить файл: {ex.Message}", "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.Warning($"Ошибка загрузки файла по адресу {openFileDialog.FileName}: {ex.Message}"); } } } diff --git a/Locomotives/Locomotives/LocomotiveNotFoundException.cs b/Locomotives/Locomotives/LocomotiveNotFoundException.cs new file mode 100644 index 0000000..38c3942 --- /dev/null +++ b/Locomotives/Locomotives/LocomotiveNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace Locomotives +{ + [Serializable] + internal class LocomotiveNotFoundException : ApplicationException + { + public LocomotiveNotFoundException(int i) : base($"Не наден объект по позиции {i}") { } + public LocomotiveNotFoundException() : base() { } + public LocomotiveNotFoundException(string message) : base(message) { } + public LocomotiveNotFoundException(string message, Exception Exception) : base(message, Exception) { } + protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Locomotives/Locomotives/Locomotives.csproj b/Locomotives/Locomotives/Locomotives.csproj index ce86fc6..66f3144 100644 --- a/Locomotives/Locomotives/Locomotives.csproj +++ b/Locomotives/Locomotives/Locomotives.csproj @@ -8,6 +8,16 @@ enable + + + + + + + Always + + + True @@ -27,4 +37,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Locomotives/Locomotives/MapsCollection.cs b/Locomotives/Locomotives/MapsCollection.cs index 0f6e083..c135794 100644 --- a/Locomotives/Locomotives/MapsCollection.cs +++ b/Locomotives/Locomotives/MapsCollection.cs @@ -71,7 +71,7 @@ namespace Locomotives return _mapStorages[ind]; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -86,13 +86,12 @@ namespace Locomotives } sw.Close(); } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найдён"); } using (StreamReader sr = new(filename)) { @@ -100,7 +99,7 @@ namespace Locomotives if (firstStr == null || !firstStr.Contains("MapsCollection")) { //если нет такой записи, то это не те данные - return false; + throw new FileFormatException("Формат данных в файле неправильный"); } string? currentString; while ((currentString = sr.ReadLine()) != null) @@ -123,7 +122,6 @@ namespace Locomotives _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } sr.Close(); - return true; } } } diff --git a/Locomotives/Locomotives/Program.cs b/Locomotives/Locomotives/Program.cs index 47d160f..5c76eb5 100644 --- a/Locomotives/Locomotives/Program.cs +++ b/Locomotives/Locomotives/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.Configuration; +using Serilog; + namespace Locomotives { internal static class Program @@ -8,8 +11,17 @@ namespace Locomotives [STAThread] static void Main() { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appconfig.json") + .AddJsonFile($"appconfig.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true) + .Build(); + var Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .ReadFrom.Configuration(configuration) + .CreateLogger(); ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetLocomotives()); + Application.Run(new FormMapWithSetLocomotives(Logger)); } } } \ No newline at end of file diff --git a/Locomotives/Locomotives/SetLocomotivesGeneric.cs b/Locomotives/Locomotives/SetLocomotivesGeneric.cs index 96c7182..987227c 100644 --- a/Locomotives/Locomotives/SetLocomotivesGeneric.cs +++ b/Locomotives/Locomotives/SetLocomotivesGeneric.cs @@ -43,7 +43,7 @@ _places.Insert(0, locomotive); return 0; } - return -1; + throw new StorageOverflowException(_places.Count); } /// /// Добавление объекта в набор на конкретную позицию @@ -62,7 +62,7 @@ _places.Insert(position, locomotive); return position; } - return -1; + throw new StorageOverflowException(_places.Count); } /// /// Удаление объекта из набора с конкретной позиции @@ -71,9 +71,9 @@ /// public int Remove(int position) { - if (position > Count || _places[position] == null) + if (position >= Count || _places[position] == null) { - return -1; + throw new LocomotiveNotFoundException(position); } _places.RemoveAt(position); return position; diff --git a/Locomotives/Locomotives/StorageOverflowException.cs b/Locomotives/Locomotives/StorageOverflowException.cs new file mode 100644 index 0000000..5900987 --- /dev/null +++ b/Locomotives/Locomotives/StorageOverflowException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace Locomotives +{ + [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 context) : base(info, context) { } + } +} diff --git a/Locomotives/Locomotives/appconfig.json b/Locomotives/Locomotives/appconfig.json new file mode 100644 index 0000000..b8a1b62 --- /dev/null +++ b/Locomotives/Locomotives/appconfig.json @@ -0,0 +1,17 @@ +{ + "Serilog": + { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": + { + "path": "Logs/log.log", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level}: {Message};{NewLine}" + } + } + ] + } +} \ No newline at end of file