diff --git a/AccordionBus/AccordionBus/AccordionBus.csproj b/AccordionBus/AccordionBus/AccordionBus.csproj index af03d74..f29b6a2 100644 --- a/AccordionBus/AccordionBus/AccordionBus.csproj +++ b/AccordionBus/AccordionBus/AccordionBus.csproj @@ -8,6 +8,17 @@ enable + + + + + + + + + + + True diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs index e9e9bad..daa4f59 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/AbstractCompany.cs @@ -26,12 +26,12 @@ namespace AccordionBus.CollectionGenericObjects _pictureWidth = picWidth; _pictureHeight = picHeigth; _collection = collection; - _collection.MaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount - 3; } public static bool operator +(AbstractCompany company, DrawningBus bus) { - return company._collection.Insert(bus); + return company._collection?.Insert(bus, new DrawningBusEqutables()) ?? false; } public static bool operator -(AbstractCompany company, int position) @@ -51,7 +51,6 @@ namespace AccordionBus.CollectionGenericObjects Graphics graphics = Graphics.FromImage(bitmap); DrawBackground(graphics); - for (int i = 0; i < (_collection?.MaxCount ?? 0); i++) { DrawningBus? obj = _collection?.Get(i); @@ -63,6 +62,8 @@ namespace AccordionBus.CollectionGenericObjects return bitmap; } + public void Sort(IComparer comparer) => _collection?.CollectionSort(comparer); + protected abstract void DrawBackground(Graphics g); protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus); diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/CollectionInfo.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..7ed3afe --- /dev/null +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.CollectionGenericObjects +{ + public class CollectionInfo : IEquatable + { + public string Name { get; private set; } + + public CollectionType CollectionType { get; private set; } + + public string Description { get; private set; } + + private static readonly string _separator = "-"; + + public CollectionInfo(string name, CollectionType collectionType, string description) + { + Name = name; + CollectionType = collectionType; + Description = description; + } + + public static CollectionInfo? GetCollectionInfo(string data) + { + string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries); + if (strs.Length < 1 || strs.Length > 3) return null; + + return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), + strs[1]), strs.Length > 2 ? strs[2] : ""); + } + + public override string ToString() + { + return Name + _separator + CollectionType + _separator + Description; + } + + public bool Equals(CollectionInfo? other) + { + return Name == other?.Name; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return Name.GetHashCode(); + } + } +} diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs index 0a5a736..1fcdbeb 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using AccordionBus.Drawnings; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -22,14 +23,14 @@ namespace AccordionBus.CollectionGenericObjects /// /// добавляемый объект /// - bool Insert(T obj); + bool Insert(T obj, IEqualityComparer? comparer = null); /// /// вставить по позиции /// /// добавляемый объект /// индекс /// - bool Insert(T obj, int position); + bool Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// удаление /// @@ -53,5 +54,11 @@ namespace AccordionBus.CollectionGenericObjects /// /// IEnumerable GetItems(); + + /// + /// Сортировка коллекции + /// + /// Сравнитель объектов + void CollectionSort(IComparer comparer); } } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs index 6a3f729..87b5648 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,6 @@ -using System; +using AccordionBus.Drawnings; +using AccordionBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -41,27 +43,50 @@ namespace AccordionBus.CollectionGenericObjects return _collection[position]; } - public bool Insert(T obj) + public bool Insert(T obj, IEqualityComparer? comparer = null) { - if (_collection == null || _collection.Count == _maxCount) return false; + if (_collection == null || _collection.Count == _maxCount) throw new CollectionOverflowException(Count); + + foreach (var drawningBus in _collection) + { + if (obj is DrawningBus objdr && drawningBus is DrawningBus bus) + { + if (comparer.Equals(objdr, bus)) throw new ObjectExistsException(); + } + else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa) + { + if (comparer.Equals(objdra, busa)) throw new ObjectExistsException(); + } + } _collection.Add(obj); return true; } - public bool Insert(T obj, int position) + public bool Insert(T obj, int position, IEqualityComparer? comparer = null) { if (_collection == null || position < 0 || position > _maxCount) return false; + foreach (var drawningBus in _collection) + { + if (obj is DrawningBus objdr && drawningBus is DrawningBus bus) + { + if (comparer.Equals(objdr, bus)) throw new ObjectExistsException(); + } + else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa) + { + if (comparer.Equals(objdra, busa)) throw new ObjectExistsException(); + } + } + _collection.Insert(position, obj); return true; } public bool Remove(int position) { - if (_collection == null || position < 0 || position >= _collection.Count) return false; + if (_collection == null || position < 0 || position >= _collection.Count) throw new PozitionOutOfCollectionException(position); - T? obj = _collection[position]; _collection[position] = null; return true; } @@ -73,5 +98,10 @@ namespace AccordionBus.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + _collection.Sort(comparer); + } } } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs index 8050a15..7d33b4c 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -using System; +using AccordionBus.Drawnings; +using AccordionBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata.Ecma335; @@ -39,12 +41,27 @@ namespace AccordionBus.CollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= _collection.Length) return null; + if (position < 0 || position >= _collection.Length) + { + throw new PozitionOutOfCollectionException(position); + } return _collection[position]; } - public bool Insert(T obj) + public bool Insert(T obj, IEqualityComparer? comparer = null) { + foreach(var drawningBus in _collection) + { + if (obj is DrawningBus objdr && drawningBus is DrawningBus bus) + { + if (comparer.Equals(objdr, bus)) throw new ObjectExistsException(); + } + else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa) + { + if (comparer.Equals(objdra, busa)) throw new ObjectExistsException(); + } + } + for (int i = 0; i < _collection.Length; i++) { if (_collection[i] == null) @@ -53,12 +70,24 @@ namespace AccordionBus.CollectionGenericObjects return true; } } - return false; + throw new CollectionOverflowException(Count); } - public bool Insert(T obj, int position) + public bool Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0 || position >= _collection.Length) { return false; } + if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(position); + + foreach (var drawningBus in _collection) + { + if (obj is DrawningBus objdr && drawningBus is DrawningBus bus) + { + if (comparer.Equals(objdr, bus)) throw new ObjectExistsException(); + } + else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa) + { + if (comparer.Equals(objdra, busa)) throw new ObjectExistsException(); + } + } if (_collection[position] == null) { @@ -85,14 +114,14 @@ namespace AccordionBus.CollectionGenericObjects } } } - return false; + throw new CollectionOverflowException(Count); } public bool Remove(int position) { - if (position < 0 || position >= _collection.Length) { return false;} + if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); - T? obj = _collection[position]; _collection[position] = null; return true; } @@ -104,5 +133,10 @@ namespace AccordionBus.CollectionGenericObjects yield return _collection[i]; } } + + public void CollectionSort(IComparer comparer) + { + Array.Sort(_collection, comparer); + } } } diff --git a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs index c1f6f09..93a265e 100644 --- a/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs +++ b/AccordionBus/AccordionBus/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using AccordionBus.Drawnings; +using AccordionBus.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -11,9 +12,9 @@ namespace AccordionBus.CollectionGenericObjects public class StorageCollection where T: DrawningBus { - readonly Dictionary> _storage; + readonly Dictionary> _storage; - public List Keys => _storage.Keys.ToList(); + public List Keys => _storage.Keys.ToList(); private readonly string _collectionKey = "CollectionStorage"; @@ -23,35 +24,37 @@ namespace AccordionBus.CollectionGenericObjects public StorageCollection() { - _storage = new Dictionary>(); + _storage = new Dictionary>(); } public void AddCollection(string name, CollectionType collectionType) { - if (_storage.ContainsKey(name) || name == "") return; + CollectionInfo info = new CollectionInfo(name, collectionType, ""); - _storage[name] = CreateCollection(collectionType); + if (_storage.ContainsKey(info) || info.Name == "") return; + + _storage[info] = CreateCollection(info.CollectionType); } public void DelCollection(string name) { - _storage.Remove(name); + _storage.Remove(new CollectionInfo(name, CollectionType.None, "")); } public ICollectionGenericObjects? this[string name] { get { - if (!_storage.ContainsKey(name)) return null; - return _storage[name]; + if (!_storage.ContainsKey(new CollectionInfo(name, CollectionType.None, ""))) return null; + return _storage[new CollectionInfo(name, CollectionType.None, "")]; } } - public bool SaveData(string filename) + public void SaveData(string filename) { if (_storage.Count == 0) { - return false; + throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -60,7 +63,7 @@ namespace AccordionBus.CollectionGenericObjects using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); - foreach (KeyValuePair> value in _storage) + foreach (KeyValuePair> value in _storage) { StringBuilder sb = new(); sb.Append(Environment.NewLine); @@ -71,8 +74,6 @@ namespace AccordionBus.CollectionGenericObjects } sb.Append(value.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); sb.Append(value.Value.MaxCount); sb.Append(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) @@ -87,57 +88,68 @@ namespace AccordionBus.CollectionGenericObjects } writer.Write(sb); } - return true; } } - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new FileNotFoundException("Файл не существует"); } using (StreamReader reader = File.OpenText(filename)) { string str = reader.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new InvalidOperationException("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new InvalidOperationException("В файле не верные данные"); } _storage.Clear(); string strs = ""; while ((strs = reader.ReadLine()) != null) { string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 4) + if (record.Length != 3) { continue; } - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? + throw new InvalidOperationException("Не удалось определить информацию об коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.CollectionType); if (collection == null) { - return false; + throw new InvalidOperationException("Не удалось создать коллекцию"); } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningBus() is T bus) { - if (!collection.Insert(bus)) + try { - return false; + if (!collection.Insert(bus)) + { + throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[2]); + } + } + catch(ObjectExistsException ex) + { + throw new InvalidOperationException(ex.Message); + } + catch (CollectionOverflowException ex) + { + throw new InvalidOperationException("Коллекция переполнена", ex); } } } - _storage.Add(record[0], collection); + + _storage.Add(collectionInfo, collection); } - return true; } } diff --git a/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByColor.cs b/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByColor.cs new file mode 100644 index 0000000..b5d48af --- /dev/null +++ b/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByColor.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Drawnings +{ + public class DrawningBusCompareByColor : IComparer + { + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null && y == null) return 0; + + if (x == null || x.EntityBus == null) return 1; + + if (y == null || y.EntityBus == null) return -1; + + if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) + { + var redCompare = x.EntityBus.BodyColor.R.CompareTo(y.EntityBus.BodyColor.R); + if (redCompare != 0) return redCompare; + + var blueCompare = x.EntityBus.BodyColor.B.CompareTo(y.EntityBus.BodyColor.B); + if (blueCompare != 0) return blueCompare; + + return x.EntityBus.BodyColor.G.CompareTo(y.EntityBus.BodyColor.G); + } + + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) return speedCompare; + + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + } +} diff --git a/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByType.cs b/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByType.cs new file mode 100644 index 0000000..a1616e6 --- /dev/null +++ b/AccordionBus/AccordionBus/Drawnings/DrawningBusCompareByType.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Policy; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Drawnings +{ + public class DrawningBusCompareByType : IComparer + { + public int Compare(DrawningBus? x, DrawningBus? y) + { + if (x == null && y == null) return 0; + + if (x == null || x.EntityBus == null) return 1; + + if (y == null || y.EntityBus == null) return -1; + + if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name); + + var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed); + if (speedCompare != 0) return speedCompare; + + return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight); + } + } +} diff --git a/AccordionBus/AccordionBus/Drawnings/DrawningBusEqutables.cs b/AccordionBus/AccordionBus/Drawnings/DrawningBusEqutables.cs new file mode 100644 index 0000000..c06bf37 --- /dev/null +++ b/AccordionBus/AccordionBus/Drawnings/DrawningBusEqutables.cs @@ -0,0 +1,47 @@ +using AccordionBus.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Drawnings +{ + public class DrawningBusEqutables : IEqualityComparer + { + public bool Equals(DrawningBus? x, DrawningBus? y) + { + if (x == null || x.EntityBus == null) return false; + + if (y == null || y.EntityBus == null) return false; + + if (x.GetType().Name != y.GetType().Name) return false; + + if (x.EntityBus.Speed != y.EntityBus.Speed) return false; + + if (x.EntityBus.Weight != y.EntityBus.Weight) return false; + + if (x.EntityBus.BodyColor != y.EntityBus.BodyColor) return false; + + if (x is DrawningAccordionBus xa && y is DrawningAccordionBus ya) + { + if (xa.EntityBus is EntityAccordionBus ex && ya.EntityBus is EntityAccordionBus ey) + { + if (ex.AdditionalColor != ey.AdditionalColor) return false; + + if (ex.FiveDoors != ey.FiveDoors) return false; + + if (ex.Hatch != ey.Hatch) return false; + } + } + + return true; + } + + public int GetHashCode([DisallowNull] DrawningBus? obj) + { + return obj.GetHashCode(); + } + } +} diff --git a/AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs b/AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..4c79e37 --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Exceptions +{ + [Serializable] + public class CollectionOverflowException : ApplicationException + { + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count : " + count) { } + + public CollectionOverflowException() : base() { } + + public CollectionOverflowException(string message) : base(message) { } + + public CollectionOverflowException(string message, Exception exception) : base(message, exception) { } + + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/AccordionBus/AccordionBus/Exceptions/ObjectExistsException.cs b/AccordionBus/AccordionBus/Exceptions/ObjectExistsException.cs new file mode 100644 index 0000000..1e6e82c --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/ObjectExistsException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Exceptions +{ + public class ObjectExistsException : ApplicationException + { + public ObjectExistsException() : base("Такой объект уже есть в соллекции") { } + + public ObjectExistsException(string message) : base(message) { } + + public ObjectExistsException(string message, Exception exception) : base(message, exception) { } + + public ObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs b/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..b2165c0 --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Exceptions +{ + [Serializable] + public 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 context) : base(info, context) { } + } +} diff --git a/AccordionBus/AccordionBus/Exceptions/PozitionOutOfCollectionException.cs b/AccordionBus/AccordionBus/Exceptions/PozitionOutOfCollectionException.cs new file mode 100644 index 0000000..ae616f3 --- /dev/null +++ b/AccordionBus/AccordionBus/Exceptions/PozitionOutOfCollectionException.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AccordionBus.Exceptions +{ + [Serializable] + public class PozitionOutOfCollectionException : ApplicationException + { + public PozitionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + + public PozitionOutOfCollectionException() : base() { } + + public PozitionOutOfCollectionException(string message) : base(message) { } + + public PozitionOutOfCollectionException(string message, Exception exception) : base(message, exception) { } + + protected PozitionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/AccordionBus/AccordionBus/FormBusCollection.Designer.cs b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs index a4f3567..cef7da5 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.Designer.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByColor = new Button(); + buttonSortByType = new Button(); groupBoxTools.SuspendLayout(); panelStorage.SuspendLayout(); panelTools.SuspendLayout(); @@ -68,7 +70,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(948, 28); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(234, 725); + groupBoxTools.Size = new Size(234, 801); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -178,6 +180,8 @@ // // panelTools // + panelTools.Controls.Add(buttonSortByColor); + panelTools.Controls.Add(buttonSortByType); panelTools.Controls.Add(buttonAddBus); panelTools.Controls.Add(buttonRefresh); panelTools.Controls.Add(maskedTextBox); @@ -187,7 +191,7 @@ panelTools.Enabled = false; panelTools.Location = new Point(3, 396); panelTools.Name = "panelTools"; - panelTools.Size = new Size(228, 326); + panelTools.Size = new Size(228, 402); panelTools.TabIndex = 7; // // buttonAddBus @@ -202,7 +206,7 @@ // // buttonRefresh // - buttonRefresh.Location = new Point(9, 265); + buttonRefresh.Location = new Point(9, 226); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(207, 54); buttonRefresh.TabIndex = 6; @@ -212,7 +216,7 @@ // // maskedTextBox // - maskedTextBox.Location = new Point(9, 112); + maskedTextBox.Location = new Point(9, 73); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(207, 27); @@ -221,7 +225,7 @@ // // buttonGoToCheck // - buttonGoToCheck.Location = new Point(9, 205); + buttonGoToCheck.Location = new Point(9, 166); buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Size = new Size(207, 54); buttonGoToCheck.TabIndex = 5; @@ -231,7 +235,7 @@ // // buttonRemoveBus // - buttonRemoveBus.Location = new Point(9, 145); + buttonRemoveBus.Location = new Point(9, 106); buttonRemoveBus.Name = "buttonRemoveBus"; buttonRemoveBus.Size = new Size(207, 54); buttonRemoveBus.TabIndex = 4; @@ -244,7 +248,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(948, 725); + pictureBox.Size = new Size(948, 801); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -289,11 +293,31 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByColor + // + buttonSortByColor.Location = new Point(9, 346); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(207, 54); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортирока по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // + // buttonSortByType + // + buttonSortByType.Location = new Point(9, 286); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(207, 54); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // // FormBusCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1182, 753); + ClientSize = new Size(1182, 829); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -339,5 +363,7 @@ private ToolStripMenuItem loadToolStripMenuItem; private SaveFileDialog saveFileDialog; private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/FormBusCollection.cs b/AccordionBus/AccordionBus/FormBusCollection.cs index 0256288..04f9378 100644 --- a/AccordionBus/AccordionBus/FormBusCollection.cs +++ b/AccordionBus/AccordionBus/FormBusCollection.cs @@ -1,5 +1,7 @@ using AccordionBus.CollectionGenericObjects; using AccordionBus.Drawnings; +using AccordionBus.Exceptions; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -19,10 +21,13 @@ namespace AccordionBus private AbstractCompany? _company = null; - public FormBusCollection() + private readonly ILogger _logger; + + public FormBusCollection(ILogger logger) { InitializeComponent(); _storageCollection = new StorageCollection(); + _logger = logger; } private void comboBoxSelectedCompany_SelectedIndexChanged(object sender, EventArgs e) @@ -43,14 +48,24 @@ namespace AccordionBus bus.SetPictureSize(pictureBox.Width, pictureBox.Height); - if (_company + bus) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company + bus) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект добавлен в коллекцию, " + bus.GetDataForSave()); + } } - else + catch (ObjectExistsException ex) { - MessageBox.Show("Объект не удалось добавить"); + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {message}", ex.Message); + } + catch (CollectionOverflowException ex) + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {message}", ex.Message); } } @@ -62,14 +77,24 @@ namespace AccordionBus MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos) + try { - MessageBox.Show("Объект удалён"); - pictureBox.Image = _company.Show(); + if (_company - pos) + { + MessageBox.Show("Объект удалён"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Объект по позиции {0} удалён", pos); + } } - else + catch (PozitionOutOfCollectionException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Не удалось удалить объект. Не верно указана позиция"); + _logger.LogError("Ошибка: {message}", ex.Message); + } + catch (ObjectNotFoundException ex) + { + MessageBox.Show("Не удалось удалить объект, его не существует"); + _logger.LogError("Ошибка: {message}", ex.Message); } } @@ -79,10 +104,17 @@ namespace AccordionBus DrawningBus? bus = null; int counter = 100; - while (bus == null && counter > 0) + try { - bus = _company.GetRandomObject(); - counter--; + while (bus == null && counter > 0) + { + bus = _company.GetRandomObject(); + counter--; + } + } + catch (PozitionOutOfCollectionException ex) + { + _logger.LogError("Ошибка: {message}", ex.Message); } if (bus == null) return; @@ -115,8 +147,10 @@ namespace AccordionBus else if (radioButtonList.Checked) collectionType = CollectionType.List; _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавлена новая коллекция {0}", textBoxCollectionName.Text); textBoxCollectionName.Text = ""; RefreshListBoxItems(); + } private void buttonCollectionDel_Click(object sender, EventArgs e) @@ -129,10 +163,12 @@ namespace AccordionBus _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RefreshListBoxItems(); MessageBox.Show("Компания удалена"); + _logger.LogInformation("Компания удалена"); } else { MessageBox.Show("Не удалось удалить компанию"); + _logger.LogError("Ошибка: не удалось удалить компанию"); } } @@ -158,6 +194,7 @@ namespace AccordionBus case "Станция": _company = new BusStation(pictureBox.Width, pictureBox.Height, collection); pictureBox.Image = _company.Show(); + break; } @@ -169,7 +206,7 @@ namespace AccordionBus listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; i++) { - string? colName = _storageCollection.Keys?[i]; + string? colName = _storageCollection.Keys?[i].Name; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); @@ -181,15 +218,18 @@ namespace AccordionBus { 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("Ошибка: {message}", ex.Message); } } } @@ -198,18 +238,39 @@ namespace AccordionBus { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RefreshListBoxItems(); + _logger.LogInformation("Загрузка из файла {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {message}", ex.Message); } } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + CompareBuses(new DrawningBusCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + CompareBuses(new DrawningBusCompareByColor()); + } + + private void CompareBuses(IComparer comparer) + { + if (_company == null) return; + + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } } diff --git a/AccordionBus/AccordionBus/Program.cs b/AccordionBus/AccordionBus/Program.cs index c6b7d4c..43b17bc 100644 --- a/AccordionBus/AccordionBus/Program.cs +++ b/AccordionBus/AccordionBus/Program.cs @@ -1,3 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; + namespace AccordionBus { internal static class Program @@ -10,8 +16,24 @@ namespace AccordionBus { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ServiceCollection services = new(); + ConfigureServices(services); ApplicationConfiguration.Initialize(); - Application.Run(new FormBusCollection()); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => { + option.SetMinimumLevel(LogLevel.Debug); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile("C:\\Users\\Professional\\Desktop\\labs\\8\\AccordionBus\\AccordionBus\\serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/AccordionBus/AccordionBus/serilog.json b/AccordionBus/AccordionBus/serilog.json new file mode 100644 index 0000000..ada83c4 --- /dev/null +++ b/AccordionBus/AccordionBus/serilog.json @@ -0,0 +1,18 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs\\log.txt", + "outputTemplate": "[{Level:u}] [{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}] {Message:1j}{NewLine}{Exception}" + } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file