From 7f58bbb1ad0dd00ac22543f9c391e2eb970e3871 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 23:48:53 +0400 Subject: [PATCH 1/2] In process : solve log problem & add left exceptions --- .../CollectionGenericObj/ArrayGenObj.cs | 150 +++++++++++++----- .../CollectionGenericObj/ListGenObj.cs | 101 +++++++++--- .../CollectionGenericObj/StorageCollection.cs | 55 +++---- .../Exceptions/CollectionOverflowException.cs | 18 +++ .../Exceptions/ObjectNotFoundException.cs | 16 ++ .../PositionOutOfCollectionException.cs | 16 ++ ProjectCruiser/Program.cs | 29 +++- ProjectCruiser/ProjectCruiser.csproj | 10 ++ ProjectCruiser/ServiceForm2.cs | 62 ++++++-- ProjectCruiser/serilog.config | 13 ++ 10 files changed, 355 insertions(+), 115 deletions(-) create mode 100644 ProjectCruiser/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectCruiser/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectCruiser/serilog.config diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 5c56167..cf2297a 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,4 +1,6 @@  +using ProjectCruiser.Exceptions; + namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj @@ -36,74 +38,140 @@ public class ArrayGenObj : ICollectionGenObj // methods : public T? GetItem(int index) { - if (index > Count || index < 0) + try { + if (index > Count) + throw new CollectionOverflowException(index); + if (index < 0) + throw new PositionOutOfCollectionException(index); + + if (_collection[index] == null) + throw new ObjectNotFoundException(index); + + return _collection[index]; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return null; } - return _collection[index]; } public int Insert(T? item) { - if (Count >= _maxCount || item == null) + if (item == null) { return -1; } + + try // выход за границы, курируется CollectionOverflowException { + if (Count >= _maxCount) + { + throw new CollectionOverflowException(Count); + } + + // any empty place -> fill immediately + for (int i = 0; i < _collection.Length; i++) + { + if (_collection[i] == null) + { + _collection[i] = item; + return i; + } + } + return Count; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); return -1; } - - // any empty place -> fill immediately - for (int i = 0; i < _collection.Length; i++) - { - if (_collection[i] == null) - { - _collection[i] = item; - return i; - } - } - return Count; } public int Insert(T? item, int index) { - if (index >= _maxCount || Count >= _maxCount || - index < 0 || _collection[index] != null - || item == null) + try { - return -1; - } + if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - if (_collection[index] == null) - { - _collection[index] = item; - return index; - } + if (item == null) throw new ObjectNotFoundException(index); - int min_diff = 100, firstNullIndex = 100; - - for (int i = 0; i < Count; i++) - { - if (_collection[i] == null - && min_diff > Math.Abs(index - i)) + if (_collection[index] == null) { - min_diff = Math.Abs(index - i); - firstNullIndex = i; + _collection[index] = item; + return index; + } + else + { + int min_diff = 100, firstNullIndex = 100; + + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null && min_diff > Math.Abs(index - i)) + { + min_diff = Math.Abs(index - i); + firstNullIndex = i; + } + } + + _collection[firstNullIndex] = item; + return firstNullIndex; } } - - _collection[firstNullIndex] = item; - return firstNullIndex; + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); + return -1; + } } public T? Remove(int index) { - if (index >= Count || index < 0) - // on the other positions items don't exist + try { + if (index >= _maxCount || index < 0) + // on the other positions items don't exist + { + throw new CollectionOverflowException(index); + // [?] PositionOutOfCollectionException <<< + } + + T? item = _collection[index]; + _collection[index] = null; + + if (item == null) throw new ObjectNotFoundException(index); + + return item; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); return null; } - - T? item = _collection[index]; - _collection[index] = null; - return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index fd256d3..3e11e11 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Reflection; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -40,49 +41,111 @@ public class ListGenObj : ICollectionGenObj public T? GetItem(int position) { - if (position >= Count || position < 0) + try { + if (position > Count) + throw new CollectionOverflowException(position); + if (position < 0) + throw new PositionOutOfCollectionException(position); + + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + + return _collection[position]; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return null; } - - return _collection[position]; } public int Insert(T? obj) { - if (Count >= _maxCount || obj == null) + if (obj == null) { return -1; } + + try // выход за границы, курируется CollectionOverflowException { + if (Count >= _maxCount) + { + throw new CollectionOverflowException(Count); + } + + _collection.Add(obj); + return Count; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); return -1; } - - _collection.Add(obj); - return Count; } public int Insert(T? obj, int position) { - if (position >= _maxCount || Count >= _maxCount || - position < 0 || _collection[position] != null - || obj == null) + try { + if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + + if (obj == null) throw new ObjectNotFoundException(position); + + _collection.Insert(position, obj); + return position; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return -1; } - - _collection.Insert(position, obj); - return position; } public T? Remove(int position) { - if (position >= Count || position < 0) - // on the other positions items don't exist + try { + if (position >= _maxCount || position < 0) + // on the other positions items don't exist + { + throw new CollectionOverflowException(position); + } + + T? item = _collection[position]; + _collection.RemoveAt(position); + + if (item == null) throw new ObjectNotFoundException(position); + + return item; + } + catch (CollectionOverflowException ex) { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); return null; } - - T? item = _collection[position]; - _collection.RemoveAt(position); - return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index 93ae0b4..a209124 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,5 +1,6 @@ using System.Text; using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -55,9 +56,11 @@ public class StorageCollection /// Путь и имя файла /// true - сохранение прошло успешно, /// false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { - if (_storages.Count == 0) { return false; } + if (_storages.Count == 0) + throw new NullReferenceException(" > No existing collections to save"); + if (File.Exists(filename)) { File.Delete(filename); } StringBuilder sb = new(); @@ -79,21 +82,6 @@ public class StorageCollection foreach (T? item in pair.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; - - /* - string n = item.GetType().Name; - string data = null; - - if (n != null && n == "DrawningCruiser") - { - data = ExtentionDrShip.GetDataForSave(item); - } - else if (n != null && n == "DrawningBase") - { - data = ExtentionDrShip.GetDataForSave(item); - } - */ - if (string.IsNullOrEmpty(data)) { continue; @@ -107,7 +95,6 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } // Создание коллекции по типу @@ -122,12 +109,9 @@ public class StorageCollection } // Загрузка информации по кораблям в хранилище из файла - public bool LoadData(string filename) + public void LoadData(string filename) { - if (!File.Exists(filename)) - { - return false; - } + if (!File.Exists(filename)) throw new FileNotFoundException(); string bufferTextFromFile = ""; @@ -145,14 +129,9 @@ public class StorageCollection new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) - { - return false; - } + throw new NullReferenceException("> No data to decode"); if (!strs[0].Equals(_collectionKey)) - { - //если нет такой записи, то это не те данные - return false; - } + throw new InvalidDataException("> Incorrect data"); string[] companies = new string[strs.Length - 1]; for (int k = 1; k < strs.Length; k++) @@ -171,10 +150,9 @@ public class StorageCollection } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) - { - return false; - } + throw new NullReferenceException("> Failed to create collection"); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, @@ -184,15 +162,20 @@ public class StorageCollection { if (elem?.CreateDrawningCar() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(ship) == -1) + throw new IndexOutOfRangeException( + "> Failed to add to collection : " + record[3]); + } + catch (CollectionOverflowException e) + { + throw new CollectionOverflowException("Collection overflowed", e); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/ProjectCruiser/Exceptions/CollectionOverflowException.cs b/ProjectCruiser/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..43f991d --- /dev/null +++ b/ProjectCruiser/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,18 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку переполнения коллекции +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) + : base("Possible accsess of collection is over : " + 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/ProjectCruiser/Exceptions/ObjectNotFoundException.cs b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..81e29f9 --- /dev/null +++ b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку, что по указанной позиции нет элемента +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) + : base("Didn't find obj on this position : " + 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/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..266b7ee --- /dev/null +++ b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку выхода за границы коллекции +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) + : base("Out of collection boarder. Position : " + 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/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index ecba91c..7e7a369 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -1,17 +1,42 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectCruiser { internal static class Program { /// - /// The main entry point for the application. + /// 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(); - Application.Run(new ServiceForm2()); + ServiceCollection services = new(); + ConfigureServices(services); + + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// DI + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + // [*] option.AddSerilog("serilog.config"); + option.AddSerilog("serilog.config"); + + // instead of : + // option.SetMinimumLevel(LogLevel.Information); + // option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser.csproj b/ProjectCruiser/ProjectCruiser.csproj index 663fdb8..1afe9e3 100644 --- a/ProjectCruiser/ProjectCruiser.csproj +++ b/ProjectCruiser/ProjectCruiser.csproj @@ -8,4 +8,14 @@ enable + + + + + + + Always + + + \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 3b0c05f..83edf3e 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,5 +1,9 @@ using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; + +using Microsoft.Extensions.Logging; +// using NLog.Extensions.Logging; + namespace ProjectCruiser; public partial class ServiceForm2 : Form @@ -9,10 +13,16 @@ public partial class ServiceForm2 : Form private readonly StorageCollection _storageCollection; - public ServiceForm2() + // Логер + private readonly ILogger _logger; + + // Конструктор > logger + public ServiceForm2(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + } // Выбор компании @@ -71,27 +81,39 @@ public partial class ServiceForm2 : Form // Передача объекта в другую форму private void btnChooseforTest_Click(object sender, EventArgs e) { + // Add EXCEPTIONS [!] if (_company == null) { return; } - DrawningBase? car = null; + DrawningBase? ship = null; int counter = 100; - while (car == null) + while (ship == null) { - car = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + ship = _company.GetRandomObject(); + counter--; + + if (counter <= 0) + { + break; + } } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return; + } + } - if (car == null) + + if (ship == null) { return; } - OceanForm1 form = new() { SetShip = car }; + OceanForm1 form = new() { SetShip = ship }; form.ShowDialog(); } @@ -190,15 +212,17 @@ public partial class ServiceForm2 : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show(" < Saved succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Saving to file : {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("< Failed to save >", "Result :", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Result :", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("< Error > : {Message}", ex.Message); } } } @@ -208,16 +232,20 @@ public partial class ServiceForm2 : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show(" < Loaded succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Loading from file : {filename}", openFileDialog.FileName); + RefreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("< Failed to load >", "Result :", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("< Failed to load >" + ex.Message, + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("< Error > : {Message}", ex.Message); } } } diff --git a/ProjectCruiser/serilog.config b/ProjectCruiser/serilog.config new file mode 100644 index 0000000..a00fcc6 --- /dev/null +++ b/ProjectCruiser/serilog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + -- 2.25.1 From 507118762322d6568cadd14529075ecac9de956e Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sun, 16 Jun 2024 19:46:37 +0400 Subject: [PATCH 2/2] logging --- .../CollectionGenericObj/AbstractCompany.cs | 14 +- .../CollectionGenericObj/ArrayGenObj.cs | 179 +++++++----------- .../CollectionGenericObj/ListGenObj.cs | 121 +++--------- .../ShipSharingService.cs | 26 ++- .../CollectionGenericObj/StorageCollection.cs | 30 +-- .../Exceptions/CollectionOverflowException.cs | 2 +- .../Exceptions/ObjectNotFoundException.cs | 2 +- .../PositionOutOfCollectionException.cs | 2 +- ProjectCruiser/Program.cs | 23 ++- ProjectCruiser/ProjectCruiser.csproj | 14 +- ProjectCruiser/ServiceForm2.Designer.cs | 2 +- ProjectCruiser/ServiceForm2.cs | 90 ++++++--- ProjectCruiser/serilog.config | 13 -- ProjectCruiser/serilog.json | 15 ++ 14 files changed, 241 insertions(+), 292 deletions(-) delete mode 100644 ProjectCruiser/serilog.config create mode 100644 ProjectCruiser/serilog.json diff --git a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index 5b98774..fdd5d80 100644 --- a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -17,8 +17,8 @@ public abstract class AbstractCompany // Коллекция автомобилей protected ICollectionGenObj? _collection = null; - private int GetMaxCount => _pictureWidth * _pictureHeight / - (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 20)) + * ( _pictureHeight / (_placeSizeHeight + 4)); public AbstractCompany(int picWidth, int picHeight, ICollectionGenObj? collection) @@ -51,20 +51,22 @@ public abstract class AbstractCompany Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); DrawBackground(graphics); - SetObjectsPosition(); - for (int i = 0; i < (_collection?.Count ?? 0); ++i) + + SetObjectsPosition(_collection.Count - 1); + + for (int i = 0; i < (_collection?.Count ?? 0); i++) { DrawningBase? obj = _collection?.GetItem(i); obj?.DrawTransport(graphics); } + return bitmap; } - // Вывод заднего фона protected abstract void DrawBackground(Graphics g); // Расстановка объектов - protected abstract void SetObjectsPosition(); + protected abstract void SetObjectsPosition(int border); } diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index cf2297a..475640a 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,5 +1,4 @@ - -using ProjectCruiser.Exceptions; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -11,7 +10,7 @@ public class ArrayGenObj : ICollectionGenObj // Максимально допустимое число объектов в массиве private int _maxCount; - public int Count => _collection.Count(s => s != null); + public int Count => _collection.Count(s => (s != null)); public int MaxCount { @@ -20,10 +19,10 @@ public class ArrayGenObj : ICollectionGenObj { if (value > 0) { + _maxCount = value; + if (_collection.Length == 0) _collection = new T?[value]; else Array.Resize(ref _collection, value); - - _maxCount = value; } } } @@ -38,140 +37,96 @@ public class ArrayGenObj : ICollectionGenObj // methods : public T? GetItem(int index) { - try - { - if (index > Count) - throw new CollectionOverflowException(index); - if (index < 0) - throw new PositionOutOfCollectionException(index); + if (index > _maxCount) + throw new CollectionOverflowException(index); + if (index < 0) + throw new PositionOutOfCollectionException(index); - if (_collection[index] == null) - throw new ObjectNotFoundException(index); + if (_collection[index] == null) + throw new ObjectNotFoundException(index); - return _collection[index]; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return null; - } + return _collection[index]; + + // CollectionOverflowException + // PositionOutOfCollectionException + // ObjectNotFoundException } public int Insert(T? item) { - if (item == null) { return -1; } + if (item == null) throw + new NullReferenceException("> Inserting item is null"); - try // выход за границы, курируется CollectionOverflowException - { - if (Count >= _maxCount) - { - throw new CollectionOverflowException(Count); - } + // выход за границы, курируется CollectionOverflowException + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - // any empty place -> fill immediately - for (int i = 0; i < _collection.Length; i++) - { - if (_collection[i] == null) - { - _collection[i] = item; - return i; - } - } - return Count; - } - catch (CollectionOverflowException ex) + // any empty place -> fill immediately + for (int i = Count; i < _maxCount; i++) { - Console.WriteLine(ex.Message); - return -1; + if (_collection[i] == null) + { + _collection[i] = item; + return i; + } } + return Count; + + // NullReferenceException + // CollectionOverflowException } public int Insert(T? item, int index) { - try + if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + + if (item == null) throw + new NullReferenceException("> Inserting item (at position) is null"); + + if (_collection[index] == null) { - if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); - if (Count >= _maxCount) throw new CollectionOverflowException(Count); + _collection[index] = item; + return index; + } + else + { + int min_diff = 100, firstNullIndex = 100; - if (item == null) throw new ObjectNotFoundException(index); - - if (_collection[index] == null) + for (int i = 0; i < Count; i++) { - _collection[index] = item; - return index; - } - else - { - int min_diff = 100, firstNullIndex = 100; - - for (int i = 0; i < Count; i++) + if (_collection[i] == null && min_diff > Math.Abs(index - i)) { - if (_collection[i] == null && min_diff > Math.Abs(index - i)) - { - min_diff = Math.Abs(index - i); - firstNullIndex = i; - } + min_diff = Math.Abs(index - i); + firstNullIndex = i; } - - _collection[firstNullIndex] = item; - return firstNullIndex; } + + _collection[firstNullIndex] = item; + return firstNullIndex; } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + + // PositionOutOfCollectionException + // CollectionOverflowException + // NullReferenceException } public T? Remove(int index) { - try + if (index >= _maxCount || index < 0) + // on the other positions items don't exist { - if (index >= _maxCount || index < 0) - // on the other positions items don't exist - { - throw new CollectionOverflowException(index); - // [?] PositionOutOfCollectionException <<< - } - - T? item = _collection[index]; - _collection[index] = null; - - if (item == null) throw new ObjectNotFoundException(index); - - return item; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; + throw new PositionOutOfCollectionException(index); } + + T? item = _collection[index]; + _collection[index] = null; + + if (item == null) throw new ObjectNotFoundException(index); + + return item; + + // PositionOutOfCollectionException + // ObjectNotFoundException } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 3e11e11..1cb23cf 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using ProjectCruiser.Exceptions; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -41,111 +37,56 @@ public class ListGenObj : ICollectionGenObj public T? GetItem(int position) { - try - { - if (position > Count) - throw new CollectionOverflowException(position); - if (position < 0) - throw new PositionOutOfCollectionException(position); + if (position > _maxCount) + throw new CollectionOverflowException(position); + if (position < 0) + throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); - return _collection[position]; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return null; - } + return _collection[position]; } public int Insert(T? obj) { - if (obj == null) { return -1; } + if (obj == null) + throw new NullReferenceException("> Inserting object is null"); - try // выход за границы, курируется CollectionOverflowException - { - if (Count >= _maxCount) - { - throw new CollectionOverflowException(Count); - } + // выход за границы, курируется CollectionOverflowException + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - _collection.Add(obj); - return Count; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + _collection.Add(obj); + return Count; } public int Insert(T? obj, int position) { - try - { - if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); - if (Count >= _maxCount) throw new CollectionOverflowException(Count); + if (position < 0 || position >= _maxCount) + throw new PositionOutOfCollectionException(position); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - if (obj == null) throw new ObjectNotFoundException(position); + if (obj == null) + throw new NullReferenceException("> Inserting object (at position) is null"); - _collection.Insert(position, obj); - return position; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + _collection.Insert(position, obj); + return position; } public T? Remove(int position) { - try { - if (position >= _maxCount || position < 0) - // on the other positions items don't exist - { - throw new CollectionOverflowException(position); - } - - T? item = _collection[position]; - _collection.RemoveAt(position); - - if (item == null) throw new ObjectNotFoundException(position); - - return item; - } - catch (CollectionOverflowException ex) + if (position >= _maxCount || position < 0) + // on the other positions items don't exist { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; + throw new PositionOutOfCollectionException(position); } + + T? item = _collection[position]; + _collection.RemoveAt(position); + + if (item == null) throw new ObjectNotFoundException(position); + + return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs index e430deb..1fa2de7 100644 --- a/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs +++ b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs @@ -41,27 +41,33 @@ public class ShipSharingService : AbstractCompany } } - protected override void SetObjectsPosition() + protected override void SetObjectsPosition(int border) { int index_collection = 0; - int newX = fromBorder + 6, newY = fromCeiling + 6; + int newY = fromCeiling + 4; if (_collection != null) { - for (int i = 0; i < MaxInColon; ++i) + for (int i = 0; i < MaxInColon; i++) { - newX = fromBorder + 2; - for (int j = 0; j < MaxInRow; ++j) + int newX = fromBorder + 2; + for (int j = 0; j < MaxInRow; j++) { - if (_collection.GetItem(index_collection) != null) + // TRY / CATCH [?] + _collection.GetItem(index_collection).SetPictureSize( + _pictureWidth, _pictureHeight); + + _collection.GetItem(index_collection).SetPosition(newX, newY); + + newX += _placeSizeWidth + between + 2; + + if (index_collection < border) { - _collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.GetItem(index_collection).SetPosition(newX, newY); - newX += _placeSizeWidth + between + 2; index_collection++; } + else return; } - newY += _placeSizeHeight + 2; + newY += _placeSizeHeight + 1; } } } diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index a209124..acc8411 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,4 +1,5 @@ -using System.Text; +using System.Security.Cryptography; +using System.Text; using ProjectCruiser.DrawningSamples; using ProjectCruiser.Exceptions; @@ -32,7 +33,7 @@ public class StorageCollection if (name == null || _storages.ContainsKey(name) || collType == CollectionType.None) { - return; + throw new NullReferenceException("> Not enough information to save"); } ICollectionGenObj collection = CreateCollection(collType); @@ -43,7 +44,7 @@ public class StorageCollection public void DelCollection(string name) { if (_storages.ContainsKey(name)) _storages.Remove(name); - return; + else throw new NullReferenceException("> No such key in the list"); } // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] @@ -59,7 +60,7 @@ public class StorageCollection public void SaveData(string filename) { if (_storages.Count == 0) - throw new NullReferenceException(" > No existing collections to save"); + throw new NullReferenceException("> No existing collections to save"); if (File.Exists(filename)) { File.Delete(filename); } @@ -111,7 +112,7 @@ public class StorageCollection // Загрузка информации по кораблям в хранилище из файла public void LoadData(string filename) { - if (!File.Exists(filename)) throw new FileNotFoundException(); + if (!File.Exists(filename)) throw new FileNotFoundException("> No such file"); string bufferTextFromFile = ""; @@ -145,14 +146,13 @@ public class StorageCollection string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) // > // key | collType | maxcount | all next inf > 4 - { - continue; - } + { continue; } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) - throw new NullReferenceException("> Failed to create collection"); + throw new NullReferenceException("[!] Failed to create collection"); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, @@ -164,13 +164,15 @@ public class StorageCollection { try { - if (collection.Insert(ship) == -1) - throw new IndexOutOfRangeException( - "> Failed to add to collection : " + record[3]); + collection.Insert(ship); + + // throw new IndexOutOfRangeException IF IT WAS Insert(item, pos) + // NullReferenceException > + // CollectionOverflowException > } - catch (CollectionOverflowException e) + catch (Exception e) { - throw new CollectionOverflowException("Collection overflowed", e); + throw new Exception(e.Message); } } } diff --git a/ProjectCruiser/Exceptions/CollectionOverflowException.cs b/ProjectCruiser/Exceptions/CollectionOverflowException.cs index 43f991d..790d0a2 100644 --- a/ProjectCruiser/Exceptions/CollectionOverflowException.cs +++ b/ProjectCruiser/Exceptions/CollectionOverflowException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class CollectionOverflowException : ApplicationException { public CollectionOverflowException(int count) - : base("Possible accsess of collection is over : " + count) { } + : base("<> Possible accsess\nof collection is over : " + count) { } public CollectionOverflowException() : base() { } public CollectionOverflowException(string message) : base(message) { } public CollectionOverflowException(string message, Exception exception) : diff --git a/ProjectCruiser/Exceptions/ObjectNotFoundException.cs b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs index 81e29f9..b6f8a4a 100644 --- a/ProjectCruiser/Exceptions/ObjectNotFoundException.cs +++ b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class ObjectNotFoundException : ApplicationException { public ObjectNotFoundException(int i) - : base("Didn't find obj on this position : " + i) { } + : base("<> Didn't find obj\non this position : " + i) { } public ObjectNotFoundException() : base() { } public ObjectNotFoundException(string message) : base(message) { } public ObjectNotFoundException(string message, Exception exception) diff --git a/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs index 266b7ee..305704e 100644 --- a/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class PositionOutOfCollectionException : ApplicationException { public PositionOutOfCollectionException(int i) - : base("Out of collection boarder. Position : " + i) { } + : base("<> Out of collection\nboarder. Position : " + i) { } public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException(string message) : base(message) { } public PositionOutOfCollectionException(string message, diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index 7e7a369..9767135 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; using Serilog; namespace ProjectCruiser @@ -16,26 +17,28 @@ namespace ProjectCruiser // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + 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("serilog.config"); - option.AddSerilog("serilog.config"); - - // instead of : - // option.SetMinimumLevel(LogLevel.Information); - // option.AddNLog("nlog.config"); + option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration( + new ConfigurationBuilder().AddJsonFile( + $"{pathNeed}serilog.json").Build()).CreateLogger()); }); } } diff --git a/ProjectCruiser/ProjectCruiser.csproj b/ProjectCruiser/ProjectCruiser.csproj index 1afe9e3..3d70e47 100644 --- a/ProjectCruiser/ProjectCruiser.csproj +++ b/ProjectCruiser/ProjectCruiser.csproj @@ -9,13 +9,15 @@ + + + + + + - - - - - Always - + + \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index d065feb..dc4fd35 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -221,7 +221,7 @@ btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; - btnDelete.Click += btnRemoveCar_Click; + btnDelete.Click += btnRemoveShip_Click; // // btnAddCruiser // diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 83edf3e..dfeae24 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,7 +1,7 @@ using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; - using Microsoft.Extensions.Logging; +using ProjectCruiser.Exceptions; // using NLog.Extensions.Logging; namespace ProjectCruiser; @@ -22,7 +22,7 @@ public partial class ServiceForm2 : Form InitializeComponent(); _storageCollection = new(); _logger = logger; - + _logger.LogInformation("> Form is loaded successfully"); } // Выбор компании @@ -31,13 +31,10 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = false; } - // Color picker (default : random) <...> - // Добавление корабля private void btnAddTransport_Click(object sender, EventArgs e) { EditorForm3 form3 = new(); - // TODO передать метод : form3.AddEvent(CreateObject); form3.Show(); } @@ -45,43 +42,58 @@ public partial class ServiceForm2 : Form // Создание объекта класса-перемещения private void CreateObject(DrawningBase? ship) { - if (_company == null || ship == null) - { - return; - } - if (_company + ship != -1) + try { + if (_company == null || ship == null) + { + throw new NullReferenceException(" > No existing collections to save"); + } + + int count = _company + ship; + MessageBox.Show("> Object was added"); pictureBox.Image = _company.Show(); + + _logger.LogInformation("> Adding object succeed {ship} at {count} position", ship, count); } - else + catch (Exception ex) { - MessageBox.Show("[!] Failed to add object"); + MessageBox.Show("[!] Failed to add object\n" + ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); } } // Удаление объекта - private void btnRemoveCar_Click(object sender, EventArgs e) + private void btnRemoveShip_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) return; if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - Convert.ToInt32(maskedTextBoxPosition.Text) != null) + try { - MessageBox.Show("> Object was removed"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("> Object was removed"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Object at " + + pos + "position was deleted successfully"); + } + } + catch (Exception ex) + { + MessageBox.Show("[!] Failed to remove object"); + _logger.LogError("< Error > : {Message}", ex.Message); } - else MessageBox.Show("[!] Failed to remove object"); } // Передача объекта в другую форму private void btnChooseforTest_Click(object sender, EventArgs e) { - // Add EXCEPTIONS [!] if (_company == null) { return; @@ -117,7 +129,6 @@ public partial class ServiceForm2 : Form form.ShowDialog(); } - // Перерисовка коллекции private void btnRefresh_Click(object sender, EventArgs e) { if (_company == null) @@ -146,7 +157,17 @@ public partial class ServiceForm2 : Form collType = CollectionType.List; } - _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); + try + { + _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); + _logger.LogInformation("Adding collection succeed : {Name}, {Type}", maskedTxtBoxCName.Text, collType); + } + catch (NullReferenceException ex) + { + Console.WriteLine(ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); + } + RefreshListBoxItems(); } @@ -156,13 +177,21 @@ public partial class ServiceForm2 : Form { MessageBox.Show("Collection was not choosed"); return; - } - if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK) + } if (MessageBox.Show("Are you sure?", "Removing", + MessageBoxButtons.OK, MessageBoxIcon.Question) + != DialogResult.OK) return; + + try { - return; + _storageCollection.DelCollection(listBox.SelectedItem.ToString()); + RefreshListBoxItems(); + _logger.LogInformation("Removing collection succeed : {Name}", listBox.SelectedItem.ToString); + } + catch (NullReferenceException ex) + { + Console.WriteLine(ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); } - _storageCollection.DelCollection(listBox.SelectedItem.ToString()); - RefreshListBoxItems(); } private void RefreshListBoxItems() @@ -199,7 +228,7 @@ public partial class ServiceForm2 : Form { case "Storage": _company = new ShipSharingService(pictureBox.Width, - pictureBox.Height, collection); + pictureBox.Height, collection); break; } @@ -235,9 +264,16 @@ public partial class ServiceForm2 : Form try { _storageCollection.LoadData(openFileDialog.FileName); + // LoadData() : Exceptions + // FileNotFoundException + // NullReferenceException + // InvalidDataException + // IndexOutOfRangeException + // CollectionOverflowException + MessageBox.Show(" < Loaded succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Loading from file : {filename}", openFileDialog.FileName); + _logger.LogInformation("Loading from file : {Filename}", openFileDialog.FileName); RefreshListBoxItems(); } diff --git a/ProjectCruiser/serilog.config b/ProjectCruiser/serilog.config deleted file mode 100644 index a00fcc6..0000000 --- a/ProjectCruiser/serilog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - diff --git a/ProjectCruiser/serilog.json b/ProjectCruiser/serilog.json new file mode 100644 index 0000000..fd4d7d8 --- /dev/null +++ b/ProjectCruiser/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} -- 2.25.1