diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs index a53a145..7b8f605 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectCatamaran.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -31,39 +32,50 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { + //TODO: выброс ошибки, если выход за границы массива + if (position >= 0 && position < Count) { - return _collection[position]; + throw new PositionOutOfCollectionException(position); } - return null; + return _collection[position]; } public int Insert(T obj) { + //TODO: выброс ошибки, если переполнение + if (Count <= _maxCount) { - _collection.Add(obj); - return Count; + throw new CollectionOverflowException(Count); + } - return -1; + _collection.Add(obj); + return Count; + } + public int Insert(T obj, int position) { + //TODO: выброс ошибки, если переполнение + if (Count < _maxCount && position >= 0 && position < _maxCount) { - _collection.Insert(position, obj); - return position; + throw new CollectionOverflowException(Count); } - return -1; + _collection.Insert(position, obj); + return position; } public T Remove(int position) { + //TODO: выброс ошибки, если выход за границы массива + T temp = _collection[position]; if (position >= 0 && position < _maxCount) { - _collection.RemoveAt(position); - return temp; + throw new CollectionOverflowException(Count); } - return null; + _collection.RemoveAt(position); + return temp; } public IEnumerable GetItems() diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs index 7ce31df..153e49f 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectCatamaran.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -53,18 +54,26 @@ namespace ProjectCatamaran.CollectiongGenericObjects; } public T? Get(int position) { + //TODO: выброс ошибки, если выход за границы массива + // проверка позиции if (position >= _collection.Length || position < 0) { - return null; + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) + { + throw new ObjectNotFoundException(position); } return _collection[position]; } public int Insert(T obj) { + //TODO: выброс ошибки, если переполнение + // вставка в свободное место набора int index = 0; - while (index < _collection.Length) + while (index < _collection.Length - 1) { if (_collection[index] == null) { @@ -73,21 +82,26 @@ namespace ProjectCatamaran.CollectiongGenericObjects; } index++; } - return -1; + throw new CollectionOverflowException(Count); + } public int Insert(T obj, int position) { + //TODO: выброс ошибки, если переполнение + if (position >= _collection.Length || position < 0) - { return -1; } + { + throw new PositionOutOfCollectionException(position); + } if (_collection[position] == null) { _collection[position] = obj; return position; } - int index; + int index; for (index = position + 1; index < _collection.Length; ++index) { if (_collection[index] == null) @@ -105,12 +119,16 @@ namespace ProjectCatamaran.CollectiongGenericObjects; return position; } } - return -1; + throw new CollectionOverflowException(Count); } - public T Remove(int position) + public T? Remove(int position) { + //TODO: выброс ошибки, если выход за границы массива + if (position >= _collection.Length || position < 0) - { return null; } + { + throw new ObjectNotFoundException(position); + } T DrawningBoat = _collection[position]; _collection[position] = null; return DrawningBoat; diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs index 38ac934..85a7fb3 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/StorageCollection.cs @@ -1,9 +1,11 @@ using ProjectCatamaran.Drawnings; +using ProjectCatamaran.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectCatamaran.CollectiongGenericObjects; @@ -93,12 +95,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("В хранилище отсутствуют коллекции для сохранения"); + } @@ -144,7 +146,6 @@ public class StorageCollection } } - return true; } @@ -153,11 +154,11 @@ 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)) @@ -166,7 +167,7 @@ public class StorageCollection string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) - return false; + throw new Exception("В файле нет данных"); _storages.Clear(); @@ -183,7 +184,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -191,17 +192,24 @@ public class StorageCollection string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBoat() is T Truck) + if (elem?.CreateDrawningBoat() is T boat) { - if (collection.Insert(Truck) == -1) - return false; + try + { + if (collection.Insert(boat) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); + } } } - _storages.Add(record[0], collection); } } - return true; } /// diff --git a/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..b418cb6 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..6b5afca --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs b/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..50378b9 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCatamaran.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/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs index 0691440..7da5162 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs @@ -1,5 +1,7 @@ -using ProjectCatamaran.CollectiongGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectCatamaran.CollectiongGenericObjects; using ProjectCatamaran.Drawnings; +using ProjectCatamaran.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -9,6 +11,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectCatamaran; @@ -22,12 +25,19 @@ public partial class FormBoatCollection : Form /// /// Компания /// - private AbstractCompany? _company; + private AbstractCompany? _company = null; - public FormBoatCollection() + /// + /// Конструктор + /// + private readonly ILogger _logger; + + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// @@ -60,19 +70,24 @@ public partial class FormBoatCollection : Form /// private void SetBoat(DrawningBoat boat) { - if (_company == null || boat == null) + try { - return; + if (_company == null || boat == null) + { + return; + } + if (_company + boat != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBoxBoat.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + boat.GetDataForSave()); + } } - - if (_company + boat != -1) + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { - MessageBox.Show("объект добавлен"); - pictureBoxBoat.Image = _company.Show(); - } - else - { - MessageBox.Show("не удалось добавить объект"); + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -96,14 +111,19 @@ public partial class FormBoatCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxBoat.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxBoat.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -121,24 +141,32 @@ public partial class FormBoatCollection : Form DrawningBoat? boat = null; int counter = 100; - while (boat == null) + try { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (boat == null) { - break; + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + if (boat == null) + { + return; + } + FormCatamaran form = new() + { + SetBoat = boat + }; + form.ShowDialog(); } - if (boat == null) + catch (Exception ex) + { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormCatamaran form = new() - { - SetBoat = boat - }; - form.ShowDialog(); } /// @@ -170,16 +198,25 @@ public partial class FormBoatCollection : Form 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(); } @@ -196,13 +233,20 @@ public partial class FormBoatCollection : 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(); - } /// @@ -261,13 +305,16 @@ public partial class FormBoatCollection : 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); } } } @@ -281,14 +328,18 @@ public partial class FormBoatCollection : 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/ProjectCatamaran/ProjectCatamaran/Program.cs b/ProjectCatamaran/ProjectCatamaran/Program.cs index 59feea7..b055357 100644 --- a/ProjectCatamaran/ProjectCatamaran/Program.cs +++ b/ProjectCatamaran/ProjectCatamaran/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace ProjectCatamaran { internal static class Program @@ -11,7 +15,34 @@ namespace ProjectCatamaran // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// + /// 01 + /// + /// + 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.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj index 244387d..f24932a 100644 --- a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj +++ b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj @@ -8,6 +8,11 @@ enable + + + + + True @@ -23,4 +28,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/serilogConfig.json b/ProjectCatamaran/ProjectCatamaran/serilogConfig.json new file mode 100644 index 0000000..9cc4d12 --- /dev/null +++ b/ProjectCatamaran/ProjectCatamaran/serilogConfig.json @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file