diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs index de42684..703d68e 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/AbstractCompany.cs @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth)*(_pictureHeight / (_placeSizeHeight + 60)); /// /// Конструктор @@ -70,7 +70,7 @@ public abstract class AbstractCompany /// public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) { - return company._collection.Remove(position); + return company._collection?.Remove(position) ?? null; } /// diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs index 45738a5..c7b9640 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/GarageService.cs @@ -1,4 +1,5 @@ using ProjectExcavator.Drawnings; +using ProjectExcavator.Exceptions; namespace ProjectExcavator.CollectionGenericObjects; @@ -35,6 +36,7 @@ internal class GarageService : AbstractCompany g.DrawLine(pen, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2 + _placeSizeHeight); } } + } protected override void SetObjectsPosition() @@ -42,18 +44,20 @@ internal class GarageService : AbstractCompany int LevelWidth = 0; int LevelHeight = 0; - - for (int i = 0; i < _collection?.Count; i++) - { - if (_collection.Get(i) != null) + for (int i = 0; i < _collection?.Count ; i++) + { + if(_collection?.Get(i)== null ) + { + return; + } + try { _collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPosition((_pictureWidth - 190) - _placeSizeWidth * LevelWidth, 20 + (_placeSizeHeight + 60) * LevelHeight); } - - if (LevelHeight + 1 > _pictureHeight / (_placeSizeHeight + 60)) + catch (ObjectNotFoundException) { - return; + break; } if (LevelWidth + 1 < _pictureWidth / _placeSizeWidth) @@ -65,6 +69,11 @@ internal class GarageService : AbstractCompany LevelWidth = 0; LevelHeight++; } + + if (LevelHeight >= _pictureHeight / (_placeSizeHeight + 60)) + { + return; + } } } } diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs index 220fad8..9289106 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectExcavator.CollectionGenericObjects; +using ProjectExcavator.Exceptions; + +namespace ProjectExcavator.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -42,14 +44,8 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - else - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + return _collection[position]; } public int Insert(T obj) @@ -57,9 +53,9 @@ public class ListGenericObjects : ICollectionGenericObjects //проверка, что не превышено максимальное количество элементов //вставка в конец набора - if (_collection.Count > _maxCount) + if (Count + 1 > MaxCount) { - return -1; + throw new CollectionOverflowException(); } _collection.Add(obj); return 1; @@ -72,11 +68,15 @@ public class ListGenericObjects : ICollectionGenericObjects // проверка позиции // вставка по позиции - if ((_collection.Count > _maxCount) || (position < 0 || position > Count)) + if (_collection.Count + 1 < _maxCount) { - return -1; + throw new CollectionOverflowException(); } - _collection.Insert(position, obj); + if (position > _collection.Count || position < 0) + { + throw new PositionOutOfCollectionException(); + } + _collection.Insert(position, obj); return 1; } @@ -85,10 +85,7 @@ public class ListGenericObjects : ICollectionGenericObjects // проверка позиции // удаление объекта из списка - if (position < 0 || position > Count) - { - return null; - } + if(position < 0 || position > Count) throw new PositionOutOfCollectionException(position); T? obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs index c3bd8fd..eabbc89 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -namespace ProjectExcavator.CollectionGenericObjects; +using ProjectExcavator.Exceptions; +namespace ProjectExcavator.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -52,7 +53,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (position < 0 || position > Count-1) { - return null; + throw new PositionOutOfCollectionException(position); } else { @@ -74,7 +75,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects //Ищется свободное место после этой позиции и идет вставка туда //если нет после, ищем до вставка - if (position >= Count || position < 0) return -1; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { @@ -105,7 +106,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects behind_position --; } - return -1; + throw new CollectionOverflowException(Count); } } @@ -115,10 +116,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects // Проверка позиции // Удаление объекта из массива, присвоив элементу массива значение null - if (position < 0 || _collection[position] == null || position > Count -1) + if (position < 0 || position >= Count) { - 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/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs index 7cfd96e..e8b773b 100644 --- a/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectExcavator/ProjectExcavator/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ -using ProjectExcavator.Drawnings; +using ProjectExcavator.Exceptions; +using ProjectExcavator.Drawnings; using System.Text; namespace ProjectExcavator.CollectionGenericObjects; @@ -103,11 +104,11 @@ public class StorageCollection /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) @@ -143,7 +144,6 @@ public class StorageCollection sb.Clear(); } } - return true; } /// @@ -151,19 +151,21 @@ public class StorageCollection /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); + if (str == null || str.Length == 0) + throw new ArgumentException("В файле нет данных"); if (str != _collectionKey.ToString()) - return false; + throw new InvalidDataException("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -176,7 +178,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -184,17 +186,22 @@ public class StorageCollection string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningTrackedVehicle() is T boat) + if (elem?.CreateDrawningTrackedVehicle() is T trackedVehicle) { - if (collection.Insert(boat) == -1) - return false; + try + { + if (collection.Insert(trackedVehicle) == -1) + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + } + catch (CollectionOverflowException ex) + { + throw new CollectionOverflowException("Коллекция переполнена", ex); + } } } _storages.Add(record[0], collection); } } - - return true; } /// diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/CollectionOverflowException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..4e67ce9 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectExcavator.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) { } +} diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/ObjectNotFoundException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..f71d8c0 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectExcavator.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) { } +} diff --git a/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs b/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..ff23179 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectExcavator.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) { } +} diff --git a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs index 58dc318..1fa4013 100644 --- a/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs +++ b/ProjectExcavator/ProjectExcavator/FormExcavatorCollection.cs @@ -1,6 +1,7 @@ -using ProjectExcavator.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectExcavator.CollectionGenericObjects; using ProjectExcavator.Drawnings; -using System.Windows.Forms; +using ProjectExcavator.Exceptions; namespace ProjectExcavator; /// @@ -13,6 +14,11 @@ public partial class FormExcavatorCollection : Form /// private readonly StorageCollection _storageCollection; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Компания /// @@ -21,10 +27,12 @@ public partial class FormExcavatorCollection : Form /// /// Конструктор /// - public FormExcavatorCollection() + public FormExcavatorCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -60,19 +68,25 @@ public partial class FormExcavatorCollection : 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(); + if (_company + trackedVehicle != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + trackedVehicle.GetDataForSave()); + } } - else + //catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { - MessageBox.Show("Не удалось добавить объект"); + MessageBox.Show("В коллекции превышено допустимое количество элементов:" ); + _logger.LogWarning($"Не удалось добавить объект: {ex.Message}"); } } @@ -85,21 +99,41 @@ public partial class FormExcavatorCollection : Form { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { + _logger.LogWarning("Удаление объекта из несуществующей коллекции"); return; } - 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 (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + throw new Exception("Входные данные отсутствуют"); + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект удален"); + } } - else + catch (PositionOutOfCollectionException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Удаление вне рамках коллекции"); + _logger.LogWarning($"Удаление объекта за пределами коллекции {pos} "); + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show("Объект по позиции " + pos + " не существует "); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -162,13 +196,12 @@ public partial class FormExcavatorCollection : Form /// private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены"); return; } - CollectionType collectionType = CollectionType.None; if (radioButtonMassive.Checked) { @@ -180,9 +213,8 @@ public partial class FormExcavatorCollection : Form } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text); RefreshListBoxItems(); - - } /// @@ -197,12 +229,22 @@ public partial class FormExcavatorCollection : 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()); + RefreshListBoxItems(); + _logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString()); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RefreshListBoxItems(); + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } /// @@ -263,13 +305,16 @@ public partial class FormExcavatorCollection : 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); } } } @@ -283,14 +328,17 @@ public partial class FormExcavatorCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); RefreshListBoxItems(); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectExcavator/ProjectExcavator/Program.cs b/ProjectExcavator/ProjectExcavator/Program.cs index 8be0f08..0fe8b31 100644 --- a/ProjectExcavator/ProjectExcavator/Program.cs +++ b/ProjectExcavator/ProjectExcavator/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace ProjectExcavator { internal static class Program @@ -11,7 +16,28 @@ namespace ProjectExcavator // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormExcavatorCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + 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}appSetting.json").Build()).CreateLogger()); + }); } } } \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj b/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj index 244387d..55f0bae 100644 --- a/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj +++ b/ProjectExcavator/ProjectExcavator/ProjectExcavator.csproj @@ -8,6 +8,14 @@ enable + + + + + + + + True @@ -23,4 +31,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectExcavator/ProjectExcavator/appSetting.json b/ProjectExcavator/ProjectExcavator/appSetting.json new file mode 100644 index 0000000..b947cc8 --- /dev/null +++ b/ProjectExcavator/ProjectExcavator/appSetting.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Applicatoin": "Sample" + } + } +} \ No newline at end of file