From 14ce4e5d499022e4d51d3646bb095c34b93d372b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=BB=D1=8C=D1=8F?= <Илья@WIN-RANNDDD> Date: Tue, 5 Dec 2023 14:10:33 +0400 Subject: [PATCH] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=207?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectMonorail/AppSettings.json | 20 +++++ .../ProjectMonorail/FormMonorailCollection.cs | 90 +++++++++++++------ .../MonorailNotFoundException.cs | 14 +++ .../MonorailsGenericCollection.cs | 6 +- .../MonorailsGenericStorage.cs | 18 ++-- ProjectMonorail/ProjectMonorail/Program.cs | 29 +++++- .../ProjectMonorail/ProjectMonorail.csproj | 11 +++ ProjectMonorail/ProjectMonorail/SetGeneric.cs | 15 ++-- .../StorageOverflowException.cs | 14 +++ 9 files changed, 170 insertions(+), 47 deletions(-) create mode 100644 ProjectMonorail/ProjectMonorail/AppSettings.json create mode 100644 ProjectMonorail/ProjectMonorail/MonorailNotFoundException.cs create mode 100644 ProjectMonorail/ProjectMonorail/StorageOverflowException.cs diff --git a/ProjectMonorail/ProjectMonorail/AppSettings.json b/ProjectMonorail/ProjectMonorail/AppSettings.json new file mode 100644 index 0000000..2fb5725 --- /dev/null +++ b/ProjectMonorail/ProjectMonorail/AppSettings.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": "Monorail" + } + } +} \ No newline at end of file diff --git a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs index ff9b2b0..50985a7 100644 --- a/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs +++ b/ProjectMonorail/ProjectMonorail/FormMonorailCollection.cs @@ -1,6 +1,7 @@ -using ProjectMonorail.DrawingObjects; +using Microsoft.Extensions.Logging; +using ProjectMonorail.DrawingObjects; using ProjectMonorail.Generics; -using System.Windows.Forms; +using ProjectMonorail.Exceptions; namespace ProjectMonorail { @@ -14,13 +15,19 @@ namespace ProjectMonorail /// private readonly MonorailsGenericStorage _storage; + /// + /// Логгер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormMonorailCollection() + public FormMonorailCollection(ILogger logger) { InitializeComponent(); _storage = new MonorailsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// @@ -53,11 +60,13 @@ namespace ProjectMonorail { if (string.IsNullOrEmpty(textBoxNameSet.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Not all data are filled in", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Failed attempt to add a set: not all data are filled in"); return; } _storage.AddSet(textBoxNameSet.Text); ReloadObjects(); + _logger.LogInformation($"Set added: {textBoxNameSet.Text}"); } /// @@ -80,12 +89,16 @@ namespace ProjectMonorail { if (listBoxSets.SelectedIndex == -1) { + _logger.LogWarning($"Failed attempt to delete a set: no set is selected"); return; } - if (MessageBox.Show($"Удалить набор {listBoxSets.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxSets.SelectedItem.ToString() ?? string.Empty; + + if (MessageBox.Show($"Delete a set {name}?", "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxSets.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Deleted set: {name}"); } } @@ -101,17 +114,27 @@ namespace ProjectMonorail var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Failed attempt to add a object: set is null"); return; } - if (obj + monorail != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowMonorails(); + if (obj + monorail != -1) + { + MessageBox.Show("Object added"); + pictureBoxCollection.Image = obj.ShowMonorails(); + _logger.LogInformation($"Object added {monorail}"); + } + else + { + MessageBox.Show("Failed attempt to add a object"); + } } - else + catch (ApplicationException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Failed attempt to add a object: {ex.Message}"); } } @@ -124,6 +147,7 @@ namespace ProjectMonorail { if (listBoxSets.SelectedIndex == -1) { + _logger.LogWarning($"Failed attempt to add a object: no set is selected"); return; } var formMonorailConfig = new FormMonorailConfig(); @@ -140,31 +164,41 @@ namespace ProjectMonorail { if (listBoxSets.SelectedIndex == -1) { + _logger.LogWarning($"Failed attempt to delete a object: no set is selected"); return; } var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning($"Failed attempt to delete a object: set is null"); return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + if (MessageBox.Show("Delete a object?", "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - - if (obj - pos) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowMonorails(); + if (obj - pos) + { + MessageBox.Show("Object deleted"); + pictureBoxCollection.Image = obj.ShowMonorails(); + _logger.LogInformation($"Deleted object in position: {pos}"); + } + else + { + MessageBox.Show("Failed attempt to delete a object"); + } } - else + catch (MonorailNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); - } + MessageBox.Show(ex.Message); + _logger.LogWarning($"Failed attempt to delete a object: {ex.Message}"); + } } /// @@ -197,15 +231,18 @@ namespace ProjectMonorail { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Save was successful", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"File saved successfully: {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Save failed", "Result", + MessageBox.Show($"Save failed: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"File saving failed: {ex.Message}"); } } } @@ -219,16 +256,19 @@ namespace ProjectMonorail { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Load was successful", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information); ReloadObjects(); + _logger.LogInformation($"File loaded successfully: {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Load failed", "Result", + MessageBox.Show($"Load failed: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"File loading failed: {ex.Message}"); } } } diff --git a/ProjectMonorail/ProjectMonorail/MonorailNotFoundException.cs b/ProjectMonorail/ProjectMonorail/MonorailNotFoundException.cs new file mode 100644 index 0000000..a619828 --- /dev/null +++ b/ProjectMonorail/ProjectMonorail/MonorailNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectMonorail.Exceptions +{ + [Serializable] + internal class MonorailNotFoundException : ApplicationException + { + public MonorailNotFoundException(int i) : base($"Object not found by position {i}") { } + public MonorailNotFoundException() : base() { } + public MonorailNotFoundException(string message) : base(message) { } + public MonorailNotFoundException(string message, Exception exception) : base(message, exception) { } + protected MonorailNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs b/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs index 40b0329..40e87f2 100644 --- a/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs +++ b/ProjectMonorail/ProjectMonorail/MonorailsGenericCollection.cs @@ -80,11 +80,7 @@ namespace ProjectMonorail.Generics public static bool operator -(MonorailsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - return collect._collection.Remove(pos); - } - return false; + return collect._collection.Remove(pos); } /// diff --git a/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs b/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs index f23c149..70e883f 100644 --- a/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs +++ b/ProjectMonorail/ProjectMonorail/MonorailsGenericStorage.cs @@ -95,8 +95,7 @@ namespace ProjectMonorail.Generics /// Сохранение информации по монорельсам в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -114,35 +113,33 @@ namespace ProjectMonorail.Generics } if (data.Length == 0) { - return false; + throw new Exception("Invalid operation, no data to save"); } using StreamWriter sw = new(filename); sw.Write($"MonorailStorage{Environment.NewLine}{data}"); - return true; } /// /// Загрузка информации по монорельсам в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("File not found"); } using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new NullReferenceException("No data to load"); } if (!str.StartsWith("MonorailStorage")) { //если нет такой записи, то это не те данные - return false; + throw new InvalidDataException("Invalid data format"); } _monorailsStorages.Clear(); while ((str = sr.ReadLine()) != null) @@ -161,14 +158,13 @@ namespace ProjectMonorail.Generics { if (collection + monorail == -1) { - return false; + throw new ApplicationException("Error adding to collection"); } } } _monorailsStorages.Add(record[0], collection); } } - return true; } } } diff --git a/ProjectMonorail/ProjectMonorail/Program.cs b/ProjectMonorail/ProjectMonorail/Program.cs index beba8fb..543d8c9 100644 --- a/ProjectMonorail/ProjectMonorail/Program.cs +++ b/ProjectMonorail/ProjectMonorail/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectMonorail { internal static class Program @@ -11,7 +16,29 @@ namespace ProjectMonorail // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMonorailCollection()); + 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}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/ProjectMonorail/ProjectMonorail/ProjectMonorail.csproj b/ProjectMonorail/ProjectMonorail/ProjectMonorail.csproj index 13ee123..c579bd7 100644 --- a/ProjectMonorail/ProjectMonorail/ProjectMonorail.csproj +++ b/ProjectMonorail/ProjectMonorail/ProjectMonorail.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/ProjectMonorail/ProjectMonorail/SetGeneric.cs b/ProjectMonorail/ProjectMonorail/SetGeneric.cs index bab1cd7..90c37bb 100644 --- a/ProjectMonorail/ProjectMonorail/SetGeneric.cs +++ b/ProjectMonorail/ProjectMonorail/SetGeneric.cs @@ -1,4 +1,7 @@ -namespace ProjectMonorail.Generics +using ProjectMonorail.Exceptions; +using System.Collections.Generic; + +namespace ProjectMonorail.Generics { /// /// Параметризованный набор объектов @@ -48,9 +51,11 @@ /// Позиция /// public int Insert(T monorail, int position) - { - if (position < 0 || position > Count || Count >= _maxCount) - return -1; + { + if (position < 0 || position > Count) + throw new MonorailNotFoundException("Impossible to insert"); + if (Count >= _maxCount) + throw new StorageOverflowException(_maxCount); _places.Insert(position, monorail); return position; @@ -64,7 +69,7 @@ public bool Remove(int position) { if (position < 0 || position >= Count) - return false; + throw new MonorailNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/ProjectMonorail/ProjectMonorail/StorageOverflowException.cs b/ProjectMonorail/ProjectMonorail/StorageOverflowException.cs new file mode 100644 index 0000000..2984f2f --- /dev/null +++ b/ProjectMonorail/ProjectMonorail/StorageOverflowException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectMonorail.Exceptions +{ + [Serializable] + internal class StorageOverflowException : ApplicationException + { + public StorageOverflowException(int count) : base($"The set has exceeded the allowable count: { 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) { } + } +}