From ffa3f822d9516e198dbfc798ec0918694707b161 Mon Sep 17 00:00:00 2001 From: Anna Date: Fri, 29 Dec 2023 20:25:33 +0400 Subject: [PATCH] laba 7 --- Airbus_Base/Airbus_Base.csproj | 12 ++++ .../Exceptions/AirplaneNotFoundException.cs | 19 ++++++ .../Exceptions/StorageOverflowException.cs | 19 ++++++ Airbus_Base/FormAirplaneCollection.cs | 61 +++++++++++++------ Airbus_Base/Generics/SetGeneric.cs | 28 ++++----- .../Generics/TheAirplaneGenericStorage.cs | 16 +++-- .../Generics/TheAirplanesGenericCollection.cs | 10 ++- Airbus_Base/Program.cs | 26 ++++++++ Airbus_Base/appsettings.json | 15 +++++ 9 files changed, 158 insertions(+), 48 deletions(-) create mode 100644 Airbus_Base/Exceptions/AirplaneNotFoundException.cs create mode 100644 Airbus_Base/Exceptions/StorageOverflowException.cs create mode 100644 Airbus_Base/appsettings.json diff --git a/Airbus_Base/Airbus_Base.csproj b/Airbus_Base/Airbus_Base.csproj index 13ee123..95b0eb3 100644 --- a/Airbus_Base/Airbus_Base.csproj +++ b/Airbus_Base/Airbus_Base.csproj @@ -8,6 +8,18 @@ enable + + + + + + + + + + + + True diff --git a/Airbus_Base/Exceptions/AirplaneNotFoundException.cs b/Airbus_Base/Exceptions/AirplaneNotFoundException.cs new file mode 100644 index 0000000..54175b4 --- /dev/null +++ b/Airbus_Base/Exceptions/AirplaneNotFoundException.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 Airbus_Base.Exceptions +{ + [Serializable] + internal class AirplaneNotFoundException : ApplicationException + { + public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public AirplaneNotFoundException() : base() { } + public AirplaneNotFoundException(string message) : base(message) { } + public AirplaneNotFoundException(string message, Exception exception) : base(message, exception) { } + protected AirplaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Airbus_Base/Exceptions/StorageOverflowException.cs b/Airbus_Base/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..9ff1be1 --- /dev/null +++ b/Airbus_Base/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 Airbus_Base.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/Airbus_Base/FormAirplaneCollection.cs b/Airbus_Base/FormAirplaneCollection.cs index 24db4a0..85a9e02 100644 --- a/Airbus_Base/FormAirplaneCollection.cs +++ b/Airbus_Base/FormAirplaneCollection.cs @@ -10,6 +10,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using Airbus_Base.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using Serilog; + namespace Airbus_Base { @@ -71,6 +76,7 @@ namespace Airbus_Base } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + Log.Information($"Добавлен набор: {textBoxStorageName.Text}"); } /// @@ -97,9 +103,10 @@ namespace Airbus_Base if (MessageBox.Show($"Удалить объект{listBoxObjects.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxObjects.SelectedItem.ToString() - ?? string.Empty); + string name = (listBoxObjects.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + Log.Information($"Удален набор: {name}"); } } @@ -121,18 +128,20 @@ namespace Airbus_Base } FormAirplaneConfig form = new(); form.Show(); - Action? airplaneDelegate = new((m) => + Action? airplaneDelegate = new((airplane) => { - bool isAdditionSuccessful = (obj + m); - if (isAdditionSuccessful) + try { + bool isAdditionSuccessful = obj + airplane; MessageBox.Show("Объект добавлен"); - m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); + airplane.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height); pictureBoxCollection.Image = obj.ShowTheAirplanes(); + Log.Information($"Добавлен объект в коллекцию {listBoxObjects.SelectedItem.ToString() ?? string.Empty}"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + Log.Warning($"Коллекция {listBoxObjects.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(airplaneDelegate); @@ -161,16 +170,23 @@ namespace Airbus_Base return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - - if (obj - pos != null) + try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + var isAdditionSuccessful = obj - pos; MessageBox.Show("Объект удален"); + Log.Information($"Удален объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowTheAirplanes(); } - else + catch (AirplaneNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + Log.Warning($"Не получилось удалить объект из коллекции {listBoxObjects.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); + } + catch (FormatException) + { + Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } @@ -203,13 +219,16 @@ namespace Airbus_Base { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { + _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + Log.Warning("Не удалось сохранить"); + MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -223,17 +242,21 @@ namespace Airbus_Base { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { + _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxObjects.Items.Add(collection); } + ReloadObjects(); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + Log.Warning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/Airbus_Base/Generics/SetGeneric.cs b/Airbus_Base/Generics/SetGeneric.cs index 707d9b2..fc0cc6d 100644 --- a/Airbus_Base/Generics/SetGeneric.cs +++ b/Airbus_Base/Generics/SetGeneric.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Airbus_Base.Exceptions; namespace Airbus_Base.Generics { @@ -42,15 +43,14 @@ namespace Airbus_Base.Generics /// /// Добавляемый самолёт /// - public bool Insert(T airplane) + public void Insert(T airplane) { if (_places.Count == _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); } Insert(airplane, 0); - return true; } /// @@ -59,15 +59,17 @@ namespace Airbus_Base.Generics /// Добавляемый самолёт /// Позиция /// - public bool Insert(T airplane, int position) + public void Insert(T airplane, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + if (_places.Count == _maxCount) { - return false; + throw new StorageOverflowException(_maxCount); + } + if (!(position >= 0 && position <= Count)) + { + throw new Exception("Неверная позиция для вставки"); } - _places.Insert(position, airplane); - return true; } /// @@ -75,15 +77,14 @@ namespace Airbus_Base.Generics /// /// /// - public bool Remove(int position) + public void Remove(int position) { - if (position < 0 || position >= Count) + if (!(position >= 0 && position < Count)) { - return false; + throw new AirplaneNotFoundException(position); } _places.RemoveAt(position); - return true; } /// @@ -95,7 +96,7 @@ namespace Airbus_Base.Generics { get { - if (position < 0 || position >= _maxCount) + if (!(position >= 0 && position < Count)) { return null; } @@ -111,7 +112,6 @@ namespace Airbus_Base.Generics } _places.Insert(position, value); - return; } } /// diff --git a/Airbus_Base/Generics/TheAirplaneGenericStorage.cs b/Airbus_Base/Generics/TheAirplaneGenericStorage.cs index 9d2796c..f52dc9c 100644 --- a/Airbus_Base/Generics/TheAirplaneGenericStorage.cs +++ b/Airbus_Base/Generics/TheAirplaneGenericStorage.cs @@ -62,7 +62,7 @@ namespace Airbus_Base.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -81,7 +81,7 @@ namespace Airbus_Base.Generics if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных для сохранения"); } string toWrite = $"AirplaneStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); @@ -93,7 +93,6 @@ namespace Airbus_Base.Generics sw.WriteLine(str); } } - return true; } /// @@ -101,11 +100,11 @@ namespace Airbus_Base.Generics /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new IOException("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -113,11 +112,11 @@ namespace Airbus_Base.Generics var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new IOException("Нет данных для загрузки"); } if (!strs[0].StartsWith("AirplaneStorage")) { - return false; + throw new IOException("Неверный формат данных"); } _airplaneStorages.Clear(); do @@ -137,7 +136,7 @@ namespace Airbus_Base.Generics { if (!(collection + airplane)) { - return false; + throw new IOException("Ошибка добавления в коллекцию"); } } } @@ -146,7 +145,6 @@ namespace Airbus_Base.Generics str = sr.ReadLine(); } while (str != null); } - return true; } /// diff --git a/Airbus_Base/Generics/TheAirplanesGenericCollection.cs b/Airbus_Base/Generics/TheAirplanesGenericCollection.cs index 2638cfd..725fafa 100644 --- a/Airbus_Base/Generics/TheAirplanesGenericCollection.cs +++ b/Airbus_Base/Generics/TheAirplanesGenericCollection.cs @@ -68,11 +68,12 @@ namespace Airbus_Base.Generics /// public static bool operator +(TheAirplanesGenericCollection collect, T? obj) { - if (obj == null) + if (obj == null || collect == null) { return false; } - return collect?._collection.Insert(obj) ?? false; + collect?._collection.Insert(obj); + return true; } /// @@ -84,10 +85,7 @@ namespace Airbus_Base.Generics public static T? operator -(TheAirplanesGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - { - collect._collection.Remove(pos); - } + collect._collection.Remove(pos); return obj; } diff --git a/Airbus_Base/Program.cs b/Airbus_Base/Program.cs index 9874a7c..7308870 100644 --- a/Airbus_Base/Program.cs +++ b/Airbus_Base/Program.cs @@ -1,3 +1,13 @@ +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; +using Serilog.Formatting.Json; +using Serilog.Configuration; + namespace Airbus_Base { internal static class Program @@ -11,6 +21,22 @@ namespace Airbus_Base // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + 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(); + Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormAirplaneCollection()); } } diff --git a/Airbus_Base/appsettings.json b/Airbus_Base/appsettings.json new file mode 100644 index 0000000..21a6582 --- /dev/null +++ b/Airbus_Base/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file -- 2.25.1