diff --git a/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs index 112673f..309d591 100644 --- a/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs +++ b/ElectricLocomotive/DrawningObjects/ExtentionDrawningLocomotive.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace ProjectElectricLocomotive.DrawningObjects { /// - /// Расширение для класса EntityCar + /// Расширение для класса EntityLocomotive /// public static class ExtentionDrawningLocomotive { diff --git a/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .cs b/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .cs new file mode 100644 index 0000000..6b84022 --- /dev/null +++ b/ElectricLocomotive/Exceptions/LocomotiveNotFoundException .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 ProjectElectricLocomotive.Exceptions +{ + [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 innerException) : base(message, innerException) { } + protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ElectricLocomotive/Exceptions/StorageOverflowException.cs b/ElectricLocomotive/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..73c104f --- /dev/null +++ b/ElectricLocomotive/Exceptions/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 ProjectElectricLocomotive.Exceptions +{ + [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/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs index 43335fa..6df5d63 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericCollection.cs @@ -149,6 +149,6 @@ namespace ProjectElectricLocomotive.Generics /// /// Получение объектов коллекции /// - public IEnumerable GetCars => _collection.GetLocomotives(); + public IEnumerable GetLocomotives => _collection.GetLocomotives(); } } \ No newline at end of file diff --git a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs index b10a6c2..012d4ce 100644 --- a/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs +++ b/ElectricLocomotive/Generics/LocomotivesGenericStorage.cs @@ -123,7 +123,7 @@ namespace ProjectElectricLocomotive.Generics sw.WriteLine("LocomotiveStorage"); if (_locomotiveStorage.Count == 0) { - return false; + throw new InvalidOperationException("Невалиданя операция, нет данных длясохранения"); } foreach ( KeyValuePair= _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } _places.Insert(0, locomotive); return true; @@ -70,11 +71,10 @@ namespace ProjectElectricLocomotive.Generics /// public bool Remove(int position) { - if (position >= Count || position < 0) + if (position >= Count || position < 0 || _places[position] == null) { - return false; + throw new LocomotiveNotFoundException(position); } - _places.RemoveAt(position); return true; @@ -90,7 +90,7 @@ namespace ProjectElectricLocomotive.Generics { if (position >= Count || position < 0) { - return null; + throw new LocomotiveNotFoundException(position); } return _places[position]; } diff --git a/ElectricLocomotive/LogicFormLocomotiveCollection.cs b/ElectricLocomotive/LogicFormLocomotiveCollection.cs index 1acefcd..ba3cb51 100644 --- a/ElectricLocomotive/LogicFormLocomotiveCollection.cs +++ b/ElectricLocomotive/LogicFormLocomotiveCollection.cs @@ -1,12 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using Microsoft.Extensions.Logging; using ProjectElectricLocomotive.DrawningObjects; +using ProjectElectricLocomotive.Exceptions; using ProjectElectricLocomotive.Generics; -using ProjectElectricLocomotive.MovementStrategy; +using System.Windows.Forms; +using System.Xml.Linq; namespace ProjectElectricLocomotive { @@ -21,15 +18,20 @@ namespace ProjectElectricLocomotive /// private readonly LocomotivesGenericStorage _storage; /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormLocomotiveCollection() + public FormLocomotiveCollection(ILogger logger) { InitializeComponent(); _storage = new LocomotivesGenericStorage( pictureBoxCollection.Width, pictureBoxCollection.Height ); + _logger = logger; } /// @@ -67,6 +69,7 @@ namespace ProjectElectricLocomotive } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } /// @@ -90,12 +93,14 @@ namespace ProjectElectricLocomotive { return; } - if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -122,15 +127,25 @@ namespace ProjectElectricLocomotive return; } SelectedLocomotive.SetPictureSize(pictureBoxCollection.Size); - if (obj + SelectedLocomotive > 0) + try { - MessageBox.Show("Объект добавлен"); + if (obj + SelectedLocomotive > 0) + { + MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowLocomotives(); + pictureBoxCollection.Image = obj.ShowLocomotives(); + _logger.LogInformation($"Объект {obj.GetType()} добавлен"); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogInformation($"Не удалось добавить объект"); + } } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.ToString()); } } @@ -165,14 +180,24 @@ namespace ProjectElectricLocomotive { pos = 0; } - if (obj - pos != -1) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowLocomotives(); + if (obj - pos != -1) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowLocomotives(); + _logger.LogInformation($"Объект {pos} удален"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogInformation($"Не удалось удалить объект {pos}"); + } } - else + catch (LocomotiveNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning(ex.ToString()); } } /// @@ -205,15 +230,19 @@ namespace ProjectElectricLocomotive saveFileDialog.Title = "Сохранение"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation($"Сохранение в {saveFileDialog.FileName} прошло успешно"); } - else - { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) + { + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation($"Не удалось сохранить в {saveFileDialog.FileName}: {ex.Message}"); + _logger.LogWarning(ex.ToString()); } } } @@ -225,16 +254,20 @@ namespace ProjectElectricLocomotive openFileDialog.Title = "Загрузка"; if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); ReloadObjects(); + _logger.LogInformation($"Загрузка из {openFileDialog.FileName} прошла успешно"); } - else + catch(Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation($"Не удалось загрузить из {openFileDialog.FileName}: {ex.Message}"); + _logger.LogWarning(ex.ToString()); } } } diff --git a/ElectricLocomotive/Program.cs b/ElectricLocomotive/Program.cs index 5def1ba..a29f79a 100644 --- a/ElectricLocomotive/Program.cs +++ b/ElectricLocomotive/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectElectricLocomotive { internal static class Program @@ -8,10 +13,37 @@ namespace ProjectElectricLocomotive [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 FormLocomotiveCollection()); + 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 => + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath( + Directory.GetCurrentDirectory()).AddJsonFile( + path: $"{pathNeed}serilog.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/ElectricLocomotive/ProjectElectricLocomotive.csproj b/ElectricLocomotive/ProjectElectricLocomotive.csproj index 13ee123..c8d4348 100644 --- a/ElectricLocomotive/ProjectElectricLocomotive.csproj +++ b/ElectricLocomotive/ProjectElectricLocomotive.csproj @@ -8,6 +8,19 @@ enable + + + + + + + + + + + + + True diff --git a/ElectricLocomotive/serilog.json b/ElectricLocomotive/serilog.json new file mode 100644 index 0000000..44c260c --- /dev/null +++ b/ElectricLocomotive/serilog.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "GasolineTanker" + } + } +} \ No newline at end of file