diff --git a/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs index a5adcbf..e729ac3 100644 --- a/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs +++ b/Lab1/Lab1/CollectionGenericObjects/AbstractCompany.cs @@ -36,7 +36,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) - 5; /// /// Конструктор @@ -97,8 +97,12 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningTruck? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningTruck? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (Exception) { } } return bitmap; diff --git a/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs index 09a304c..255ab4c 100644 --- a/Lab1/Lab1/CollectionGenericObjects/ListGenericObjects.cs +++ b/Lab1/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; @@ -29,46 +30,46 @@ where T : class /// Конструктор /// public ListGenericObjects() - { - _collection = new(); - } + { + _collection = new(); + } - public T? Get(int position) - { - // TODO проверка позиции - if (position >= Count || position < 0) return null; - return _collection[position]; - } + public T? Get(int position) + { + // TODO проверка позиции + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; + } - public int Insert(T obj) - { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count == _maxCount) return -1; - _collection.Add(obj); - return Count; - } + public int Insert(T obj) + { + // TODO проверка, что не превышено максимальное количество элементов + // TODO вставка в конец набора + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; + } - public int Insert(T obj, int position) - { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; - _collection.Insert(position, obj); - return position; - } + public int Insert(T obj, int position) + { + // TODO проверка, что не превышено максимальное количество элементов + // TODO проверка позиции + // TODO вставка по позиции + 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 >= Count || position < 0) return null; - T obj = _collection[position]; - _collection.RemoveAt(position); - return obj; - } + public T Remove(int position) + { + // TODO проверка позиции + // TODO удаление объекта из списка + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; + } public IEnumerable GetItems() { diff --git a/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs b/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs index 326ff27..600e70d 100644 --- a/Lab1/Lab1/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/Lab1/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; @@ -49,8 +50,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции - 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]; } @@ -68,7 +69,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) @@ -79,7 +80,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects // если нет после, ищем до // TODO вставка if (position >= _collection.Length || position < 0) - { return -1; } + { throw new PositionOutOfCollectionException(position); } if (_collection[position] == null) { @@ -105,7 +106,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects return position; } } - return -1; + throw new CollectionOverflowException(Count); } public T Remove(int position) @@ -113,7 +114,9 @@ public class MassiveGenericObjects : ICollectionGenericObjects // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null if (position >= _collection.Length || position < 0) - { return null; } + { throw new PositionOutOfCollectionException(position); } + if (_collection[position] == null) + { throw new ObjectNotFoundException(position); } T obj = _collection[position]; _collection[position] = null; return obj; diff --git a/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs b/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs index c308fe3..23db620 100644 --- a/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs +++ b/Lab1/Lab1/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using Lab1.Drawnings; +using Lab1.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -95,11 +96,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } @@ -145,7 +146,6 @@ public class StorageCollection } } - return true; } /// @@ -158,12 +158,12 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { //проверяем существования файла с заданным именем if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение @@ -174,7 +174,7 @@ public class StorageCollection string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - return false; + throw new Exception("В файле неверные данные"); //прочитываем первуя строку файла, и если она не совпадает с значением _collectionKey, возвращаем false _storages.Clear(); @@ -196,7 +196,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } //находим тип коллекции, создаем её экземпляр и если коллекция пустая, возвращаем false. @@ -206,10 +206,19 @@ public class StorageCollection string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTruck() is T Truck) + if (elem?.CreateDrawningTruck() is T ship) { - if (collection.Insert(Truck) == -1) - return false; + try + { + if (collection.Insert(ship) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } //элементы из строки записи добавляем в коллекцию, проверяем, является ли каждый элемент объектом типа T, и, @@ -219,8 +228,6 @@ public class StorageCollection //Загруженную коллекцию добавляем в хранилище с ключом, извлеченным из записи. } } - return true; - //после успешной загрузки всех данных возвращаем true. } diff --git a/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs b/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs index 3d1e54a..da5c47b 100644 --- a/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs +++ b/Lab1/Lab1/CollectionGenericObjects/TruckPark.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics.Metrics; using System.Linq; using System.Text; using System.Threading.Tasks; using Lab1.Drawnings; +using Lab1.Exceptions; + namespace Lab1.CollectionGenericObjects; public class TruckPark : AbstractCompany @@ -35,13 +38,25 @@ public class TruckPark : AbstractCompany //TO DO protected override void SetObjectsPosition() { + int count = 0; for (int y = 5; y + 50 < _pictureHeight; y += 90) { for (int x = 5; x + 200 < _pictureWidth; x += _placeSizeHeight + 90) { - _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(count)?.SetPosition(x, y); + //_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); + //_collection?.Get(count)?.SetPosition(x, y); + //count++; + if (count < _collection?.Count) + { + try + { + _collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(count)?.SetPosition(x, y); + } + catch (ObjectNotFoundException) { } + } + count++; } } diff --git a/Lab1/Lab1/Exceptions/CollectionOverflowException.cs b/Lab1/Lab1/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..c45c749 --- /dev/null +++ b/Lab1/Lab1/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace Lab1.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/Lab1/Lab1/Exceptions/ObjectNotFoundException.cs b/Lab1/Lab1/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..0fc28e8 --- /dev/null +++ b/Lab1/Lab1/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + + +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/Lab1/Lab1/Exceptions/PositionOutOfCollectionException.cs b/Lab1/Lab1/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..d024395 --- /dev/null +++ b/Lab1/Lab1/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +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/Lab1/Lab1/FormTruckCollection.cs b/Lab1/Lab1/FormTruckCollection.cs index 95188ce..fcf135a 100644 --- a/Lab1/Lab1/FormTruckCollection.cs +++ b/Lab1/Lab1/FormTruckCollection.cs @@ -1,6 +1,8 @@ using Lab1.CollectionGenericObjects; using Lab1.Drawnings; +using Lab1.Exceptions; using Lab1.MovementStrategy; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -24,13 +26,20 @@ public partial class FormTruckCollection : Form /// AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormTruckCollection() + public FormTruckCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// Выбор компании @@ -56,19 +65,24 @@ public partial class FormTruckCollection : Form private void SetTruck(DrawningTruck? truck) { - if (_company == null || truck == null) + try { - return; + if (_company == null || truck == null) + { + return; + } + if (_company + truck != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + truck.GetDataForSave()); + } } - - if (_company + truck != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -83,24 +97,27 @@ public partial class FormTruckCollection : Form { return; } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + 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); } } - + /// /// Передача объекта в другую форму /// @@ -115,26 +132,27 @@ public partial class FormTruckCollection : Form DrawningTruck? truck = null; int counter = 100; - while (truck == null) + try { - truck = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (truck == null) { - break; + truck = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + FormRoadTrain form = new() + { + SetTruck = truck + }; + form.ShowDialog(); } - - if (truck == null) + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - - FormRoadTrain form = new() - { - SetTruck = truck - }; - form.ShowDialog(); } /// @@ -160,22 +178,29 @@ public partial class FormTruckCollection : Form { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + 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(); } /// /// Удаление коллекции @@ -193,12 +218,20 @@ public partial class FormTruckCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); } /// @@ -229,21 +262,19 @@ public partial class FormTruckCollection : Form MessageBox.Show("Коллекция не выбрана"); return; } - - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; } - switch (comboBoxSelectorCompany.Text) { case "Хранилище": _company = new TruckPark(pictureBox.Width, pictureBox.Height, collection); break; } - panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } @@ -252,13 +283,16 @@ public partial class FormTruckCollection : 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -267,14 +301,17 @@ public partial class FormTruckCollection : Form { 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("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/Lab1/Lab1/Lab1.csproj b/Lab1/Lab1/Lab1.csproj index e1a0735..e499e07 100644 --- a/Lab1/Lab1/Lab1.csproj +++ b/Lab1/Lab1/Lab1.csproj @@ -8,4 +8,15 @@ enable + + + + + + + + + + + \ No newline at end of file diff --git a/Lab1/Lab1/Program.cs b/Lab1/Lab1/Program.cs index 1fc53b0..cb229b7 100644 --- a/Lab1/Lab1/Program.cs +++ b/Lab1/Lab1/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; namespace Lab1 { internal static class Program @@ -11,7 +15,34 @@ 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 FormTruckCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + /// + /// DI + /// + /// + private static void ConfigureServices(ServiceCollection services) + { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/Lab1/Lab1/serilog.json b/Lab1/Lab1/serilog.json new file mode 100644 index 0000000..4652831 --- /dev/null +++ b/Lab1/Lab1/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "C:\\Users\\savel\\source\\repos\\ISEbd-11_Savelyev_P.Y._Simple\\Lab1\\log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file