diff --git a/DoubleDeckerBus/DoubleDeckerBus/BusNotFoundException.cs b/DoubleDeckerBus/DoubleDeckerBus/BusNotFoundException.cs new file mode 100644 index 0000000..3757dac --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/BusNotFoundException.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 DoubleDeckerBus +{ + [Serializable] + internal class BusNotFoundException : ApplicationException + { + public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public BusNotFoundException() : base() { } + public BusNotFoundException(string message) : base(message) { } + public BusNotFoundException(string message, Exception exception) : base(message, exception) { } + protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj index d7b238e..4200721 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj +++ b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj @@ -8,6 +8,30 @@ enable + + + + + + + SettingsSingleFileGenerator + serilog.Designer.cs + Always + + + + + + + + + + + + + + + PreserveNewest @@ -17,6 +41,11 @@ True Resources.resx + + True + True + serilog.json + diff --git a/DoubleDeckerBus/DoubleDeckerBus/DrawingObjectBus.cs b/DoubleDeckerBus/DoubleDeckerBus/DrawingObjectBus.cs index bd5e511..f881878 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DrawingObjectBus.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/DrawingObjectBus.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -8,13 +9,22 @@ namespace DoubleDeckerBus { internal class DrawingObjectBus : IDrawingObject { - private DrawingBus _bus = null; + public DrawingBus? _bus = null; public DrawingObjectBus(DrawingBus bus) { _bus = bus; } + public DrawingBus? Get_bus() + { + return _bus; + } + + public DrawingBus getBus(DrawingBus? _bus) { + return _bus; + } + public float Step => _bus?.Bus?.Step ?? 0; public (float Left, float Right, float Top, float Bottom) GetCurrentPosition() @@ -22,7 +32,7 @@ namespace DoubleDeckerBus return _bus?.GetCurrentPosition() ?? default; } - public string GetInfo() + public string? GetInfo() { return _bus?.GetDataForSave(); } @@ -46,5 +56,10 @@ namespace DoubleDeckerBus { return new DrawingObjectBus(data.CreateDrawningCar()); } + + public DrawingBus getBus() + { + return _bus; + } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusConfig.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusConfig.cs index 2c4b4d3..63346bc 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusConfig.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusConfig.cs @@ -143,7 +143,7 @@ namespace DoubleDeckerBus } private void ButtonAdd_Click(object sender, EventArgs e) - { + { EventAddBus?.Invoke(_bus); Close(); } diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormMapWithSetBuses.cs b/DoubleDeckerBus/DoubleDeckerBus/FormMapWithSetBuses.cs index 9b404cb..35a549d 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormMapWithSetBuses.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormMapWithSetBuses.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -21,9 +22,12 @@ namespace DoubleDeckerBus private readonly MapsCollection _mapsCollection; - public FormMapWithSetBuses() + private readonly ILogger _logger; + + public FormMapWithSetBuses(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxSelectorMap.Items.Clear(); foreach (var item in _mapsDict) { @@ -56,24 +60,30 @@ namespace DoubleDeckerBus var formBusConfig = new FormBusConfig(); formBusConfig.AddEvent(AddBus); formBusConfig.Show(); - } private void AddBus(DrawingBus bus) - { + { if (listBoxMaps.SelectedIndex == -1) { return; } - DrawingObjectBus boat = new(bus); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0) + try { + DrawingObjectBus _bus = new(bus); + _ = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + _bus; MessageBox.Show("Объект добавлен"); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Объект добавлен"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show($"Не удалось добавить объект {ex.Message}"); + _logger.LogInformation($"Объект не добаавлен {ex.Message}"); + } + catch (Exception ex) { + MessageBox.Show($"Не удалось добавить объект {ex.Message}"); + _logger.LogInformation($"Объект не добаавлен {ex.Message}"); } } @@ -88,15 +98,31 @@ namespace DoubleDeckerBus return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален"); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Объект не удален"); + } } - else + catch (BusNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + _logger.LogWarning("Автобус не найден"); } + catch (Exception ex) + { + MessageBox.Show($"Неизветсная шибка: {ex.Message}"); + _logger.LogWarning("Неизвестная ошибка при удалении"); + } + } private void ButtonShowStorage_Click(object sender, EventArgs e) @@ -106,6 +132,7 @@ namespace DoubleDeckerBus return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Отображение хранилища"); } private void ButtonShowOnMap_Click(object sender, EventArgs e) @@ -115,6 +142,7 @@ namespace DoubleDeckerBus return; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap(); + _logger.LogInformation($"Отображение карты"); } private void ButtonMove_Click(object sender, EventArgs e) @@ -142,6 +170,7 @@ namespace DoubleDeckerBus break; } pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir); + _logger.LogInformation($"Передвижение {name}"); } private void ButtonAddMap_Click(object sender, EventArgs e) @@ -149,32 +178,38 @@ namespace DoubleDeckerBus if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не все данные заполнены при добавлени карты"); return; } if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Нет такой карты {comboBoxSelectorMap.Text}"); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}"); } private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation($"Выбраная карта изменилась {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); } private void ButtonDeleteMap_Click(object sender, EventArgs e) { if (listBoxMaps.SelectedIndex == -1) { + _logger.LogWarning("Удаление карты не произошло. Не выбрана карта"); return; } if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); + _logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}"); ReloadMaps(); } } @@ -183,13 +218,15 @@ namespace DoubleDeckerBus { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.SaveData(saveFileDialog.FileName)) + try { + _mapsCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение {openFileDialog.FileName} прошло успешно"); } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) { + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Сохранение {openFileDialog.FileName} прошло не успешно"); } } } @@ -198,13 +235,16 @@ namespace DoubleDeckerBus { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_mapsCollection.LoadData(openFileDialog.FileName)) - { + try { + _mapsCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна"); ReloadMaps(); } - else { - MessageBox.Show("Ошибка при загрузке", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) + { + MessageBox.Show($"Ошибка при загрузке: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Загрузка из файла {openFileDialog.FileName} прошла не успешно"); } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/IDrawingObject.cs b/DoubleDeckerBus/DoubleDeckerBus/IDrawingObject.cs index 93c20a0..2e091e9 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/IDrawingObject.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/IDrawingObject.cs @@ -8,6 +8,7 @@ namespace DoubleDeckerBus { internal interface IDrawingObject { + public DrawingBus getBus(); public float Step { get; } void SetObject(int x, int y, int width, int height); diff --git a/DoubleDeckerBus/DoubleDeckerBus/MapWithSetBusesGeneric.cs b/DoubleDeckerBus/DoubleDeckerBus/MapWithSetBusesGeneric.cs index d5513cf..66aed8b 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/MapWithSetBusesGeneric.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/MapWithSetBusesGeneric.cs @@ -29,7 +29,7 @@ namespace DoubleDeckerBus } public static int operator +(MapWithSetBusesGeneric map, T bus) - { + { return map._setBuses.Insert(bus); } diff --git a/DoubleDeckerBus/DoubleDeckerBus/MapsCollection.cs b/DoubleDeckerBus/DoubleDeckerBus/MapsCollection.cs index 5642947..eff74e7 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/MapsCollection.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/MapsCollection.cs @@ -51,7 +51,7 @@ namespace DoubleDeckerBus stream.Write(info, 0, info.Length); } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -65,14 +65,13 @@ namespace DoubleDeckerBus sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } - return true; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не найден"); } string line; using (StreamReader sw = new(filename)) @@ -80,7 +79,7 @@ namespace DoubleDeckerBus line = sw.ReadLine(); if (line == null || !line.Contains("MapsCollection")) { - return false; + throw new FileFormatException("Формат данных в файле не совпадает"); } _mapStorages.Clear(); @@ -102,8 +101,6 @@ namespace DoubleDeckerBus _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); line = sw.ReadLine(); } - - return true; } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/Program.cs b/DoubleDeckerBus/DoubleDeckerBus/Program.cs index 66c3e0d..75a901f 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Program.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Logging; + namespace DoubleDeckerBus { internal static class Program @@ -11,7 +17,27 @@ namespace DoubleDeckerBus // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMapWithSetBuses()); + 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: "serilog.json").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/DoubleDeckerBus/DoubleDeckerBus/SetBusesGeneric.cs b/DoubleDeckerBus/DoubleDeckerBus/SetBusesGeneric.cs index 1da17a2..a0a4123 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/SetBusesGeneric.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/SetBusesGeneric.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace DoubleDeckerBus { internal class SetBusesGeneric - where T : class + where T : IDrawingObject { private readonly List _places; @@ -29,7 +29,11 @@ namespace DoubleDeckerBus public int Insert(T bus, int position) { - if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) return -1; + if (position < 0 || position >= _maxCount) + { + throw new BusNotFoundException("Место указано неверно"); + } + BusyPlaces++; _places.Insert(position, bus); @@ -38,7 +42,10 @@ namespace DoubleDeckerBus public T Remove(int position) { - if (position < 0 || position >= _maxCount) return null; + + if (position < 0 || position >= _maxCount) { + throw new BusNotFoundException(position); + } T savedBus = _places[position]; _places.RemoveAt(position); return savedBus; @@ -46,7 +53,7 @@ namespace DoubleDeckerBus public T this[int position] { get { - if (position < 0 || position >= _maxCount) return null; + if (position < 0 || position >= _maxCount) return default(T); return _places[position]; } set { diff --git a/DoubleDeckerBus/DoubleDeckerBus/StorageOverFlowException.cs b/DoubleDeckerBus/DoubleDeckerBus/StorageOverFlowException.cs new file mode 100644 index 0000000..1e6d319 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/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 DoubleDeckerBus +{ + [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/DoubleDeckerBus/DoubleDeckerBus/serilog.Designer.cs b/DoubleDeckerBus/DoubleDeckerBus/serilog.Designer.cs new file mode 100644 index 0000000..456cc8b --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/serilog.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Этот код создан программой. +// Исполняемая версия:4.0.30319.42000 +// +// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае +// повторной генерации кода. +// +//------------------------------------------------------------------------------ + +namespace DoubleDeckerBus { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.3.0.0")] + internal sealed partial class serilog : global::System.Configuration.ApplicationSettingsBase { + + private static serilog defaultInstance = ((serilog)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new serilog()))); + + public static serilog Default { + get { + return defaultInstance; + } + } + } +} diff --git a/DoubleDeckerBus/DoubleDeckerBus/serilog.json b/DoubleDeckerBus/DoubleDeckerBus/serilog.json new file mode 100644 index 0000000..4c3cf19 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "DoubleDeckerBus" + } + } +} \ No newline at end of file