From a8c6ceef37cc6d04bcbeefecc0faca08bc1762ee Mon Sep 17 00:00:00 2001 From: DyCTaTOR <125912249+DyCTaTOR@users.noreply.github.com> Date: Mon, 4 Dec 2023 22:01:10 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Exceptions/MonorailNotFoundException.cs | 22 +++++ .../Exceptions/StorageOverflowException.cs | 21 +++++ Monorail/Monorail/FormMonorailCollection.cs | 87 +++++++++++-------- .../Generics/MonorailsGenericStorage.cs | 24 ++--- Monorail/Monorail/Monorail.csproj | 10 +++ Monorail/Monorail/Program.cs | 34 +++++++- Monorail/saveFileDialog.txt | 2 + 7 files changed, 148 insertions(+), 52 deletions(-) create mode 100644 Monorail/Monorail/Exceptions/MonorailNotFoundException.cs create mode 100644 Monorail/Monorail/Exceptions/StorageOverflowException.cs create mode 100644 Monorail/saveFileDialog.txt diff --git a/Monorail/Monorail/Exceptions/MonorailNotFoundException.cs b/Monorail/Monorail/Exceptions/MonorailNotFoundException.cs new file mode 100644 index 0000000..ff1967f --- /dev/null +++ b/Monorail/Monorail/Exceptions/MonorailNotFoundException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Monorail.Exceptions +{ + [Serializable] + internal class MonorailNotFoundException : ApplicationException + { + public MonorailNotFoundException(int i) : base($"Не найден объект по позиции {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/Monorail/Monorail/Exceptions/StorageOverflowException.cs b/Monorail/Monorail/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..b1279d2 --- /dev/null +++ b/Monorail/Monorail/Exceptions/StorageOverflowException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Monorail.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/Monorail/Monorail/FormMonorailCollection.cs b/Monorail/Monorail/FormMonorailCollection.cs index 4a8a3cf..49edb49 100644 --- a/Monorail/Monorail/FormMonorailCollection.cs +++ b/Monorail/Monorail/FormMonorailCollection.cs @@ -8,8 +8,12 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Monorail.DrawningObjects; +using Monorail.Exceptions; using Monorail.Generics; using Monorail.MovementStrategy; +using Monorail.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace Monorail { @@ -17,12 +21,16 @@ namespace Monorail public partial class FormMonorailCollection : Form { private readonly MonorailsGenericStorage _storage; + + private readonly ILogger _logger; + readonly int countPlace = 21; - public FormMonorailCollection() + public FormMonorailCollection(ILogger logger) { InitializeComponent(); _storage = new MonorailsGenericStorage (pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -49,11 +57,13 @@ namespace Monorail { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не все данные заполнены"); return; } - _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}"); + } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) @@ -67,12 +77,16 @@ EventArgs e) { 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); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void ButtonAddMonorail_Click(object sender, EventArgs e) @@ -103,18 +117,22 @@ EventArgs e) { return; } - - int addedIndex = obj + monorail; - if (addedIndex != -1 && addedIndex < countPlace) + try { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowMonorails(); + int addedIndex = obj + monorail; + if (addedIndex != -1 && addedIndex < countPlace) + { + MessageBox.Show("Объект добавлен"); + pictureBoxCollection.Image = obj.ShowMonorails(); + _logger.LogInformation($"Добавлен монорельс"); + } } - - else + catch(StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning("Не удалось добавить объект"); } + } private void ButtonRemoveMonorail_Click(object sender, EventArgs e) { @@ -135,24 +153,20 @@ EventArgs e) { return; } - int pos; - if (maskedTextBoxNumber.Text == "") + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + try { - MessageBox.Show("Введите позицию элемента выше"); - return; + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowMonorails(); + _logger.LogInformation("Объект удален"); + } } - else + catch (MonorailNotFoundException ex) { - pos = Convert.ToInt32(maskedTextBoxNumber.Text); - } - if (obj - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowMonorails(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"Не удалось удалить объект. Исключение: {ex}"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -172,15 +186,16 @@ EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -188,17 +203,17 @@ EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else + ReloadObjects(); + } catch(MonorailNotFoundException ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - ReloadObjects(); } } } diff --git a/Monorail/Monorail/Generics/MonorailsGenericStorage.cs b/Monorail/Monorail/Generics/MonorailsGenericStorage.cs index 5fa5bca..b97db18 100644 --- a/Monorail/Monorail/Generics/MonorailsGenericStorage.cs +++ b/Monorail/Monorail/Generics/MonorailsGenericStorage.cs @@ -52,7 +52,7 @@ namespace Monorail.Generics return _monorailsStorages[ind]; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -72,28 +72,28 @@ namespace Monorail.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } using StreamWriter sw = new(filename); sw.Write($"MonorailStorage{Environment.NewLine}{data}"); - return true; + return; } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader sr = File.OpenText(filename)) { string str = sr.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!str.StartsWith("MonorailStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _monorailsStorages.Clear(); @@ -101,11 +101,6 @@ namespace Monorail.Generics while ((strs = sr.ReadLine()) != null) { - if (strs == null) - { - return false; - } - string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { @@ -122,15 +117,14 @@ namespace Monorail.Generics { if ((collection + monorail) == -1) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); + } } } _monorailsStorages.Add(record[0], collection); } - return true; } } - } } diff --git a/Monorail/Monorail/Monorail.csproj b/Monorail/Monorail/Monorail.csproj index b57c89e..bfb95a5 100644 --- a/Monorail/Monorail/Monorail.csproj +++ b/Monorail/Monorail/Monorail.csproj @@ -8,4 +8,14 @@ enable + + + + + + + + + + \ No newline at end of file diff --git a/Monorail/Monorail/Program.cs b/Monorail/Monorail/Program.cs index 411e9f6..2d5c64a 100644 --- a/Monorail/Monorail/Program.cs +++ b/Monorail/Monorail/Program.cs @@ -1,3 +1,12 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Extensions.Logging; +using System.Configuration; +using Serilog.Settings.AppSettings; +using Serilog.Settings.Xml; +using Serilog.Sinks.File; + namespace Monorail { internal static class Program @@ -11,7 +20,30 @@ namespace Monorail // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormMonorailCollection()); + + string logFolderPath = Path.Combine(AppContext.BaseDirectory, "Logs"); + string logFilePath = Path.Combine(logFolderPath, "monoraillog-{Date}.log"); + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day) + .CreateLogger(); + + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(Log.Logger); + }); } } } \ No newline at end of file diff --git a/Monorail/saveFileDialog.txt b/Monorail/saveFileDialog.txt new file mode 100644 index 0000000..19937ae --- /dev/null +++ b/Monorail/saveFileDialog.txt @@ -0,0 +1,2 @@ +MonorailStorage +two|100:100:White;;