diff --git a/lab1/ElectricLocomotive.csproj b/lab1/ElectricLocomotive.csproj index 7c4e5c4..ee9b493 100644 --- a/lab1/ElectricLocomotive.csproj +++ b/lab1/ElectricLocomotive.csproj @@ -20,4 +20,24 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lab1/Exceptions/LocoNotFoundException.cs b/lab1/Exceptions/LocoNotFoundException.cs new file mode 100644 index 0000000..02d1104 --- /dev/null +++ b/lab1/Exceptions/LocoNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ElectricLocomotive.Exceptions; + +public class LocoNotFoundException : ApplicationException +{ + public LocoNotFoundException(int i) : base($"Не найден объект попозиции {i}") { } + public LocoNotFoundException() : base() { } + public LocoNotFoundException(string message) : base(message) { } + public LocoNotFoundException(string message, Exception exception) : + base(message, exception) { } + protected LocoNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/lab1/Exceptions/StorageOverflowException.cs b/lab1/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..c3a3358 --- /dev/null +++ b/lab1/Exceptions/StorageOverflowException.cs @@ -0,0 +1,17 @@ +using System.Runtime.Serialization; + + +namespace ElectricLocomotive.Exceptions; + +[Serializable] +public 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) { } +} \ No newline at end of file diff --git a/lab1/FormLocomotivCollection.cs b/lab1/FormLocomotivCollection.cs index e231097..8c813ce 100644 --- a/lab1/FormLocomotivCollection.cs +++ b/lab1/FormLocomotivCollection.cs @@ -1,4 +1,6 @@ using System.Windows.Forms; +using ElectricLocomotive.Exceptions; +using Serilog; namespace ElectricLocomotive; @@ -35,14 +37,18 @@ public partial class FormLocomotivCollection : Form { FormLocoConfig form = new(); form.Show(); Action? monorailDelegate = new((m) => { - bool q = (obj + m); - if (q) { + try + { + bool q = obj + m; MessageBox.Show("Объект добавлен"); + Log.Information($"Добавлен объект в коллекцию {storageListBox.SelectedItem.ToString() ?? string.Empty}"); m.ChangePictureBoxSize(collectionPictureBox.Width, collectionPictureBox.Height); collectionPictureBox.Image = obj.ShowLocos(); } - else { - MessageBox.Show("Не удалось добавить объект"); + catch (StorageOverflowException ex) + { + Log.Warning($"Коллекция {storageListBox.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(monorailDelegate); @@ -60,13 +66,24 @@ public partial class FormLocomotivCollection : Form { MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = Convert.ToInt32(locoIndexInput.Text); - if (obj - pos != null) { + + try + { + int pos = Convert.ToInt32(locoIndexInput.Text); + var q = obj - pos; MessageBox.Show("Объект удален"); + Log.Information($"Удален объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); collectionPictureBox.Image = obj.ShowLocos(); } - else { - MessageBox.Show("Не удалось удалить объект"); + catch(LocoNotFoundException ex) + { + Log.Warning($"Не получилось удалить объект из коллекции {storageListBox.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); + } + catch(FormatException ex) + { + Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } @@ -92,9 +109,10 @@ public partial class FormLocomotivCollection : Form { } if (MessageBox.Show($"Удалить объект{storageListBox.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(storageListBox.SelectedItem.ToString() - ?? string.Empty); + string name = storageListBox.SelectedItem.ToString() ?? string.Empty; + _storage.DelSet(name); ReloadObjects(); + Log.Information($"Удален набор: {name}"); } } @@ -107,33 +125,46 @@ public partial class FormLocomotivCollection : Form { } _storage.AddSet(storageIndexInput.Text); ReloadObjects(); + Log.Information($"Добавлен набор: {storageIndexInput.Text}"); } private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { 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 { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) + { + Log.Warning("Не удалось сохранить"); + MessageBox.Show($"Не сохранилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { if (loadFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(loadFileDialog.FileName)) { + try + { + _storage.LoadData(loadFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - foreach (var collection in _storage.Keys) { + Log.Information($"Файл {loadFileDialog.FileName} успешно загружен"); + foreach (var collection in _storage.Keys) + { storageListBox.Items.Add(collection); } + ReloadObjects(); } - else { - MessageBox.Show("Не загрузилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + catch (Exception ex) + { + Log.Warning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/lab1/Generics/LocosGenericCollection.cs b/lab1/Generics/LocosGenericCollection.cs index a0b349c..11a8aea 100644 --- a/lab1/Generics/LocosGenericCollection.cs +++ b/lab1/Generics/LocosGenericCollection.cs @@ -28,10 +28,7 @@ public class LocosGenericCollection where T : DrawingLocomotiv where U : 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/lab1/Generics/LocosGenericStorage.cs b/lab1/Generics/LocosGenericStorage.cs index 5d175ec..5026eea 100644 --- a/lab1/Generics/LocosGenericStorage.cs +++ b/lab1/Generics/LocosGenericStorage.cs @@ -65,7 +65,7 @@ public class LocosGenericStorage if (data.Length == 0) { - return false; + throw new Exception("Невалиданя операция, нет данных длясохранения"); } string toWrite = $"LocoStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, @@ -84,7 +84,7 @@ public class LocosGenericStorage { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { @@ -93,11 +93,11 @@ public class LocosGenericStorage StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { - return false; + throw new Exception("Нет данных для загрузки"); } if (!strs[0].StartsWith("LocoStorage")) { - return false; + throw new Exception("Неверный формат данных"); } _electricLocoStorages.Clear(); do @@ -121,7 +121,7 @@ public class LocosGenericStorage { if (!(collection + monorail)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } diff --git a/lab1/Generics/SetGeneric.cs b/lab1/Generics/SetGeneric.cs index 6141000..0ad1009 100644 --- a/lab1/Generics/SetGeneric.cs +++ b/lab1/Generics/SetGeneric.cs @@ -1,4 +1,6 @@ -namespace ElectricLocomotive; +using ElectricLocomotive.Exceptions; + +namespace ElectricLocomotive; public class SetGeneric where T : class { @@ -15,14 +17,17 @@ public class SetGeneric where T : class public bool Insert(T electricLocomotiv) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(electricLocomotiv, 0); return true; } public bool Insert(T electricLocomotiv, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + + if (!(position >= 0 && position <= Count)) return false; _places.Insert(position, electricLocomotiv); return true; @@ -31,7 +36,7 @@ public class SetGeneric where T : class public bool Remove(int position) { if (!(position >= 0 && position < Count)) - return false; + throw new LocoNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/lab1/Program.cs b/lab1/Program.cs index d457a45..a2f9d18 100644 --- a/lab1/Program.cs +++ b/lab1/Program.cs @@ -1,3 +1,5 @@ +using Serilog; + namespace ElectricLocomotive { internal static class Program @@ -8,9 +10,13 @@ namespace ElectricLocomotive [STAThread] static void Main() { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); + Log.Logger = new LoggerConfiguration() + .WriteTo.File("log.txt") + .MinimumLevel.Debug() + .CreateLogger(); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormLocomotivCollection()); } }