diff --git a/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs b/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs index f16d879..b14a196 100644 --- a/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs +++ b/solution/lab1/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using lab1.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -39,9 +40,6 @@ public class ListGenericObjects : ICollectionGenericObjects public CollectionType GetCollectionType => CollectionType.List; - public int SetMaxCount { set => throw new NotImplementedException(); } - int ICollectionGenericObjects.SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - /// /// Конструктор /// @@ -50,26 +48,20 @@ public class ListGenericObjects : ICollectionGenericObjects _collection = new(); } - public T? Get(int position) { - if (position >= 0 && position < _collection.Count) - { - return _collection[position]; - } - return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора - if (_collection.Count <= _maxCount) - { - _collection.Add(obj); - return _collection.Count; - } - return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; + } public int Insert(T obj, int position) @@ -77,26 +69,22 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции - if (position >= 0 && position < _maxCount && _collection.Count <= _maxCount) - { - _collection.Insert(position, obj); - return position; - } - return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); + return position; } public T? Remove(int position) { // TODO проверка позиции // TODO удаление объекта из списка - if (position < 0 || position > _maxCount) - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); T temp = _collection[position]; _collection.RemoveAt(position); return temp; } + public IEnumerable GetItems() { for (int i = 0; i < Count; ++i) diff --git a/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs b/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs index 1980391..ade487e 100644 --- a/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/solution/lab1/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using lab1.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -39,8 +40,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects public CollectionType GetCollectionType => CollectionType.Massive; - public int SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - /// /// Конструктор @@ -52,7 +51,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // проверка позиции - if (position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } @@ -69,7 +69,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) @@ -105,14 +105,15 @@ public class MassiveGenericObjects : ICollectionGenericObjects } index--; } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null - if (position >= _collection.Length || position < 0) return null; + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); T temp = _collection[position]; _collection[position] = null; return temp; diff --git a/solution/lab1/CollectionGenericObjects/StorageCollection.cs b/solution/lab1/CollectionGenericObjects/StorageCollection.cs index cee9430..9545a48 100644 --- a/solution/lab1/CollectionGenericObjects/StorageCollection.cs +++ b/solution/lab1/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using lab1.Drawnings; +using lab1.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -95,12 +96,12 @@ public class StorageCollection /// Сохранение информации по штурмовику в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствует коллекция для сохранения"); } if (File.Exists(filename)) { @@ -133,30 +134,30 @@ public class StorageCollection writer.Write(_separatorItems); } } - return true; + } } /// /// Загрузка информации по штурмовику в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; @@ -171,7 +172,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -179,17 +180,29 @@ public class StorageCollection { if (elem?.CreateDrawningEntityFighter() is T fighter) { - if (collection.Insert(fighter) == -1) + try { - return false; + if (collection.Insert(fighter) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию" + record[3]); + } } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } + + } + } _storages.Add(record[0], collection); } - return true; + } - } + + +} /// /// Создание коллекции по типу /// diff --git a/solution/lab1/CollectionGenericObjects/TrackedVehicleSharingService.cs b/solution/lab1/CollectionGenericObjects/TrackedVehicleSharingService.cs index a7432ea..19ef884 100644 --- a/solution/lab1/CollectionGenericObjects/TrackedVehicleSharingService.cs +++ b/solution/lab1/CollectionGenericObjects/TrackedVehicleSharingService.cs @@ -12,6 +12,12 @@ public class TrackedVehicleSharingService : AbstractCompany public TrackedVehicleSharingService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) { } + + internal static int getAmountOfObjects() + { + throw new NotImplementedException(); + } + /// /// Вывод заднего фона /// diff --git a/solution/lab1/Exceptions/CollectionOverflowExeption.cs b/solution/lab1/Exceptions/CollectionOverflowExeption.cs new file mode 100644 index 0000000..a68c85a --- /dev/null +++ b/solution/lab1/Exceptions/CollectionOverflowExeption.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace lab1.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + + +} diff --git a/solution/lab1/Exceptions/ObjectNotFoundException.cs b/solution/lab1/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..ba7ef96 --- /dev/null +++ b/solution/lab1/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace lab1.Exceptions; +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + +} \ No newline at end of file diff --git a/solution/lab1/Exceptions/PositionOutOfCollectionException.cs b/solution/lab1/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..10b16c0 --- /dev/null +++ b/solution/lab1/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace lab1.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/solution/lab1/FormTrackedVehicleCollection.cs b/solution/lab1/FormTrackedVehicleCollection.cs index ec9b14c..5d9d446 100644 --- a/solution/lab1/FormTrackedVehicleCollection.cs +++ b/solution/lab1/FormTrackedVehicleCollection.cs @@ -1,5 +1,8 @@ using lab1.CollectionGenericObjects; using lab1.Drawnings; +using lab1.Exceptions; +using Microsoft.Extensions.Logging; +using System.Collections.Generic; namespace lab1; /// @@ -12,6 +15,10 @@ public partial class FormTrackedVehicleCollection : Form /// Хранилище коллекций /// private readonly StorageCollection _storageCollection; + /// Логер + /// + private readonly ILogger _logger; + /// /// Компания /// @@ -20,10 +27,12 @@ public partial class FormTrackedVehicleCollection : Form /// /// Конструктор /// - public FormTrackedVehicleCollection() + public FormTrackedVehicleCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// Выбор компании @@ -57,19 +66,24 @@ public partial class FormTrackedVehicleCollection : Form /// private void SetTrackedVehicle(DrawningTrackedVehicle trackedVehicle) { - if (_company == null || trackedVehicle == null) + try { - return; + if (_company == null || trackedVehicle == null) + { + return; + } + if (_company + trackedVehicle != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект:" + trackedVehicle.GetDataForSave); + } } - - if (_company + trackedVehicle >= 0) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -80,10 +94,6 @@ public partial class FormTrackedVehicleCollection : Form /// private void ButtonRemoveTrackedVehicle_Click(object sender, EventArgs e) { - if (_company == null) - { - return; - } if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; @@ -93,14 +103,20 @@ public partial class FormTrackedVehicleCollection : Form return; } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + int tempSize = TrackedVehicleSharingService.getAmountOfObjects(); + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции" + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } /// @@ -117,24 +133,28 @@ public partial class FormTrackedVehicleCollection : Form } DrawningTrackedVehicle? fighter = null; int counter = 100; - while (fighter == null) + try { - fighter = _company.GetRandomObject(); - counter--; - if (counter <= 0) + + while (fighter == null) { - break; + fighter = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + FormFighter form = new(); + { + SetTrackedVehicle(fighter); + }; + form.ShowDialog(); } - if (fighter == null) + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormFighter form = new() - { - SetTrackedVehicle = fighter - }; - form.ShowDialog(); } @@ -185,19 +205,26 @@ public partial class FormTrackedVehicleCollection : Form MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена" + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); - } /// /// Удаление коллекции @@ -210,14 +237,25 @@ public partial class FormTrackedVehicleCollection : Form // нужно убедиться, что есть выбранная коллекция // спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись // удалить и обновить ListBox - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { + MessageBox.Show("Коллекция не выбрана"); return; } - if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty)) - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty); - - RerfreshListBoxItems(); + try + { + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция:" + listBoxCollection.SelectedItem.ToString() + "удалена"); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// @@ -273,19 +311,24 @@ public partial class FormTrackedVehicleCollection : Form // TODO продумать логику if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Загрузка не удалась", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } } + /// /// Обработка нажатия "Сохранение" /// @@ -295,17 +338,20 @@ public partial class FormTrackedVehicleCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } + } } } - diff --git a/solution/lab1/Program.cs b/solution/lab1/Program.cs index 53acbe8..5dafb44 100644 --- a/solution/lab1/Program.cs +++ b/solution/lab1/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using System; + namespace lab1 { internal static class Program @@ -10,8 +13,29 @@ namespace lab1 { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); - Application.Run(new FormTrackedVehicleCollection()); + ServiceCollection service = new(); + ConfigureServices(service); + using ServiceProvider serviceProvider = service.BuildServiceProvider(); + + Application.Run(serviceProvider.GetRequiredService()); + } + /// + /// Êîíôèãóðàöèÿ ñåðâèñà DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .WriteTo.File("log.txt") + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/solution/lab1/lab1.csproj b/solution/lab1/lab1.csproj index 244387d..d11a7da 100644 --- a/solution/lab1/lab1.csproj +++ b/solution/lab1/lab1.csproj @@ -8,6 +8,10 @@ enable + + + + True