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..f2bd6ba 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; - readonly int countPlace = 21; - public FormMonorailCollection() + + private readonly ILogger _logger; + + readonly int countPlace = 22; + 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,23 @@ 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($"Добавлен монорельс"); + } + } + catch (StorageOverflowException ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning(ex.Message); } - else - { - MessageBox.Show("Не удалось добавить объект"); - } } private void ButtonRemoveMonorail_Click(object sender, EventArgs e) { @@ -135,24 +154,27 @@ EventArgs e) { return; } - int pos; - if (maskedTextBoxNumber.Text == "") - { - MessageBox.Show("Введите позицию элемента выше"); - return; - } - else + int pos = 0; + try { pos = Convert.ToInt32(maskedTextBoxNumber.Text); } - if (obj - pos != null) + catch (Exception) { + MessageBox.Show("Введите позицию монорельса", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try { + var curObj = obj - pos; MessageBox.Show("Объект удален"); pictureBoxCollection.Image = obj.ShowMonorails(); - } - else + _logger.LogInformation($"Объект удален по позиции: {pos}"); + }catch(MonorailNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось удалить объект по позиции {pos}"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -172,15 +194,18 @@ EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение файла"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не сохранилось: {ex.Message}"); } } } @@ -188,17 +213,20 @@ EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + ReloadObjects(); + _logger.LogInformation("Загрузка файла"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось. {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не загрузилось: {ex.Message}"); } - ReloadObjects(); } } } diff --git a/Monorail/Monorail/Generics/MonorailsGenericCollection.cs b/Monorail/Monorail/Generics/MonorailsGenericCollection.cs index 43b29fe..0a05c67 100644 --- a/Monorail/Monorail/Generics/MonorailsGenericCollection.cs +++ b/Monorail/Monorail/Generics/MonorailsGenericCollection.cs @@ -37,10 +37,7 @@ namespace Monorail.Generics public static T? operator -(MonorailsGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return obj; } public U? GetU(int pos) diff --git a/Monorail/Monorail/Generics/MonorailsGenericStorage.cs b/Monorail/Monorail/Generics/MonorailsGenericStorage.cs index 5fa5bca..64dc5f7 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/Generics/SetGeneric.cs b/Monorail/Monorail/Generics/SetGeneric.cs index 755b4fb..b211434 100644 --- a/Monorail/Monorail/Generics/SetGeneric.cs +++ b/Monorail/Monorail/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using Monorail.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -23,15 +24,12 @@ namespace Monorail.Generics } public int Insert(T monorail, int position) { - if (Count == _maxCount) - return -1; + if (Count == _maxCount || position >= _maxCount) + throw new StorageOverflowException(Count); if (position < 0 || monorail == null) - return -1; - - if (position >= _maxCount) - return -1; - + throw new StorageOverflowException("Ошибка. Объект не найден или введённый " + + "номер позиции = отрицательное число"); if (Count == 0) { @@ -48,7 +46,7 @@ namespace Monorail.Generics // TODO проверка позиции if (position >= Count) { - return false; + throw new MonorailNotFoundException(position); } // TODO удаление объекта из массива, присвоив элементу массива значение null if (_places[position] != null) @@ -58,7 +56,7 @@ namespace Monorail.Generics } else { - return false; + throw new MonorailNotFoundException(position); } } public T? this[int position] 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