From d7880d438d5f5f3280d0a4f9d5d147e6213b9285 Mon Sep 17 00:00:00 2001 From: Efi Date: Thu, 20 Apr 2023 23:31:51 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Monorail/Monorail/FormMapWithSetLocomotive.cs | 190 ++++++++++++------ .../Monorail/LocomotiveNotFoundException.cs | 19 ++ Monorail/Monorail/MapsCollection.cs | 76 +++---- Monorail/Monorail/Monorail.csproj | 17 ++ Monorail/Monorail/Program.cs | 47 ++++- Monorail/Monorail/SetLocomotiveGeneric.cs | 22 +- Monorail/Monorail/StorageOverflowException.cs | 19 ++ Monorail/Monorail/serilog.json | 20 ++ Monorail20230420 | 1 + 9 files changed, 297 insertions(+), 114 deletions(-) create mode 100644 Monorail/Monorail/LocomotiveNotFoundException.cs create mode 100644 Monorail/Monorail/StorageOverflowException.cs create mode 100644 Monorail/Monorail/serilog.json create mode 100644 Monorail20230420 diff --git a/Monorail/Monorail/FormMapWithSetLocomotive.cs b/Monorail/Monorail/FormMapWithSetLocomotive.cs index a81148a..494133b 100644 --- a/Monorail/Monorail/FormMapWithSetLocomotive.cs +++ b/Monorail/Monorail/FormMapWithSetLocomotive.cs @@ -8,37 +8,40 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; + namespace Monorail { public partial class FormMapWithSetLocomotive : Form { - private readonly Dictionary _mapsDict = new() + private MapWithSetLocomotiveGeneric _mapLocomotiveCollectionGeneric; + private readonly Dictionary _mapDict = new() { - { "Простая карта", new SimpleMap() }, - { "Карта с грязью", new FieldMap() }, - { "Карта с кустами", new BushesMap() } + {"Простая карта", new SimpleMap() }, + {"Карта с грязью", new FieldMap() }, + {"Карта с кустами",new BushesMap() } }; private readonly MapsCollection _mapsCollection; - - public FormMapWithSetLocomotive() + private readonly ILogger _logger; + public FormMapWithSetLocomotive(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); comboBoxSelectorMap.Items.Clear(); - foreach (var elem in _mapsDict) + foreach (var elem in _mapDict) { comboBoxSelectorMap.Items.Add(elem.Key); } } - private void ReloadMaps() { int index = listBoxMaps.SelectedIndex; listBoxMaps.Items.Clear(); - for (int i = 0; i < _mapsCollection.Keys.Count; i++) + foreach (var list in _mapsCollection.Keys) { - listBoxMaps.Items.Add(_mapsCollection.Keys[i]); + listBoxMaps.Items.Add(list); } if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count)) @@ -50,68 +53,69 @@ namespace Monorail listBoxMaps.SelectedIndex = index; } } - - private void ButtonAddMap_Click(object sender, EventArgs e) + private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, + EventArgs e) { - if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) + AbstractMap map = null; + switch (comboBoxSelectorMap.Text) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + case "Простая карта": + map = new SimpleMap(); + break; + case "Карта с грязью": + map = new FieldMap(); + break; + case "Карта с кустами": + map = new BushesMap(); + break; } - if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) + if (map != null) { - MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + _mapLocomotiveCollectionGeneric = new MapWithSetLocomotiveGeneric( + pictureBoxLocomotive.Width, pictureBoxLocomotive.Height, map); } - _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); - ReloadMaps(); - } - - private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) - { - pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); - } - - private void ButtonDeleteMap_Click(object sender, EventArgs e) - { - if (listBoxMaps.SelectedIndex == -1) + else { - return; - } - - if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); - ReloadMaps(); + _mapLocomotiveCollectionGeneric = null; } } - private void ButtonAddLocomotive_Click(object sender, EventArgs e) { var FormLocmotiveConfig = new FormLocomotiveConfig(); FormLocmotiveConfig.AddEvent(new(AddLocomotive)); FormLocmotiveConfig.Show(); } - public void AddLocomotive(DrawingLocomotive locomotive) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectLocomotive(locomotive) != -1) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Locomotive}", locomotive); + pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation("Не удалось добавить объект"); + } } - - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectLocomotive(locomotive) != -1) + catch (StorageOverflowException ex) { - MessageBox.Show("Object is added"); - pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + catch (ArgumentException ex) { - MessageBox.Show("Unable to add object"); + _logger.LogWarning("Ошибка добавления: {0}. Объект: {@Locomotive}", ex.Message, locomotive); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - } - private void ButtonRemoveLocomotive_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) @@ -127,17 +131,32 @@ namespace Monorail return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedLocomotive = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedLocomotive != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Locomotive}", deletedLocomotive); + pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (LocomotiveNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } - private void ButtonShowStorage_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) @@ -146,7 +165,6 @@ namespace Monorail } pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); } - private void ButtonShowOnMap_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) @@ -155,13 +173,13 @@ namespace Monorail } pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap(); } - private void ButtonMove_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) { return; } + //получаем имя кнопки string name = ((Button)sender)?.Name ?? string.Empty; Direction dir = Direction.None; switch (name) @@ -181,20 +199,56 @@ namespace Monorail } pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); } - + private void ButtonAddMap_Click(object sender, EventArgs e) + { + if (comboBoxSelectorMap.SelectedIndex == -1 || + string.IsNullOrEmpty(textBoxNewMapName.Text)) + { + MessageBox.Show("Не все данные заполнены", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) + { + MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + return; + } + _mapsCollection.AddMap(textBoxNewMapName.Text, + _mapDict[comboBoxSelectorMap.Text]); + ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); + } + private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) + { + pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + private void ButtonDeleteMap_Click(object sender, EventArgs e) + { + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + ReloadMaps(); + } + } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -204,17 +258,19 @@ namespace Monorail { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) + try { + _mapsCollection.LoadData(openFileDialog.FileName); ReloadMaps(); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + 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} | {ex.Message}."); } } } - } } diff --git a/Monorail/Monorail/LocomotiveNotFoundException.cs b/Monorail/Monorail/LocomotiveNotFoundException.cs new file mode 100644 index 0000000..aedfc15 --- /dev/null +++ b/Monorail/Monorail/LocomotiveNotFoundException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Monorail +{ + [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 contex) : base(info, contex) { } + } +} diff --git a/Monorail/Monorail/MapsCollection.cs b/Monorail/Monorail/MapsCollection.cs index f91f3d2..07db8dd 100644 --- a/Monorail/Monorail/MapsCollection.cs +++ b/Monorail/Monorail/MapsCollection.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; namespace Monorail { + internal class MapsCollection { readonly Dictionary> _mapStorages; @@ -43,66 +44,71 @@ namespace Monorail return null; } } - 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)) { File.Delete(filename); } - using (StreamWriter fs = new StreamWriter(filename)) + using (FileStream fs = new(filename, FileMode.Create)) { - fs.Write($"MapsCollection{Environment.NewLine}"); + WriteToFile($"MapsCollection{Environment.NewLine}", fs); foreach (var storage in _mapStorages) { - fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); + WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs); } } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } - string str = ""; - using (StreamReader fs = new StreamReader(filename)) + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) { - str = fs.ReadLine(); - if (!str.Contains("MapsCollection")) + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) { - //если нет такой записи, то это не те данные - return false; - } - _mapStorages.Clear(); - while ((str = fs.ReadLine()) != null) - { - var elem = str.Split(separatorDict); - AbstractMap map = null; - switch (elem[1]) - { - case "SimpleMap": - map = new SimpleMap(); - break; - case "BushesMap": - map = new BushesMap(); - break; - case "FieldMap": - map = new FieldMap(); - break; - } - _mapStorages.Add(elem[0], new MapWithSetLocomotiveGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + bufferTextFromFile += temp.GetString(b); } } - return true; + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (!strs[0].Contains("MapsCollection")) + { + //если нет такой записи, то это не те данные + throw new Exception("Формат данных в файле не правильный"); + } + //очищаем записи + _mapStorages.Clear(); + for (int i = 1; i < strs.Length; ++i) + { + var elem = strs[i].Split(separatorDict); + AbstractMap map = null; + switch (elem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "FieldMap": + map = new FieldMap(); + break; + case "BushesMap": + map = new BushesMap(); + break; + } + _mapStorages.Add(elem[0], new MapWithSetLocomotiveGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } } } } diff --git a/Monorail/Monorail/Monorail.csproj b/Monorail/Monorail/Monorail.csproj index 13ee123..e42e26f 100644 --- a/Monorail/Monorail/Monorail.csproj +++ b/Monorail/Monorail/Monorail.csproj @@ -8,6 +8,23 @@ enable + + + + + + + + + + + + + + + + + True diff --git a/Monorail/Monorail/Program.cs b/Monorail/Monorail/Program.cs index 344f9de..667b1fe 100644 --- a/Monorail/Monorail/Program.cs +++ b/Monorail/Monorail/Program.cs @@ -1,17 +1,62 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; +using System.Diagnostics; +using System.Reflection; + namespace Monorail { + 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 FormMapWithSetLocomotive()); + + var services = new ServiceCollection(); + ConfigureServices(services); + + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(ServiceCollection services) + { + + string path = Directory.GetCurrentDirectory(); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); + path = path.Substring(0, path.LastIndexOf("\\")); + + services.AddSingleton() + .AddLogging(option => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: path + "\\serilog.json", optional: false, reloadOnChange: true) + .Build(); + + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + logger.Information(" "); + }); + } } } \ No newline at end of file diff --git a/Monorail/Monorail/SetLocomotiveGeneric.cs b/Monorail/Monorail/SetLocomotiveGeneric.cs index f03e51b..c2c7146 100644 --- a/Monorail/Monorail/SetLocomotiveGeneric.cs +++ b/Monorail/Monorail/SetLocomotiveGeneric.cs @@ -25,26 +25,26 @@ namespace Monorail } public int Insert(T locomotive, int position) { - if (position <= _places.Count && _places.Count < _maxCount && position >= 0) + if (Count == _maxCount) { - _places.Insert(position, locomotive); - return position; + throw new StorageOverflowException(_maxCount); } - else - return -1; + if (position < 0 || position > _maxCount) return -1; + _places.Insert(position, locomotive); + return position; } public T Remove(int position) { - if (position < _places.Count && position >= 0) + if (position >= Count || position < 0) { - var locomotive = _places[position]; - _places.RemoveAt(position); - return locomotive; + throw new LocomotiveNotFoundException(position); } - else - return null; + T ship = _places[position]; + _places.RemoveAt(position); + return ship; } + public T this[int position] { get diff --git a/Monorail/Monorail/StorageOverflowException.cs b/Monorail/Monorail/StorageOverflowException.cs new file mode 100644 index 0000000..79b725b --- /dev/null +++ b/Monorail/Monorail/StorageOverflowException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Monorail +{ + [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/Monorail/Monorail/serilog.json b/Monorail/Monorail/serilog.json new file mode 100644 index 0000000..b9809a5 --- /dev/null +++ b/Monorail/Monorail/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._Monorail_Base\\Monorail\\log.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Locomotive" + } + } +} \ No newline at end of file diff --git a/Monorail20230420 b/Monorail20230420 new file mode 100644 index 0000000..54d8f87 --- /dev/null +++ b/Monorail20230420 @@ -0,0 +1 @@ +[23:29:36.152]INFO: Создание Лога