From c50ddb14a28095491e6709bc6b56efdd44b6a6cb Mon Sep 17 00:00:00 2001 From: Kankistodor <153865585+Kankistodor@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:26:19 +0400 Subject: [PATCH] Lab7-ready --- .../AbstractCompany.cs | 181 ++++++++++-------- .../ListGenericObjects.cs | 14 +- .../MassiveGenericObjects.cs | 111 +++++------ .../StorageCollection.cs | 86 ++++++++- .../TransDepoService.cs | 86 +++++---- .../CollectionAlreadyExistsException.cs | 13 ++ .../Exceptions/CollectionInsertException.cs | 13 ++ .../Exceptions/CollectionOverflowException.cs | 31 +++ .../Exceptions/CollectionTypeException.cs | 14 ++ .../Exceptions/EmptyFileExeption.cs | 14 ++ .../Exceptions/EmptyStorageException.cs | 13 ++ .../Exceptions/FileFormatException.cs | 13 ++ .../Exceptions/FileNotFoundException.cs | 14 ++ .../Exceptions/ObjectNotFoundException.cs | 15 ++ .../PositionOutOfCollectionException.cs | 27 +++ ProjectElectroTrans/FormTransCollection.cs | 70 +++++-- .../FormTransConfig.Designer.cs | 3 - ProjectElectroTrans/FormTransConfig.cs | 2 +- ProjectElectroTrans/Program.cs | 37 +++- .../ProjectElectroTrans.csproj | 12 +- ProjectElectroTrans/serilogConfig.json | 20 ++ 21 files changed, 564 insertions(+), 225 deletions(-) create mode 100644 ProjectElectroTrans/Exceptions/CollectionAlreadyExistsException.cs create mode 100644 ProjectElectroTrans/Exceptions/CollectionInsertException.cs create mode 100644 ProjectElectroTrans/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectElectroTrans/Exceptions/CollectionTypeException.cs create mode 100644 ProjectElectroTrans/Exceptions/EmptyFileExeption.cs create mode 100644 ProjectElectroTrans/Exceptions/EmptyStorageException.cs create mode 100644 ProjectElectroTrans/Exceptions/FileFormatException.cs create mode 100644 ProjectElectroTrans/Exceptions/FileNotFoundException.cs create mode 100644 ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectElectroTrans/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectElectroTrans/serilogConfig.json diff --git a/ProjectElectroTrans/CollectionGenericObjects/AbstractCompany.cs b/ProjectElectroTrans/CollectionGenericObjects/AbstractCompany.cs index 09d85f0..44c72f7 100644 --- a/ProjectElectroTrans/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectElectroTrans/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,5 @@ using ProjectElectroTrans.Drawnings; +using ProjectElectroTrans.Exceptions; namespace ProjectElectroTrans.CollectionGenericObjects; @@ -7,59 +8,60 @@ namespace ProjectElectroTrans.CollectionGenericObjects; /// public abstract class AbstractCompany { - /// - /// Размер места (ширина) - /// - protected readonly int _placeSizeWidth = 210; + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 210; - /// - /// Размер места (высота) - /// - protected readonly int _placeSizeHeight = 80; + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 80; - /// - /// Ширина окна - /// - protected readonly int _pictureWidth; + /// + /// Ширина окна + /// + protected readonly int _pictureWidth; - /// - /// Высота окна - /// - protected readonly int _pictureHeight; + /// + /// Высота окна + /// + protected readonly int _pictureHeight; - /// - /// Коллекция поездов - /// - protected ICollectionGenericObjects? _collection = null; + /// + /// Коллекция поездов + /// + protected ICollectionGenericObjects? _collection = null; - /// - /// Вычисление максимального количества элементов, который можно разместить в окне - /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + /// + /// Вычисление максимального количества элементов, который можно разместить в окне + /// + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); + // private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight); - /// - /// Конструктор - /// - /// Ширина окна - /// Высота окна - /// Коллекция поездов - public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) - { - _pictureWidth = picWidth; - _pictureHeight = picHeight; - _collection = collection; - _collection.MaxCount = GetMaxCount; - } + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция поездов + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.MaxCount = GetMaxCount; + } - /// - /// Перегрузка оператора сложения для класса - /// - /// Компания - /// Добавляемый объект - /// - public static int operator +(AbstractCompany company, DrawingTrans trans) - { - return company._collection.Insert(trans); + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawingTrans trans) + { + return company._collection.Insert(trans); } /// @@ -69,48 +71,59 @@ public abstract class AbstractCompany /// Номер удаляемого объекта /// public static DrawingTrans? operator -(AbstractCompany company, int position) - { - return company._collection?.Remove(position); - } + { + return company._collection?.Remove(position); + } - /// - /// Получение случайного объекта из коллекции - /// - /// - public DrawingTrans? GetRandomObject() - { - Random rnd = new(); - return _collection?.Get(rnd.Next(GetMaxCount)); - } + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawingTrans? GetRandomObject() + { + Random rnd = new(); + return _collection?.Get(rnd.Next(GetMaxCount)); + } - /// - /// Вывод всей коллекции - /// - /// - public Bitmap? Show() - { - Bitmap bitmap = new(_pictureWidth, _pictureHeight); - Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackgound(graphics); - SetObjectsPosition(); - for (int i = 0; i < (_collection?.Count ?? 0); ++i) - { - DrawingTrans? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); - } + SetObjectsPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); ++i) + { + try + { + DrawingTrans? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } + } - return bitmap; - } + return bitmap; + } - /// - /// Вывод заднего фона - /// - /// - protected abstract void DrawBackgound(Graphics g); + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); - /// - /// Расстановка объектов - /// - protected abstract void SetObjectsPosition(); + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); } \ No newline at end of file diff --git a/ProjectElectroTrans/CollectionGenericObjects/ListGenericObjects.cs b/ProjectElectroTrans/CollectionGenericObjects/ListGenericObjects.cs index 4d72837..ef589a5 100644 --- a/ProjectElectroTrans/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectElectroTrans/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -namespace ProjectElectroTrans.CollectionGenericObjects; +using ProjectElectroTrans.Exceptions; + +namespace ProjectElectroTrans.CollectionGenericObjects; /// /// Параметризованный набор объектов @@ -43,28 +45,28 @@ public class ListGenericObjects : ICollectionGenericObjects public T Get(int position) { - if (position >= Count || position < 0) return null; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - if (Count == _maxCount) return -1; + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (Count == _maxCount) return -1; - if (position >= Count || position < 0) return -1; + 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) { - if (position >= _collection.Count || position < 0) return null; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectElectroTrans/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectElectroTrans/CollectionGenericObjects/MassiveGenericObjects.cs index 8bf183d..2cf890f 100644 --- a/ProjectElectroTrans/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectElectroTrans/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ - +using ProjectElectroTrans.Exceptions; + namespace ProjectElectroTrans.CollectionGenericObjects; /// @@ -6,55 +7,49 @@ namespace ProjectElectroTrans.CollectionGenericObjects; /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects - where T : class + where T : class { - /// - /// Массив объектов, которые храним - /// - private T?[] _collection; + /// + /// Массив объектов, которые храним + /// + private T?[] _collection; - public int Count => _collection.Length; + public int Count => _collection.Length; - public int MaxCount - { - get - { - return _collection.Length; - } - set - { - if (value > 0) - { - if (_collection.Length > 0) - { - Array.Resize(ref _collection, value); - } - else - { - _collection = new T?[value]; - } - } - } - } - - public CollectionType GetCollectionType => CollectionType.Massive; - - /// - /// Конструктор - /// - public MassiveGenericObjects() - { - _collection = Array.Empty(); - } - - public T? Get(int position) + public int MaxCount { - if (position >= 0 && position < Count) + get { return _collection.Length; } + set { - return _collection[position]; + if (value > 0) + { + if (_collection.Length > 0) + { + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; + } + } } + } - return null; + public CollectionType GetCollectionType => CollectionType.Massive; + + /// + /// Конструктор + /// + public MassiveGenericObjects() + { + _collection = Array.Empty(); + } + + public T? Get(int 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) @@ -69,16 +64,13 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { // проверка позиции - if (position < 0 || position >= Count) - { - return -1; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); // проверка, что элемент массива по этой позиции пустой, если нет, то // ищется свободное место после этой позиции и идет вставка туда @@ -111,7 +103,7 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (!pushed) { - return position; + throw new CollectionOverflowException(Count); } } @@ -123,23 +115,20 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Remove(int position) { // проверка позиции - if (position < 0 || position >= Count) - { - return null; - } + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) return null; + if (_collection[position] == null) throw new ObjectNotFoundException(position); T? temp = _collection[position]; _collection[position] = null; return temp; } - public IEnumerable GetItems() - { - for (int i = 0; i < _collection.Length; ++i) - { - yield return _collection[i]; - } - } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectElectroTrans/CollectionGenericObjects/StorageCollection.cs b/ProjectElectroTrans/CollectionGenericObjects/StorageCollection.cs index 036892c..375d8a7 100644 --- a/ProjectElectroTrans/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectElectroTrans/CollectionGenericObjects/StorageCollection.cs @@ -1,6 +1,9 @@ using ProjectElectroTrans.Drawnings; using System.Text; using ProjectElectroTrans.CollectionGenericObjects; +using ProjectElectroTrans.Exceptions; +using FileFormatException = ProjectElectroTrans.Exceptions.FileFormatException; +using FileNotFoundException = ProjectElectroTrans.Exceptions.FileNotFoundException; namespace ProjectElectroTrans.CollectionGenericObjects; @@ -51,9 +54,9 @@ public class StorageCollection /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) + if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name); + if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionType == CollectionType.Massive) _storages[name] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) _storages[name] = new ListGenericObjects(); @@ -67,6 +70,7 @@ public class StorageCollection { if (_storages.ContainsKey(name)) _storages.Remove(name); + } /// @@ -93,7 +97,7 @@ public class StorageCollection { if (_storages.Count == 0) { - return false; + throw new EmptyFileExeption(); } if (File.Exists(filename)) @@ -154,14 +158,15 @@ public class StorageCollection using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - return false; + throw new FileNotFoundException(filename); + } if (!str.StartsWith(_collectionKey)) { - return false; + throw new FileFormatException(filename); } _storages.Clear(); @@ -178,7 +183,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -187,9 +192,70 @@ public class StorageCollection { if (elem?.CreateDrawningTrans() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + collection.Insert(ship); + } + catch (Exception ex) + { + throw new FileFormatException(filename, ex); + } + } + } + + _storages.Add(record[0], collection); + } + + return true; + } + if (!File.Exists(filename)) + { + } + + using (StreamReader fs = File.OpenText(filename)) + { + string str = fs.ReadLine(); + if (string.IsNullOrEmpty(str)) + { + throw new EmptyFileExeption(filename); + } + + if (!str.StartsWith(_collectionKey)) + { + } + + _storages.Clear(); + string strs = ""; + while ((strs = fs.ReadLine()) != null) + { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + } + + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningTrans() is T ship) + { + try + { + if (collection.Insert(ship) == -1) + { + throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw ex.InnerException!; } } } diff --git a/ProjectElectroTrans/CollectionGenericObjects/TransDepoService.cs b/ProjectElectroTrans/CollectionGenericObjects/TransDepoService.cs index 48d165d..e86c983 100644 --- a/ProjectElectroTrans/CollectionGenericObjects/TransDepoService.cs +++ b/ProjectElectroTrans/CollectionGenericObjects/TransDepoService.cs @@ -1,6 +1,7 @@ using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Entities; using System; +using ProjectElectroTrans.Exceptions; namespace ProjectElectroTrans.CollectionGenericObjects; @@ -9,47 +10,62 @@ namespace ProjectElectroTrans.CollectionGenericObjects; /// public class TransDepoService : AbstractCompany { - /// - /// Конструктор - /// - /// - /// - /// - public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base(picWidth, picHeight, collection) - { - } + /// + /// Конструктор + /// + /// + /// + /// + public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects collection) : base( + picWidth, picHeight, collection) + { + } - protected override void DrawBackgound(Graphics g) - { + protected override void DrawBackgound(Graphics g) + { Pen pen = new(Color.Black); for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { - for(int j = 0; j < _pictureHeight / _placeSizeHeight; j++) + for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) { - g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j)); - g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); - } - g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); - } + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), + new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j)); + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), + new(_placeSizeWidth * i, _placeSizeHeight * (j + 1))); + } - + g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), + new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight))); + } } - protected override void SetObjectsPosition() - { - int n = 0; - for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) - { - for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) - { - DrawingTrans? drawingTrans = _collection?.Get(n); - n++; - if (drawingTrans != null) - { - drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight); - drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); - } - } - } - } + protected override void SetObjectsPosition() + { + int n = 0; + for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) + { + for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) + { + try + { + DrawingTrans? drawingTrans = _collection?.Get(n); + if (drawingTrans != null) + { + drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight); + drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + } + } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } + + n++; + } + } + } } \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/CollectionAlreadyExistsException.cs b/ProjectElectroTrans/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..eab928f --- /dev/null +++ b/ProjectElectroTrans/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/CollectionInsertException.cs b/ProjectElectroTrans/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..d107dd0 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/CollectionInsertException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) : + base(message, exception) { } + protected CollectionInsertException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/CollectionOverflowException.cs b/ProjectElectroTrans/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..5a82cbc --- /dev/null +++ b/ProjectElectroTrans/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + + +namespace ProjectElectroTrans.Exceptions +{ + [Serializable] + internal class CollectionOverflowException : ApplicationException + { + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) + { + } + + public CollectionOverflowException() : base() + { + } + + public CollectionOverflowException(string message) : base(message) + { + } + + public CollectionOverflowException(string message, Exception exception) : + base(message, exception) + { + } + + protected CollectionOverflowException(SerializationInfo info, + StreamingContext contex) : base(info, contex) + { + } + } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/CollectionTypeException.cs b/ProjectElectroTrans/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..945cfa4 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/CollectionTypeException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; +using ProjectElectroTrans.CollectionGenericObjects; + +namespace ProjectElectroTrans.Exceptions; + +public class CollectionTypeException : Exception +{ + public CollectionTypeException() : base() { } + public CollectionTypeException(string message) : base(message) { } + public CollectionTypeException(string message, Exception exception) : + base(message, exception) { } + protected CollectionTypeException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/EmptyFileExeption.cs b/ProjectElectroTrans/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..59acb0a --- /dev/null +++ b/ProjectElectroTrans/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class EmptyFileExeption : Exception +{ + public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { } + public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileExeption(string name, string message) : base(message) { } + public EmptyFileExeption(string name, string message, Exception exception) : + base(message, exception) { } + protected EmptyFileExeption(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/EmptyStorageException.cs b/ProjectElectroTrans/Exceptions/EmptyStorageException.cs new file mode 100644 index 0000000..372a500 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/EmptyStorageException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class EmptyStorageException : Exception +{ + public EmptyStorageException() : base() { } + public EmptyStorageException(string message) : base(message) { } + public EmptyStorageException(string message, Exception exception) : + base(message, exception) { } + protected EmptyStorageException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/FileFormatException.cs b/ProjectElectroTrans/Exceptions/FileFormatException.cs new file mode 100644 index 0000000..dbbc5e2 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/FileFormatException.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class FileFormatException : Exception +{ + public FileFormatException() : base() { } + public FileFormatException(string message) : base(message) { } + public FileFormatException(string name, Exception exception) : + base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { } + protected FileFormatException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/FileNotFoundException.cs b/ProjectElectroTrans/Exceptions/FileNotFoundException.cs new file mode 100644 index 0000000..043a0bc --- /dev/null +++ b/ProjectElectroTrans/Exceptions/FileNotFoundException.cs @@ -0,0 +1,14 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.Exceptions; + +public class FileNotFoundException : Exception +{ + public FileNotFoundException(string name) : base($"Файл {name} не существует ") { } + public FileNotFoundException() : base() { } + public FileNotFoundException(string name, string message) : base(message) { } + public FileNotFoundException(string name, string message, Exception exception) : + base(message, exception) { } + protected FileNotFoundException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs b/ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..fd8c2f6 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,15 @@ +using System.Runtime.Serialization; + +namespace ProjectElectroTrans.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/ProjectElectroTrans/Exceptions/PositionOutOfCollectionException.cs b/ProjectElectroTrans/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..a29c061 --- /dev/null +++ b/ProjectElectroTrans/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,27 @@ +using System.Runtime.Serialization; + +[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/ProjectElectroTrans/FormTransCollection.cs b/ProjectElectroTrans/FormTransCollection.cs index 429c2df..f6f6d61 100644 --- a/ProjectElectroTrans/FormTransCollection.cs +++ b/ProjectElectroTrans/FormTransCollection.cs @@ -1,6 +1,7 @@ using ProjectElectroTrans.CollectionGenericObjects; using ProjectElectroTrans.Drawnings; -using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using ProjectElectroTrans.Exceptions; namespace ProjectElectroTrans; @@ -19,13 +20,19 @@ public partial class FormTransCollection : Form /// private AbstractCompany? _company = null; + /// + /// Логер + /// + private readonly ILogger _logger; + /// /// Конструктор /// - public FormTransCollection() + public FormTransCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; } /// @@ -62,15 +69,18 @@ public partial class FormTransCollection : Form { return; } - - if (_company + drawingTrans != -1) + try { + var res = _company + drawingTrans; MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - _ = MessageBox.Show(drawingTrans.ToString()); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -93,14 +103,18 @@ public partial class FormTransCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - pos != null) + try { + var res = _company - pos; MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); pictureBox.Image = _company.Show(); } - else + catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } @@ -179,8 +193,18 @@ public partial class FormTransCollection : Form collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); + try + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } /// @@ -203,6 +227,7 @@ public partial class FormTransCollection : Form } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); RerfreshListBoxItems(); } @@ -247,6 +272,7 @@ public partial class FormTransCollection : Form { case "Хранилище": _company = new TransDepoService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } @@ -263,15 +289,19 @@ public partial class FormTransCollection : 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("Не сохранилось", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } } @@ -285,16 +315,20 @@ public partial class FormTransCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}"); + RerfreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("Не загружено", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } diff --git a/ProjectElectroTrans/FormTransConfig.Designer.cs b/ProjectElectroTrans/FormTransConfig.Designer.cs index 63ebe44..907f1e6 100644 --- a/ProjectElectroTrans/FormTransConfig.Designer.cs +++ b/ProjectElectroTrans/FormTransConfig.Designer.cs @@ -43,7 +43,6 @@ panelRed = new Panel(); checkBoxBulldozerDump = new CheckBox(); checkBoxSupport = new CheckBox(); - checkBoxBucket = new CheckBox(); numericUpDownWeight = new NumericUpDown(); numericUpDownSpeed = new NumericUpDown(); labelWeight = new Label(); @@ -73,7 +72,6 @@ groupBoxConfig.Controls.Add(groupBoxColors); groupBoxConfig.Controls.Add(checkBoxBulldozerDump); groupBoxConfig.Controls.Add(checkBoxSupport); - groupBoxConfig.Controls.Add(checkBoxBucket); groupBoxConfig.Controls.Add(numericUpDownWeight); groupBoxConfig.Controls.Add(numericUpDownSpeed); groupBoxConfig.Controls.Add(labelWeight); @@ -377,7 +375,6 @@ private Label labelSpeed; private CheckBox checkBoxBulldozerDump; private CheckBox checkBoxSupport; - private CheckBox checkBoxBucket; private GroupBox groupBoxColors; private Panel panelPurple; private Panel panelYellow; diff --git a/ProjectElectroTrans/FormTransConfig.cs b/ProjectElectroTrans/FormTransConfig.cs index 4a677eb..6ea77d1 100644 --- a/ProjectElectroTrans/FormTransConfig.cs +++ b/ProjectElectroTrans/FormTransConfig.cs @@ -102,7 +102,7 @@ namespace ProjectElectroTrans case "labelModifiedObject": _trans = new DrawingElectroTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, - Color.Black, checkBoxBucket.Checked, + Color.Black, checkBoxBulldozerDump.Checked, checkBoxSupport.Checked); break; } diff --git a/ProjectElectroTrans/Program.cs b/ProjectElectroTrans/Program.cs index c78bbd9..63adb10 100644 --- a/ProjectElectroTrans/Program.cs +++ b/ProjectElectroTrans/Program.cs @@ -1,20 +1,45 @@ -using System.Drawing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; + namespace ProjectElectroTrans { internal static class Program { - /// - /// 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 FormTransCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + + 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++) + { + pathNeed += path[i] + "\\"; + } + + 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/ProjectElectroTrans/ProjectElectroTrans.csproj b/ProjectElectroTrans/ProjectElectroTrans.csproj index 244387d..ab8106b 100644 --- a/ProjectElectroTrans/ProjectElectroTrans.csproj +++ b/ProjectElectroTrans/ProjectElectroTrans.csproj @@ -2,7 +2,7 @@ WinExe - net7.0-windows + net8.0-windows enable true enable @@ -23,4 +23,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/ProjectElectroTrans/serilogConfig.json b/ProjectElectroTrans/serilogConfig.json new file mode 100644 index 0000000..14cb44c --- /dev/null +++ b/ProjectElectroTrans/serilogConfig.json @@ -0,0 +1,20 @@ +{ + "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}" + } + }, {"Name": "Console"} + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "Locomotives" + } + } +} \ No newline at end of file -- 2.25.1