From 39ef9a866f029f43a39d62c53c2dff7836df6566 Mon Sep 17 00:00:00 2001 From: AlyonaFr <149268946+AlyonaFr@users.noreply.github.com> Date: Wed, 1 May 2024 23:07:04 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ListGenericObjects.cs | 36 +++-- .../MassiveGenericObjects.cs | 36 +++-- .../StorageCollection.cs | 34 +++-- .../Exceptions/CollectionOverflowException.cs | 26 ++++ .../Exceptions/ObjectNotFoundException.cs | 25 ++++ .../PositionOutOfCollectionException.cs | 25 ++++ .../ProjectCatamaran/FormBoatCollection.cs | 141 ++++++++++++------ ProjectCatamaran/ProjectCatamaran/Program.cs | 33 +++- .../ProjectCatamaran/ProjectCatamaran.csproj | 11 ++ .../ProjectCatamaran/serilogConfig.json | 15 ++ 10 files changed, 302 insertions(+), 80 deletions(-) create mode 100644 ProjectCatamaran/ProjectCatamaran/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectCatamaran/ProjectCatamaran/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectCatamaran/ProjectCatamaran/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectCatamaran/ProjectCatamaran/serilogConfig.json 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 -- 2.25.1 From 43d87b33f59ea62d2088a487e86d6da28fc9400c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D1=91=D0=BD=D0=B0=20=D0=A4=D1=80=D0=BE=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0?= Date: Thu, 16 May 2024 04:12:06 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=BA=D0=BE=D1=80=D1=80=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D0=B8=D1=80=D0=BE=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 15 ++- .../BoatHarborService.cs | 39 ++++---- .../ListGenericObjects.cs | 34 ++----- .../MassiveGenericObjects.cs | 93 +++++++++---------- ProjectCatamaran/ProjectCatamaran/Program.cs | 53 +++++------ .../ProjectCatamaran/ProjectCatamaran.csproj | 5 +- .../ProjectCatamaran/serilogConfig.json | 35 ++++--- 7 files changed, 133 insertions(+), 141 deletions(-) diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs index 0bdeb11..b290193 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectCatamaran.Drawnings; +using ProjectCatamaran.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -32,7 +33,8 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// -private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); + /// /// Конструктор /// @@ -88,8 +90,15 @@ private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _ SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } return bitmap; } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs index bddbc58..288b017 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/BoatHarborService.cs @@ -1,4 +1,5 @@ using ProjectCatamaran.Drawnings; +using ProjectCatamaran.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -27,14 +28,14 @@ public class BoatHarborService : AbstractCompany { int width = _pictureWidth / _placeSizeWidth; int height = _pictureHeight / _placeSizeHeight; - Pen pen = new(Color.Black, 4); - for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + Pen pen = new(Color.Black, 2); + for (int i = 0; i < width + 1; i++) { - for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) + for (int j = 0; j < height + 1; ++j) { - g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + 5, i * _placeSizeWidth + _placeSizeWidth - 90, j * _placeSizeHeight + 5); + g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight); + g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight); } - g.DrawLine(pen, i * _placeSizeWidth,0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight + 5); } } @@ -48,23 +49,27 @@ public class BoatHarborService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5); } + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } + if (curWidth < width - 1) - curWidth++; - else - { - curWidth = 0; - curHeight--; - } - if (curHeight < 0) - { - return; - } - } + curWidth++; + else + { + curWidth = 0; + curHeight--; + } + if (curHeight < 0) + { + return; + } + + } } } diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs index 7b8f605..7e700ea 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/ListGenericObjects.cs @@ -32,23 +32,12 @@ public class ListGenericObjects : ICollectionGenericObjects } public T? Get(int position) { - //TODO: выброс ошибки, если выход за границы массива - - if (position >= 0 && position < Count) - { - throw new PositionOutOfCollectionException(position); - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - //TODO: выброс ошибки, если переполнение - - if (Count <= _maxCount) - { - throw new CollectionOverflowException(Count); - - } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; @@ -56,26 +45,17 @@ public class ListGenericObjects : ICollectionGenericObjects public int Insert(T obj, int position) { - //TODO: выброс ошибки, если переполнение - - if (Count < _maxCount && position >= 0 && position < _maxCount) - { - throw new CollectionOverflowException(Count); - } + 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: выброс ошибки, если выход за границы массива - - T temp = _collection[position]; - if (position >= 0 && position < _maxCount) - { - throw new CollectionOverflowException(Count); - } + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } public IEnumerable GetItems() diff --git a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs index 153e49f..2666ad8 100644 --- a/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs +++ b/ProjectCatamaran/ProjectCatamaran/CollectiongGenericObjects/MassiveGenericObjects.cs @@ -54,84 +54,77 @@ namespace ProjectCatamaran.CollectiongGenericObjects; } public T? Get(int position) { - //TODO: выброс ошибки, если выход за границы массива - - // проверка позиции - if (position >= _collection.Length || position < 0) - { - throw new PositionOutOfCollectionException(position); - } - if (_collection[position] == null) - { - throw new ObjectNotFoundException(position); - } + if (position < 0 || position >= Count) 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 - 1) + // вставка в свободное место набора + for (int i = 0; i < Count; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return i; } - index++; } + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - //TODO: выброс ошибки, если переполнение + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - - if (position >= _collection.Length || position < 0) + if (_collection[position] != null) { - throw new PositionOutOfCollectionException(position); - } - if (_collection[position] == null) - { - _collection[position] = obj; - return position; - } + bool pushed = false; - int index; - for (index = position + 1; index < _collection.Length; ++index) - { - if (_collection[index] == null) + int index; + for (index = position + 1; index < _collection.Length; index++) { - _collection[position] = obj; - return position; + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } } - } - for (index = position - 1; index >= 0; --index) - { - if (_collection[index] == null) + if (!pushed) { - _collection[position] = obj; - return position; + + for (index = position - 1; index >= 0; index--) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } } + if (!pushed) + { + throw new CollectionOverflowException(Count); + } + } - throw new CollectionOverflowException(Count); + _collection[position] = obj; + return position; } public T? Remove(int position) { - //TODO: выброс ошибки, если выход за границы массива + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (position >= _collection.Length || position < 0) - { - throw new ObjectNotFoundException(position); - } - T DrawningBoat = _collection[position]; + if (_collection[position] == null) throw new ObjectNotFoundException(position); + T temp = _collection[position]; _collection[position] = null; - return DrawningBoat; + return temp; } public IEnumerable GetItems() diff --git a/ProjectCatamaran/ProjectCatamaran/Program.cs b/ProjectCatamaran/ProjectCatamaran/Program.cs index b055357..46bb482 100644 --- a/ProjectCatamaran/ProjectCatamaran/Program.cs +++ b/ProjectCatamaran/ProjectCatamaran/Program.cs @@ -1,34 +1,32 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using Serilog; -namespace ProjectCatamaran + +namespace ProjectCatamaran; + +internal static class Program { - internal static class Program + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - - ServiceCollection services = new(); - ConfigureServices(services); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); Application.Run(serviceProvider.GetRequiredService()); } + } - /// - /// 01 - /// - /// - private static void ConfigureServices(ServiceCollection services) + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => { - string[] path = Directory.GetCurrentDirectory().Split('\\'); string pathNeed = ""; for (int i = 0; i < path.Length - 3; i++) @@ -36,13 +34,12 @@ namespace ProjectCatamaran pathNeed += path[i] + "\\"; } - - services.AddSingleton() - .AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); - }); - } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true) + .Build(); + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(logger); + }); } } \ No newline at end of file diff --git a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj index f24932a..277d423 100644 --- a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj +++ b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj @@ -9,8 +9,11 @@ + + - + + diff --git a/ProjectCatamaran/ProjectCatamaran/serilogConfig.json b/ProjectCatamaran/ProjectCatamaran/serilogConfig.json index 9cc4d12..63d86d9 100644 --- a/ProjectCatamaran/ProjectCatamaran/serilogConfig.json +++ b/ProjectCatamaran/ProjectCatamaran/serilogConfig.json @@ -1,15 +1,20 @@ - - - - - - - - - - - - - \ No newline at end of file +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Catamaran" + } + } +} \ No newline at end of file -- 2.25.1 From 53b04bf136ffa827dc5a63eb24252034a298c4bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D1=91=D0=BD=D0=B0=20=D0=A4=D1=80=D0=BE=D0=BB?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0?= Date: Thu, 16 May 2024 09:12:06 +0400 Subject: [PATCH 3/3] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectCatamaran/FormBoatCollection.cs | 43 +++++++++---------- .../ProjectCatamaran/ProjectCatamaran.csproj | 7 ++- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs index 7da5162..e4da5eb 100644 --- a/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs +++ b/ProjectCatamaran/ProjectCatamaran/FormBoatCollection.cs @@ -70,24 +70,22 @@ public partial class FormBoatCollection : Form /// private void SetBoat(DrawningBoat boat) { - try + if (_company == null || boat == null) + { + return; + } + try { - if (_company == null || boat == null) - { - return; - } - if (_company + boat != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBoxBoat.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + boat.GetDataForSave()); - } + var res = _company + boat; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBoxBoat.Image = _company.Show(); } - catch (ObjectNotFoundException) { } - catch (CollectionOverflowException ex) + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -113,17 +111,16 @@ public partial class FormBoatCollection : Form int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBoxBoat.Image = _company.Show(); - _logger.LogInformation("Удален объект по позиции " + pos); - } + var res = _company - pos; + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); + pictureBoxBoat.Image = _company.Show(); } catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } diff --git a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj index 277d423..8397199 100644 --- a/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj +++ b/ProjectCatamaran/ProjectCatamaran/ProjectCatamaran.csproj @@ -10,10 +10,13 @@ - - + + + + + -- 2.25.1