From 336b0a05fde1336e84d9d2a287e1f115b0190508 Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Wed, 6 Dec 2023 19:46:43 +0400 Subject: [PATCH 1/4] Lab7 --- Trolleybus/Trolleybus/BusNotFoundException.cs | 15 +++++ .../Trolleybus/BusesGenericCollection.cs | 6 +- Trolleybus/Trolleybus/BusesGenericStorage.cs | 20 ++++--- Trolleybus/Trolleybus/FormBusCollection.cs | 55 +++++++++++++------ Trolleybus/Trolleybus/Program.cs | 16 +++++- Trolleybus/Trolleybus/SetGeneric.cs | 21 ++++--- .../Trolleybus/StorageOverflowException.cs | 14 +++++ Trolleybus/Trolleybus/Trolleybus.csproj | 7 +++ 8 files changed, 114 insertions(+), 40 deletions(-) create mode 100644 Trolleybus/Trolleybus/BusNotFoundException.cs create mode 100644 Trolleybus/Trolleybus/StorageOverflowException.cs diff --git a/Trolleybus/Trolleybus/BusNotFoundException.cs b/Trolleybus/Trolleybus/BusNotFoundException.cs new file mode 100644 index 0000000..e0fc2ab --- /dev/null +++ b/Trolleybus/Trolleybus/BusNotFoundException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + + +namespace ProjectTrolleybus.Exceptions +{ + [Serializable] + internal class BusNotFoundException : ApplicationException + { + public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public BusNotFoundException() : base() { } + public BusNotFoundException(string message) : base(message) { } + public BusNotFoundException(string message, Exception exception) : base(message, exception) { } + protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} diff --git a/Trolleybus/Trolleybus/BusesGenericCollection.cs b/Trolleybus/Trolleybus/BusesGenericCollection.cs index 9fbd6f1..9d1db1f 100644 --- a/Trolleybus/Trolleybus/BusesGenericCollection.cs +++ b/Trolleybus/Trolleybus/BusesGenericCollection.cs @@ -55,7 +55,8 @@ namespace ProjectTrolleybus.Generics { if (obj == null || collect == null) return false; - return collect?._collection.Insert(obj) ?? false; + collect?._collection.Insert(obj); + return true; } /// /// Перегрузка оператора вычитания @@ -66,8 +67,7 @@ namespace ProjectTrolleybus.Generics public static T? operator -(BusesGenericCollection collect, int pos) { T? obj = collect._collection[pos]; - if (obj != null) - collect._collection.Remove(pos); + collect._collection.Remove(pos); return obj; } /// diff --git a/Trolleybus/Trolleybus/BusesGenericStorage.cs b/Trolleybus/Trolleybus/BusesGenericStorage.cs index 232012e..073dd0f 100644 --- a/Trolleybus/Trolleybus/BusesGenericStorage.cs +++ b/Trolleybus/Trolleybus/BusesGenericStorage.cs @@ -88,7 +88,7 @@ namespace ProjectTrolleybus.Generics /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (File.Exists(filename)) { @@ -107,24 +107,26 @@ namespace ProjectTrolleybus.Generics } if (data.Length == 0) { - return false; + throw new Exception("Невалидная операция, нет данных для сохранения"); + } using (StreamWriter streamWriter = new(filename)) { streamWriter.WriteLine($"BusStorages{Environment.NewLine}{data}"); } - return true; + return; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new IOException("Файл не найден"); + } using (StreamReader streamReader = new(filename)) { @@ -132,11 +134,11 @@ namespace ProjectTrolleybus.Generics var strings = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strings == null || strings.Length == 0) { - return false; + throw new IOException("Нет данных для загрузки"); } if (!strings[0].StartsWith("BusStorages")) { - return false; + throw new IOException("Неверный формат данных"); } _busStorages.Clear(); do @@ -156,7 +158,7 @@ namespace ProjectTrolleybus.Generics { if (!(collection + bus)) { - return false; + throw new Exception("Ошибка добавления в коллекцию"); } } } @@ -164,7 +166,7 @@ namespace ProjectTrolleybus.Generics str = streamReader.ReadLine(); } while (str != null); } - return true; + return; } } } diff --git a/Trolleybus/Trolleybus/FormBusCollection.cs b/Trolleybus/Trolleybus/FormBusCollection.cs index 9dad877..029a5ed 100644 --- a/Trolleybus/Trolleybus/FormBusCollection.cs +++ b/Trolleybus/Trolleybus/FormBusCollection.cs @@ -11,6 +11,10 @@ using ProjectTrolleybus.DrawingObjects; using ProjectTrolleybus.MovementStrategy; using ProjectTrolleybus.Generics; using ProjectTrolleybus; +using ProjectTrolleybus.Exceptions; +using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using Serilog; namespace ProjectTrolleybus { @@ -51,6 +55,7 @@ namespace ProjectTrolleybus } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + Log.Information($"Добавлен набор: {textBoxStorageName.Text}"); } private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { @@ -64,8 +69,10 @@ namespace ProjectTrolleybus } if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); + string name = (listBoxStorages.SelectedItem.ToString() ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + Log.Information($"Удален набор: {name}"); } } private void ButtonAddBus_Click(object sender, EventArgs e) @@ -83,14 +90,17 @@ namespace ProjectTrolleybus form.Show(); Action? busDelegate = new((bus) => { - if (obj + bus) + try { + var result = obj + bus; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowBuses(); + Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); } - else + catch (StorageOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); } }); form.AddEvent(busDelegate); @@ -111,15 +121,23 @@ namespace ProjectTrolleybus { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); + var result = obj - pos; MessageBox.Show("Объект удален"); + Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowBuses(); } - else + catch (BusNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + MessageBox.Show(ex.Message); ; + } + catch (FormatException ex) + { + Log.Warning($"Было введено не число"); + MessageBox.Show("Введите число"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -139,15 +157,17 @@ namespace ProjectTrolleybus { 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); } } } @@ -155,19 +175,22 @@ namespace ProjectTrolleybus { 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) { listBoxStorages.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/Trolleybus/Trolleybus/Program.cs b/Trolleybus/Trolleybus/Program.cs index 42d34a4..72b1bc7 100644 --- a/Trolleybus/Trolleybus/Program.cs +++ b/Trolleybus/Trolleybus/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using Serilog; + namespace ProjectTrolleybus { internal static class Program @@ -8,10 +13,15 @@ namespace ProjectTrolleybus [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.Run(new FormBusCollection()); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); } } -} \ No newline at end of file +} diff --git a/Trolleybus/Trolleybus/SetGeneric.cs b/Trolleybus/Trolleybus/SetGeneric.cs index 44bc8f6..3d44f87 100644 --- a/Trolleybus/Trolleybus/SetGeneric.cs +++ b/Trolleybus/Trolleybus/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using ProjectTrolleybus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -21,26 +22,28 @@ namespace ProjectTrolleybus.Generics _places = new List(count); } - public bool Insert(T trolleybus) + public void Insert(T trolleybus) { if (_places.Count == _maxCount) - return false; + throw new StorageOverflowException(_maxCount); Insert(trolleybus, 0); - return true; + return; } - public bool Insert(T trolleybus, int position) + public void Insert(T trolleybus, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) - return false; + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) + throw new Exception("Неверная позиция для вставки"); _places.Insert(position, trolleybus); - return true; + return; } public bool Remove(int position) { if (!(position >= 0 && position < Count)) - return false; + throw new BusNotFoundException(position); _places.RemoveAt(position); return true; } diff --git a/Trolleybus/Trolleybus/StorageOverflowException.cs b/Trolleybus/Trolleybus/StorageOverflowException.cs new file mode 100644 index 0000000..eb466a9 --- /dev/null +++ b/Trolleybus/Trolleybus/StorageOverflowException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectTrolleybus.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/Trolleybus/Trolleybus/Trolleybus.csproj b/Trolleybus/Trolleybus/Trolleybus.csproj index 13ee123..e568267 100644 --- a/Trolleybus/Trolleybus/Trolleybus.csproj +++ b/Trolleybus/Trolleybus/Trolleybus.csproj @@ -16,6 +16,13 @@ + + + + + + + ResXFileCodeGenerator -- 2.25.1 From 9fceaf0eed869057d15d5b3bd10329b676d1fb0a Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Wed, 6 Dec 2023 20:58:03 +0400 Subject: [PATCH 2/4] Lab7+ --- Trolleybus/Trolleybus/Program.cs | 16 +++++++++++++--- Trolleybus/Trolleybus/Trolleybus.csproj | 12 ++++++++++++ Trolleybus/Trolleybus/appsettings.json | 12 ++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 Trolleybus/Trolleybus/appsettings.json diff --git a/Trolleybus/Trolleybus/Program.cs b/Trolleybus/Trolleybus/Program.cs index 72b1bc7..cefc694 100644 --- a/Trolleybus/Trolleybus/Program.cs +++ b/Trolleybus/Trolleybus/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; @@ -14,14 +15,23 @@ namespace ProjectTrolleybus static void Main() { 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() - .WriteTo.File("log.txt") - .MinimumLevel.Debug() + .ReadFrom.Configuration(configuration) .CreateLogger(); - Application.Run(new FormBusCollection()); Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new FormBusCollection()); } } } diff --git a/Trolleybus/Trolleybus/Trolleybus.csproj b/Trolleybus/Trolleybus/Trolleybus.csproj index e568267..875313f 100644 --- a/Trolleybus/Trolleybus/Trolleybus.csproj +++ b/Trolleybus/Trolleybus/Trolleybus.csproj @@ -22,6 +22,18 @@ + + + + + + + + + + + + diff --git a/Trolleybus/Trolleybus/appsettings.json b/Trolleybus/Trolleybus/appsettings.json new file mode 100644 index 0000000..5e25ffb --- /dev/null +++ b/Trolleybus/Trolleybus/appsettings.json @@ -0,0 +1,12 @@ +{ + "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 From 0e533c7136d8353ef75d7f2d32acd0b8048d915d Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Wed, 6 Dec 2023 21:00:20 +0400 Subject: [PATCH 3/4] Lab7++ --- Trolleybus/Trolleybus/Trolleybus.csproj | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Trolleybus/Trolleybus/Trolleybus.csproj b/Trolleybus/Trolleybus/Trolleybus.csproj index 875313f..17266be 100644 --- a/Trolleybus/Trolleybus/Trolleybus.csproj +++ b/Trolleybus/Trolleybus/Trolleybus.csproj @@ -42,4 +42,10 @@ + + + Always + + + \ No newline at end of file -- 2.25.1 From 7678a196270a42e4e10ff1f5464beda52ecb94c0 Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Sat, 9 Dec 2023 10:26:29 +0400 Subject: [PATCH 4/4] Lab7 pull request --- Trolleybus/Trolleybus/BusesGenericStorage.cs | 6 ++---- Trolleybus/Trolleybus/FormBusCollection.cs | 6 +++--- Trolleybus/Trolleybus/Program.cs | 4 +++- Trolleybus/Trolleybus/SetGeneric.cs | 5 +---- Trolleybus/Trolleybus/Trolleybus.csproj | 7 ------- 5 files changed, 9 insertions(+), 19 deletions(-) diff --git a/Trolleybus/Trolleybus/BusesGenericStorage.cs b/Trolleybus/Trolleybus/BusesGenericStorage.cs index 073dd0f..e690b59 100644 --- a/Trolleybus/Trolleybus/BusesGenericStorage.cs +++ b/Trolleybus/Trolleybus/BusesGenericStorage.cs @@ -107,14 +107,13 @@ namespace ProjectTrolleybus.Generics } if (data.Length == 0) { - throw new Exception("Невалидная операция, нет данных для сохранения"); + throw new IOException("Невалидная операция, нет данных для сохранения"); } using (StreamWriter streamWriter = new(filename)) { streamWriter.WriteLine($"BusStorages{Environment.NewLine}{data}"); } - return; } /// /// Загрузка информации по автомобилям в хранилище из файла @@ -158,7 +157,7 @@ namespace ProjectTrolleybus.Generics { if (!(collection + bus)) { - throw new Exception("Ошибка добавления в коллекцию"); + throw new IOException("Ошибка добавления в коллекцию"); } } } @@ -166,7 +165,6 @@ namespace ProjectTrolleybus.Generics str = streamReader.ReadLine(); } while (str != null); } - return; } } } diff --git a/Trolleybus/Trolleybus/FormBusCollection.cs b/Trolleybus/Trolleybus/FormBusCollection.cs index 029a5ed..2f8ae47 100644 --- a/Trolleybus/Trolleybus/FormBusCollection.cs +++ b/Trolleybus/Trolleybus/FormBusCollection.cs @@ -92,7 +92,7 @@ namespace ProjectTrolleybus { try { - var result = obj + bus; + bool q = obj + bus; MessageBox.Show("Объект добавлен"); pictureBoxCollection.Image = obj.ShowBuses(); Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); @@ -124,7 +124,7 @@ namespace ProjectTrolleybus try { int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - var result = obj - pos; + var q = obj - pos; MessageBox.Show("Объект удален"); Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}"); pictureBoxCollection.Image = obj.ShowBuses(); @@ -134,7 +134,7 @@ namespace ProjectTrolleybus Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); MessageBox.Show(ex.Message); ; } - catch (FormatException ex) + catch (FormatException) { Log.Warning($"Было введено не число"); MessageBox.Show("Введите число"); diff --git a/Trolleybus/Trolleybus/Program.cs b/Trolleybus/Trolleybus/Program.cs index cefc694..4ff58e9 100644 --- a/Trolleybus/Trolleybus/Program.cs +++ b/Trolleybus/Trolleybus/Program.cs @@ -1,8 +1,10 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; using Serilog; +using Serilog.Events; +using Serilog.Formatting.Json; +using Serilog.Configuration; namespace ProjectTrolleybus { diff --git a/Trolleybus/Trolleybus/SetGeneric.cs b/Trolleybus/Trolleybus/SetGeneric.cs index 3d44f87..29c2c3f 100644 --- a/Trolleybus/Trolleybus/SetGeneric.cs +++ b/Trolleybus/Trolleybus/SetGeneric.cs @@ -27,7 +27,6 @@ namespace ProjectTrolleybus.Generics if (_places.Count == _maxCount) throw new StorageOverflowException(_maxCount); Insert(trolleybus, 0); - return; } public void Insert(T trolleybus, int position) @@ -37,15 +36,13 @@ namespace ProjectTrolleybus.Generics if (!(position >= 0 && position <= Count)) throw new Exception("Неверная позиция для вставки"); _places.Insert(position, trolleybus); - return; } - public bool Remove(int position) + public void Remove(int position) { if (!(position >= 0 && position < Count)) throw new BusNotFoundException(position); _places.RemoveAt(position); - return true; } public T? this[int position] diff --git a/Trolleybus/Trolleybus/Trolleybus.csproj b/Trolleybus/Trolleybus/Trolleybus.csproj index 17266be..640cb23 100644 --- a/Trolleybus/Trolleybus/Trolleybus.csproj +++ b/Trolleybus/Trolleybus/Trolleybus.csproj @@ -16,13 +16,6 @@ - - - - - - - -- 2.25.1