diff --git a/Lab/CarNotFoundException.cs b/Lab/CarNotFoundException.cs new file mode 100644 index 0000000..594bc4d --- /dev/null +++ b/Lab/CarNotFoundException.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 Lab +{ + [Serializable] internal class CarNotFoundException : ApplicationException + { + public CarNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public CarNotFoundException() : base() { } + public CarNotFoundException(string message) : base(message) { } + public CarNotFoundException(string message, Exception exception) : base(message, exception) { } + protected CarNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/Lab/CarsGenericStorage.cs b/Lab/CarsGenericStorage.cs index 96b7a22..238d4b3 100644 --- a/Lab/CarsGenericStorage.cs +++ b/Lab/CarsGenericStorage.cs @@ -47,7 +47,7 @@ namespace Lab.Generics return null; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -66,37 +66,36 @@ namespace Lab.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine("CarStorage"); writer.Write(data.ToString()); - return true; } } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) { string checker = reader.ReadLine(); if (checker == null) - return false; + throw new Exception("Нет данных для загрузки"); if (!checker.StartsWith("CarStorage")) - return false; + throw new Exception("Неверный формат ввода"); _carStorages.Clear(); string strs; bool firstinit = true; while ((strs = reader.ReadLine()) != null) { if (strs == null && firstinit) - return false; + throw new Exception("Нет данных для загрузки"); if (strs == null ) break; firstinit = false; @@ -108,17 +107,19 @@ namespace Lab.Generics data?.CreateDrawTanker(_separatorForObject, _pictureWidth, _pictureHeight); if (car != null) { - if (!(collection + car)) + try {_ = collection + car; } + catch (CarNotFoundException e) { - return false; + throw e; } - } - - + catch (StorageOverflowException e) + { + throw e; + } + } } _carStorages.Add(name, collection); } - return true; } } diff --git a/Lab/CollectionsFrame.cs b/Lab/CollectionsFrame.cs index 4feb258..86af8d5 100644 --- a/Lab/CollectionsFrame.cs +++ b/Lab/CollectionsFrame.cs @@ -10,16 +10,20 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace Lab { public partial class CollectionsFrame : Form { private readonly CarsGenericStorage _storage; - public CollectionsFrame() + + private readonly ILogger _logger; + public CollectionsFrame(ILogger logger) { InitializeComponent(); _storage = new CarsGenericStorage(DrawTank.Width, DrawTank.Height); + _logger = logger; } private void ReloadObjects() { @@ -46,10 +50,12 @@ namespace Lab { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Пустое название набора"); return; } _storage.AddSet(SetTextBox.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор: {SetTextBox.Text}"); } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) @@ -61,14 +67,17 @@ namespace Lab { if (CollectionListBox.SelectedIndex == -1) { + _logger.LogWarning("Удаление невыбранного набора"); return; } - if (MessageBox.Show($"Удалить объект {CollectionListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, + string name = CollectionListBox.SelectedItem.ToString() ?? string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(CollectionListBox.SelectedItem.ToString() ?? string.Empty); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } @@ -78,16 +87,21 @@ namespace Lab var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { + _logger.LogWarning("Добавление пустого объекта"); return; } - if (obj + tanker) - { + try + { + _ = obj + tanker; + MessageBox.Show("Объект добавлен"); DrawTank.Image = obj.ShowCars(); + _logger.LogInformation($"Добавлен объект в набор {CollectionListBox.SelectedItem.ToString()}"); } - else + catch (Exception ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning($"{ex.Message} в наборе {CollectionListBox.SelectedItem.ToString()}"); } } private void ButtonAddCar_Click(object sender, EventArgs e) @@ -104,6 +118,7 @@ namespace Lab { if (CollectionListBox.SelectedIndex == -1) { + _logger.LogWarning("Удаление объекта из несуществующего набора"); return; } var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? @@ -118,14 +133,24 @@ namespace Lab return; } int pos = Convert.ToInt32(CarTextBox.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - DrawTank.Image = obj.ShowCars(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + DrawTank.Image = obj.ShowCars(); + _logger.LogInformation($"Удален объект из набора {CollectionListBox.SelectedItem.ToString()}"); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning($"Не удалось удалить объект из набора {CollectionListBox.SelectedItem.ToString()}"); + } } - else + catch (CarNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); + _logger.LogWarning($"{ex.Message} из набора {CollectionListBox.SelectedItem.ToString()}"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs @@ -147,13 +172,16 @@ namespace Lab { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } @@ -162,14 +190,17 @@ namespace Lab if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); ReloadObjects(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}"); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}"); } } } diff --git a/Lab/Lab.csproj b/Lab/Lab.csproj index 13ee123..8729984 100644 --- a/Lab/Lab.csproj +++ b/Lab/Lab.csproj @@ -8,6 +8,20 @@ enable + + + + + + + + + + + + + + True diff --git a/Lab/Laba1WithoutGit.csproj b/Lab/Laba1WithoutGit.csproj deleted file mode 100644 index 13ee123..0000000 --- a/Lab/Laba1WithoutGit.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - WinExe - net6.0-windows - enable - true - enable - - - - - True - True - Resources.resx - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - \ No newline at end of file diff --git a/Lab/Program.cs b/Lab/Program.cs index 5ea6184..e6dc91d 100644 --- a/Lab/Program.cs +++ b/Lab/Program.cs @@ -1,17 +1,42 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; namespace Lab { internal static class Program { - /// - /// The main entry point for the application. - /// [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 CollectionsFrame()); + 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/Lab/SetGeneric.cs b/Lab/SetGeneric.cs index 48cd770..c026c56 100644 --- a/Lab/SetGeneric.cs +++ b/Lab/SetGeneric.cs @@ -26,20 +26,18 @@ namespace Lab.Generics public bool Insert(T car, int position) { if (position < 0 || position >= _maxCount) - return false; + throw new CarNotFoundException(position); if (Count >= _maxCount) - return false; + throw new StorageOverflowException(position); _places.Insert(0, car); return true; } public bool Remove(int position) { - if (position < 0 || position > _maxCount) - return false; - if (position >= Count) - return false; + if (position < 0 || position > _maxCount || position >= Count) + throw new CarNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/Lab/StorageOverflowException.cs b/Lab/StorageOverflowException.cs new file mode 100644 index 0000000..984fe64 --- /dev/null +++ b/Lab/StorageOverflowException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Lab +{ + [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/Lab/appsettings.json b/Lab/appsettings.json new file mode 100644 index 0000000..18b762e --- /dev/null +++ b/Lab/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": "GasolineTanker" + } + } + } \ No newline at end of file