From f655c6b4bb852fa5b02864912673503c66c9b9e8 Mon Sep 17 00:00:00 2001 From: Timur_Sharafutdinov Date: Mon, 13 May 2024 11:43:03 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 7 +- .../CollectionInfo.cs | 66 ++++++++++++++++ .../ICollectionGenericObjects.cs | 15 +++- .../ListGenericObjects.cs | 35 +++++++-- .../MassivGenericObjects.cs | 77 +++++++++++++------ .../StorageCollection.cs | 51 ++++++------ .../Drawning/DrawningCraneCompareByColor.cs | 19 +++++ .../Drawning/DrawningCraneCompareByType.cs | 21 +++++ .../Drawning/DrawningCraneEqutables.cs | 32 ++++++++ ...ObjectIsPresentInTheCollectionException.cs | 18 +++++ .../FormCarCollection.Designer.cs | 64 ++++++++++----- .../HoistingCrane/FormCarCollection.cs | 36 ++++++--- 12 files changed, 352 insertions(+), 89 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs create mode 100644 HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs create mode 100644 HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByType.cs create mode 100644 HoistingCrane/HoistingCrane/Drawning/DrawningCraneEqutables.cs create mode 100644 HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index fb26d02..94b5609 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -42,7 +42,7 @@ namespace HoistingCrane.CollectionGenericObjects } public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) { - return company.arr?.Insert(car) ?? -1; + return company.arr?.Insert(car, new DrawningCraneEqutables()) ?? -1; } public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) { @@ -84,5 +84,10 @@ namespace HoistingCrane.CollectionGenericObjects /// Расстановка объектов /// protected abstract void SetObjectsPosition(); + /// + /// Сортировка + /// + /// + public void Sort(IComparer comparer) => arr?.CollectionSort(comparer); } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs new file mode 100644 index 0000000..5762d92 --- /dev/null +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs @@ -0,0 +1,66 @@ +using System.Diagnostics.CodeAnalysis; + +namespace HoistingCrane.CollectionGenericObjects +{ + public class CollectionInfo : IEquatable + { + /// + /// Название + /// + public string name { get; private set; } + /// + /// Тип + /// + public CollectionType collectionType { get; private set; } + /// + /// Описание + /// + public string description { get; private set; } + /// + /// Разделитель + /// + public static readonly string _separator = "-"; + + /// + /// Конструктор + /// + /// + /// + /// + public CollectionInfo(string name, CollectionType collectionType, string description) + { + this.name = name; + this.collectionType = collectionType; + this.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] : string.Empty); + } + + public override string ToString() + { + return name + _separator + collectionType + _separator + description; + } + + public bool Equals(CollectionInfo? other) + { + if(other == null) return false; + if (name != other.name) return false; + return true; + } + + public override bool Equals(object? obj) + { + return Equals(obj as CollectionInfo); + } + + public override int GetHashCode() + { + return name.GetHashCode(); + } + } +} diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs index ae99e89..1fb465a 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,4 +1,6 @@ -namespace HoistingCrane.CollectionGenericObjects +using HoistingCrane.Drawning; + +namespace HoistingCrane.CollectionGenericObjects { public interface ICollectionGenericObjects where T: class @@ -15,15 +17,17 @@ /// Добавление элемента в коллекцию /// /// + /// /// Сравнение двух объектов /// - int Insert(T obj); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление элемента в коллекцию на определенную позицию /// /// /// + /// Сравнение двух объектов /// - int Insert(T obj, int position); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление элемента из коллекции по его позиции /// @@ -45,5 +49,10 @@ /// /// IEnumerable GetItems(); + /// + /// Сортировка коллекции + /// + /// + void CollectionSort(IComparer comparer); } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index 7503bb0..66feeeb 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using HoistingCrane.Exceptions; +using HoistingCrane.Drawning; +using HoistingCrane.Exceptions; namespace HoistingCrane.CollectionGenericObjects { public class ListGenericObjects : ICollectionGenericObjects where T : class @@ -46,20 +47,33 @@ namespace HoistingCrane.CollectionGenericObjects return list[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (Count == _maxCount) + // TODO выброс ошибки, если такой объект есть в коллекции + if (comparer != null && list.Contains(obj)) { - throw new CollectionOverflowException(Count); + throw new ObjectIsPresentInTheCollectionException(obj); + } + if (list.Count >= _maxCount) + { + throw new CollectionOverflowException(_maxCount); } list.Add(obj); - return Count; + return _maxCount; } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); - if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (comparer != null && list.Contains(obj)) + { + throw new ObjectIsPresentInTheCollectionException(); + } + if (Count >= _maxCount) + throw new CollectionOverflowException(_maxCount); + + if (position < 0 || position >= _maxCount) + throw new PositionOutOfCollectionException(position); + list.Insert(position, obj); return position; } @@ -79,5 +93,10 @@ namespace HoistingCrane.CollectionGenericObjects yield return list[i]; } } + + public void CollectionSort(IComparer comparer) + { + list.Sort(comparer); + } } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs index 43df118..f96e396 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs @@ -1,4 +1,6 @@ -using HoistingCrane.Exceptions; +using HoistingCrane.Drawning; +using HoistingCrane.Exceptions; + namespace HoistingCrane.CollectionGenericObjects { public class MassivGenericObjects : ICollectionGenericObjects where T : class @@ -42,41 +44,65 @@ namespace HoistingCrane.CollectionGenericObjects return arr[position]; } - public int Insert(T obj) + public int Insert(T obj, IEqualityComparer? comparer = null) { - int countObjectNotNull = 0; - for(int i = 0; i < Count; i++) + if (comparer != null) { - if (arr[i] != null) countObjectNotNull += 1; + foreach (T? item in arr) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) + throw new ObjectIsPresentInTheCollectionException(); + } } - if(countObjectNotNull == MaxCount) throw new CollectionOverflowException(Count); - return Insert(obj, 0); + int index = 0; + while (index < arr.Length) + { + if (arr[index] == null) + { + arr[index] = obj; + return index; + } + index++; + } + throw new CollectionOverflowException(Count); } - public int Insert(T obj, int position) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (position < 0 || position >= Count) + if (comparer != null) { - throw new PositionOutOfCollectionException(position); + foreach (T? item in arr) + { + if ((comparer as IEqualityComparer).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) + throw new ObjectIsPresentInTheCollectionException(); + } } - int copyPos = position - 1; - while (position < Count) + if (position >= arr.Length || position < 0) throw new PositionOutOfCollectionException(position); + + if (arr[position] == null) { - if (arr[position] == null) - { - arr[position] = obj; - return position; - } - position++; + arr[position] = obj; + return position; } - while (copyPos > 0) + int index = position + 1; + while (index < arr.Length) { - if (arr[copyPos] == null) + if (arr[index] == null) { - arr[copyPos] = obj; - return copyPos; + arr[index] = obj; + return index; } - copyPos--; + index++; + } + index = position - 1; + while (index >= 0) + { + if (arr[index] == null) + { + arr[index] = obj; + return index; + } + index--; } throw new CollectionOverflowException(Count); } @@ -97,5 +123,10 @@ namespace HoistingCrane.CollectionGenericObjects yield return arr[i]; } } + public void CollectionSort(IComparer comparer) + { + T[] notNullArr = arr.OfType().ToArray(); + Array.Sort(notNullArr, comparer); + } } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs index 7ac7b49..07ea4c1 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs @@ -8,11 +8,11 @@ namespace HoistingCrane.CollectionGenericObjects /// /// Словарь (хранилище) с коллекциями /// - readonly Dictionary> dict; + readonly Dictionary> dict; /// /// Возвращение списка названий коллекций /// - public List Keys => dict.Keys.ToList(); + public List Keys => dict.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл /// @@ -30,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects /// public StorageCollection() { - dict = new Dictionary>(); + dict = new Dictionary>(); } /// /// Добавление коллекции в хранилище @@ -39,15 +39,16 @@ namespace HoistingCrane.CollectionGenericObjects /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { - if (!string.IsNullOrEmpty(name) && !Keys.Contains(name)) + var collectionInfo = new CollectionInfo(name, collectionType, " "); + if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo)) { - if(collectionType == CollectionType.Massive) + if (collectionType == CollectionType.Massive) { - dict.Add(name, new MassivGenericObjects ()); + dict.Add(collectionInfo, new MassivGenericObjects ()); } if(collectionType == CollectionType.List) { - dict.Add(name, new ListGenericObjects ()); + dict.Add(collectionInfo, new ListGenericObjects ()); } } } @@ -57,8 +58,11 @@ namespace HoistingCrane.CollectionGenericObjects /// Название коллекции public void DelCollection(string name) { - if (dict.ContainsKey(name)) - dict.Remove(name); + var key = dict.Keys.FirstOrDefault(k => k.name == name); + if (key != null) + { + dict.Remove(key); + } } /// /// Доступ к коллекции @@ -69,8 +73,9 @@ namespace HoistingCrane.CollectionGenericObjects { get { - if (name == null || !dict.ContainsKey(name)) { return null; } - return dict[name]; + var key = dict.Keys.FirstOrDefault(k => k.name == name); + if (key == null) { return null; } + return dict[key]; } } /// @@ -94,20 +99,16 @@ namespace HoistingCrane.CollectionGenericObjects { writer.Write(_collectionKey); - foreach (KeyValuePair> value in dict) + foreach (KeyValuePair> value in dict) { StringBuilder sb = new(); sb.Append(Environment.NewLine); - - // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } 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()) @@ -152,18 +153,14 @@ namespace HoistingCrane.CollectionGenericObjects while ((strs = fs.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); - if (collection == null) - { - throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); - } - collection.MaxCount = Convert.ToInt32(record[2]); - string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new InvalidOperationException("Не удалось определить информацию о коллекции: " + record[0]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionInfo.collectionType) ?? throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); + collection.MaxCount = Convert.ToInt32(record[1]); + string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningTrackedVehicle() is T crane) @@ -172,7 +169,7 @@ namespace HoistingCrane.CollectionGenericObjects { if (collection.Insert(crane) == -1) { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); + throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[2]); } } catch(CollectionOverflowException ex) @@ -181,7 +178,7 @@ namespace HoistingCrane.CollectionGenericObjects } } } - dict.Add(record[0], collection); + dict.Add(collectionInfo, collection); } } } diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs new file mode 100644 index 0000000..8e76d17 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs @@ -0,0 +1,19 @@ +namespace HoistingCrane.Drawning +{ + public class DrawningCraneCompareByColor : IComparer + { + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + //TODO: Прописать логику сравнения по цветам, скорости и весу + if (x == null || x.EntityTrackedVehicle == null) return -1; + if (y == null || y.EntityTrackedVehicle == null) return 1; + var colorCompare = x.EntityTrackedVehicle.BodyColor.ToArgb().CompareTo(y.EntityTrackedVehicle.BodyColor.ToArgb()); + if (colorCompare != 0) return colorCompare; + var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed); + if (speedCompare != 0) return speedCompare; + return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight); + } + } +} + + diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByType.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByType.cs new file mode 100644 index 0000000..b2e59ef --- /dev/null +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByType.cs @@ -0,0 +1,21 @@ +namespace HoistingCrane.Drawning +{ + public class DrawningCraneCompareByType : IComparer + { + /// + /// Сравнение по типу, скорости и весу + /// + /// + /// + /// + public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) return -1; + if (y == null || y.EntityTrackedVehicle == null) return 1; + if (x.GetType().Name != y.GetType().Name) return x.GetType().Name.CompareTo(y.GetType().Name); + var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed); + if(speedCompare != 0) return speedCompare; + return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight); + } + } +} diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningCraneEqutables.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneEqutables.cs new file mode 100644 index 0000000..432dd15 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneEqutables.cs @@ -0,0 +1,32 @@ +using HoistingCrane.Entities; +using System.Diagnostics.CodeAnalysis; + +namespace HoistingCrane.Drawning +{ + public class DrawningCraneEqutables : IEqualityComparer + { + public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) + { + if (x == null || x.EntityTrackedVehicle == null) return false; + if (y == null || y.EntityTrackedVehicle == null) return false; + if (x.GetType().Name != y.GetType().Name) return false; + if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed) return false; + if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight) return false; + if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor) return false; + if ((x.EntityTrackedVehicle as EntityHoistingCrane)!= null && (y.EntityTrackedVehicle as EntityHoistingCrane)!=null) + { + var newX = x.EntityTrackedVehicle as EntityHoistingCrane; + var newY = y.EntityTrackedVehicle as EntityHoistingCrane; + if (newX?.AdditionalColor != newY?.AdditionalColor) return false; + if (newX?.Platform != newY?.Platform) return false; + if (newX?.Counterweight != newY?.Counterweight) return false; + } + return true; + } + + public int GetHashCode([DisallowNull] DrawningTrackedVehicle obj) + { + return obj.GetHashCode(); + } + } +} diff --git a/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs b/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs new file mode 100644 index 0000000..d659852 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Exceptions +{ + public class ObjectIsPresentInTheCollectionException : ApplicationException + { + public ObjectIsPresentInTheCollectionException(object obj) : base("В коллекции уже присустствует объект " + obj) { } + public ObjectIsPresentInTheCollectionException() : base() { } + public ObjectIsPresentInTheCollectionException(string message) : base(message) { } + public ObjectIsPresentInTheCollectionException(string message, Exception exception) : base(message, exception) { } + protected ObjectIsPresentInTheCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs b/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs index 4991414..2405784 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs @@ -52,6 +52,8 @@ loadToolStripMenuItem = new ToolStripMenuItem(); saveFileDialog = new SaveFileDialog(); openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); panelCompanyTool.SuspendLayout(); panelStorage.SuspendLayout(); @@ -68,7 +70,7 @@ groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Location = new Point(763, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(210, 485); + groupBoxTools.Size = new Size(210, 524); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; @@ -76,20 +78,22 @@ // panelCompanyTool // panelCompanyTool.Anchor = AnchorStyles.None; + panelCompanyTool.Controls.Add(buttonSortByColor); + panelCompanyTool.Controls.Add(buttonSortByType); panelCompanyTool.Controls.Add(buttonCreateHoistingCrane); panelCompanyTool.Controls.Add(maskedTextBox); panelCompanyTool.Controls.Add(buttonRefresh); panelCompanyTool.Controls.Add(buttonGoToChek); panelCompanyTool.Controls.Add(buttonDeleteCar); - panelCompanyTool.Location = new Point(6, 312); + panelCompanyTool.Location = new Point(6, 296); panelCompanyTool.Name = "panelCompanyTool"; - panelCompanyTool.Size = new Size(204, 185); + panelCompanyTool.Size = new Size(204, 221); panelCompanyTool.TabIndex = 8; // // buttonCreateHoistingCrane // buttonCreateHoistingCrane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonCreateHoistingCrane.Location = new Point(9, 13); + buttonCreateHoistingCrane.Location = new Point(6, 3); buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane"; buttonCreateHoistingCrane.Size = new Size(192, 22); buttonCreateHoistingCrane.TabIndex = 0; @@ -100,7 +104,7 @@ // maskedTextBox // maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(9, 41); + maskedTextBox.Location = new Point(6, 31); maskedTextBox.Mask = "00"; maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Size = new Size(192, 23); @@ -109,7 +113,7 @@ // buttonRefresh // buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(9, 129); + buttonRefresh.Location = new Point(6, 119); buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(192, 27); buttonRefresh.TabIndex = 5; @@ -120,7 +124,7 @@ // buttonGoToChek // buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToChek.Location = new Point(9, 99); + buttonGoToChek.Location = new Point(6, 89); buttonGoToChek.Name = "buttonGoToChek"; buttonGoToChek.Size = new Size(192, 24); buttonGoToChek.TabIndex = 6; @@ -131,7 +135,7 @@ // buttonDeleteCar // buttonDeleteCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDeleteCar.Location = new Point(9, 70); + buttonDeleteCar.Location = new Point(6, 60); buttonDeleteCar.Name = "buttonDeleteCar"; buttonDeleteCar.Size = new Size(192, 23); buttonDeleteCar.TabIndex = 4; @@ -141,7 +145,7 @@ // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(12, 295); + buttonCreateCompany.Location = new Point(12, 267); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(192, 23); buttonCreateCompany.TabIndex = 7; @@ -161,12 +165,12 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 19); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(204, 229); + panelStorage.Size = new Size(204, 216); panelStorage.TabIndex = 7; // // buttonDeleteCollection // - buttonDeleteCollection.Location = new Point(9, 199); + buttonDeleteCollection.Location = new Point(9, 186); buttonDeleteCollection.Name = "buttonDeleteCollection"; buttonDeleteCollection.Size = new Size(192, 27); buttonDeleteCollection.TabIndex = 6; @@ -178,14 +182,14 @@ // listBoxCollection.FormattingEnabled = true; listBoxCollection.ItemHeight = 15; - listBoxCollection.Location = new Point(9, 118); + listBoxCollection.Location = new Point(9, 101); listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Size = new Size(192, 79); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd // - buttonCollectionAdd.Location = new Point(9, 81); + buttonCollectionAdd.Location = new Point(9, 72); buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Size = new Size(192, 23); buttonCollectionAdd.TabIndex = 4; @@ -196,7 +200,7 @@ // radioButtonList // radioButtonList.AutoSize = true; - radioButtonList.Location = new Point(128, 56); + radioButtonList.Location = new Point(128, 47); radioButtonList.Name = "radioButtonList"; radioButtonList.Size = new Size(67, 19); radioButtonList.TabIndex = 3; @@ -207,7 +211,7 @@ // radioButtonMassive // radioButtonMassive.AutoSize = true; - radioButtonMassive.Location = new Point(18, 56); + radioButtonMassive.Location = new Point(12, 47); radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Size = new Size(69, 19); radioButtonMassive.TabIndex = 2; @@ -237,7 +241,7 @@ comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(12, 266); + comboBoxSelectorCompany.Location = new Point(12, 238); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(192, 23); comboBoxSelectorCompany.TabIndex = 2; @@ -248,7 +252,7 @@ pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(763, 485); + pictureBox.Size = new Size(763, 524); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // @@ -292,11 +296,33 @@ // openFileDialog.Filter = "txt file | *.txt"; // + // buttonSortByType + // + buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByType.Location = new Point(6, 152); + buttonSortByType.Name = "buttonSortByType"; + buttonSortByType.Size = new Size(192, 27); + buttonSortByType.TabIndex = 7; + buttonSortByType.Text = "Сортировка по типу"; + buttonSortByType.UseVisualStyleBackColor = true; + buttonSortByType.Click += buttonSortByType_Click; + // + // buttonSortByColor + // + buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonSortByColor.Location = new Point(6, 185); + buttonSortByColor.Name = "buttonSortByColor"; + buttonSortByColor.Size = new Size(192, 27); + buttonSortByColor.TabIndex = 8; + buttonSortByColor.Text = "Сортировка по цвету"; + buttonSortByColor.UseVisualStyleBackColor = true; + buttonSortByColor.Click += buttonSortByColor_Click; + // // FormCarCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(973, 509); + ClientSize = new Size(973, 548); Controls.Add(pictureBox); Controls.Add(groupBoxTools); Controls.Add(menuStrip); @@ -341,5 +367,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/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index 318a373..b4cf3d6 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -52,7 +52,7 @@ namespace HoistingCrane MessageBox.Show("Ошибка переполнения коллекции"); logger.LogError("Ошибка: {Message}", ex.Message); } - + } private void buttonDeleteCar_Click(object sender, EventArgs e) @@ -123,7 +123,7 @@ namespace HoistingCrane 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); @@ -149,7 +149,8 @@ namespace HoistingCrane collectionType = CollectionType.List; logger.LogInformation("Создана коллекция '{nameCol}' , название: {name}", collectionType, textBoxCollectionName.Text); } - _storageCollection.AddCollection(textBoxCollectionName.Text,collectionType);RerfreshListBoxItems(); + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); } private void buttonDeleteCollection_Click(object sender, EventArgs e) { @@ -166,18 +167,18 @@ namespace HoistingCrane } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); - + } private void buttonCreateCompany_Click(object sender, EventArgs e) { - - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) + if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; @@ -222,7 +223,7 @@ namespace HoistingCrane /// private void loadToolStripMenuItem_Click(object sender, EventArgs e) { - if(openFileDialog.ShowDialog() == DialogResult.OK) + if (openFileDialog.ShowDialog() == DialogResult.OK) { try { @@ -231,13 +232,30 @@ namespace HoistingCrane MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); logger.LogInformation("Загрузка в файл: {filename}", saveFileDialog.FileName); } - catch(Exception ex) + catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogError("Ошибка: {Message}", ex.Message); } } } + + private void buttonSortByType_Click(object sender, EventArgs e) + { + compareCars(new DrawningCraneCompareByType()); + } + + private void buttonSortByColor_Click(object sender, EventArgs e) + { + compareCars(new DrawningCraneCompareByColor()); + } + + private void compareCars(IComparer comparer) + { + if (_company == null) return; + _company.Sort(comparer); + pictureBox.Image = _company.Show(); + } } } From 0d5ea4481fee4c7d720bfe71c8cfdaa1cd37ba62 Mon Sep 17 00:00:00 2001 From: sqdselo <147947144+sqdselo@users.noreply.github.com> Date: Wed, 5 Jun 2024 06:51:03 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=208?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCompany.cs | 6 +- .../ICollectionGenericObjects.cs | 4 +- .../ListGenericObjects.cs | 48 ++++---- .../MassivGenericObjects.cs | 107 ++++++++++-------- .../Drawning/DrawningCraneCompareByColor.cs | 5 +- .../Drawning/StorageEqutables.cs | 12 ++ ...ObjectIsPresentInTheCollectionException.cs | 12 +- .../HoistingCrane/FormCarCollection.cs | 4 +- .../HoistingCrane/HoistingCrane.csproj | 1 + HoistingCrane/HoistingCrane/Program.cs | 26 +++-- HoistingCrane/HoistingCrane/serilog.json | 17 +++ 11 files changed, 150 insertions(+), 92 deletions(-) create mode 100644 HoistingCrane/HoistingCrane/Drawning/StorageEqutables.cs create mode 100644 HoistingCrane/HoistingCrane/serilog.json diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index 94b5609..9608211 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -30,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects { get { - return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-2; + return (pictureWidth / _placeSizeWidth) * (pictureHeight * _placeSizeHeight); } } public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects array) @@ -42,11 +42,11 @@ namespace HoistingCrane.CollectionGenericObjects } public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) { - return company.arr?.Insert(car, new DrawningCraneEqutables()) ?? -1; + return company.arr.Insert(car, new DrawningCraneEqutables()); } public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) { - return company.arr?.Remove(position) ?? null; + return company.arr?.Remove(position); } public DrawningTrackedVehicle? GetRandomObject() diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs index 1fb465a..02a42a6 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -19,7 +19,7 @@ namespace HoistingCrane.CollectionGenericObjects /// /// /// Сравнение двух объектов /// - int Insert(T obj, IEqualityComparer? comparer = null); + int Insert(T obj, IEqualityComparer? comparer = null); /// /// Добавление элемента в коллекцию на определенную позицию /// @@ -27,7 +27,7 @@ namespace HoistingCrane.CollectionGenericObjects /// /// Сравнение двух объектов /// - int Insert(T obj, int position, IEqualityComparer? comparer = null); + int Insert(T obj, int position, IEqualityComparer? comparer = null); /// /// Удаление элемента из коллекции по его позиции /// diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index 66feeeb..99d6afb 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -46,36 +46,42 @@ namespace HoistingCrane.CollectionGenericObjects if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return list[position]; } - - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { - // TODO выброс ошибки, если такой объект есть в коллекции - if (comparer != null && list.Contains(obj)) + try { - throw new ObjectIsPresentInTheCollectionException(obj); + if (list.Contains(obj, comparer)) throw new ObjectIsPresentInTheCollectionException(Count); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + list.Add(obj); + return Count - 1; } - if (list.Count >= _maxCount) + catch (ObjectIsPresentInTheCollectionException ex) { - throw new CollectionOverflowException(_maxCount); + MessageBox.Show(ex.Message); + return -1; } - list.Add(obj); - return _maxCount; } - - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (comparer != null && list.Contains(obj)) + try { - throw new ObjectIsPresentInTheCollectionException(); + if (comparer != null && list.Contains(obj, comparer)) + { + throw new ObjectIsPresentInTheCollectionException(Count); + } + + if (Count == _maxCount) throw new CollectionOverflowException(Count); + + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + + list.Insert(position, obj); + return position; + } + catch (ObjectIsPresentInTheCollectionException ex) + { + Console.WriteLine(ex.Message); + return -1; } - if (Count >= _maxCount) - throw new CollectionOverflowException(_maxCount); - - if (position < 0 || position >= _maxCount) - throw new PositionOutOfCollectionException(position); - - list.Insert(position, obj); - return position; } public T? Remove(int position) diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs index f96e396..316bd4c 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs @@ -1,9 +1,10 @@ using HoistingCrane.Drawning; using HoistingCrane.Exceptions; +using System.Linq; namespace HoistingCrane.CollectionGenericObjects { - public class MassivGenericObjects : ICollectionGenericObjects where T : class + public class MassivGenericObjects : ICollectionGenericObjects where T : DrawningTrackedVehicle { private T?[] arr; public MassivGenericObjects() @@ -43,68 +44,83 @@ namespace HoistingCrane.CollectionGenericObjects if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); return arr[position]; } - - public int Insert(T obj, IEqualityComparer? comparer = null) + public int Insert(T obj, IEqualityComparer? comparer = null) { - if (comparer != null) + try { - foreach (T? item in arr) + if (arr.Contains(obj, comparer)) { - if ((comparer as IEqualityComparer).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) - throw new ObjectIsPresentInTheCollectionException(); + throw new ObjectIsPresentInTheCollectionException(); } + for (int i = 0; i < Count; ++i) + { + if (arr[i] == null) + { + arr[i] = obj; + return i; + } + } + throw new CollectionOverflowException(Count); } - int index = 0; - while (index < arr.Length) + catch (ObjectIsPresentInTheCollectionException ex) { - if (arr[index] == null) - { - arr[index] = obj; - return index; - } - index++; + MessageBox.Show(ex.Message); + return -1; } - throw new CollectionOverflowException(Count); + } - public int Insert(T obj, int position, IEqualityComparer? comparer = null) + public int Insert(T obj, int position, IEqualityComparer? comparer = null) { - if (comparer != null) + try { - foreach (T? item in arr) + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + if (comparer != null) { - if ((comparer as IEqualityComparer).Equals(obj as DrawningTrackedVehicle, item as DrawningTrackedVehicle)) - throw new ObjectIsPresentInTheCollectionException(); + for (int i = 0; i < Count; i++) + { + if (comparer.Equals(arr[i], obj)) + { + throw new ObjectIsPresentInTheCollectionException(); + } + } } - } - if (position >= arr.Length || position < 0) throw new PositionOutOfCollectionException(position); - - if (arr[position] == null) - { - arr[position] = obj; - return position; - } - int index = position + 1; - while (index < arr.Length) - { - if (arr[index] == null) + if (arr[position] == null) { - arr[index] = obj; - return index; + arr[position] = obj; + return position; } - index++; - } - index = position - 1; - while (index >= 0) - { - if (arr[index] == null) + else { - arr[index] = obj; - return index; + for (int i = 1; i < Count; ++i) + { + if (arr[position + i] == null) + { + arr[position + i] = obj; + return position + i; + } + for (i = position - 1; i >= 0; i--) + { + if (arr[i] == null) + { + arr[i] = obj; + return i; + } + } + } } - index--; + throw new CollectionOverflowException(Count); + } + catch (PositionOutOfCollectionException ex) + { + MessageBox.Show(ex.Message); + return -1; + } + catch (ObjectIsPresentInTheCollectionException ex) + { + MessageBox.Show(ex.Message); + return -1; } - throw new CollectionOverflowException(Count); } public T? Remove(int position) @@ -127,6 +143,7 @@ namespace HoistingCrane.CollectionGenericObjects { T[] notNullArr = arr.OfType().ToArray(); Array.Sort(notNullArr, comparer); + Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length); } } } diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs index 8e76d17..9902054 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningCraneCompareByColor.cs @@ -4,11 +4,10 @@ { public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y) { - //TODO: Прописать логику сравнения по цветам, скорости и весу if (x == null || x.EntityTrackedVehicle == null) return -1; if (y == null || y.EntityTrackedVehicle == null) return 1; - var colorCompare = x.EntityTrackedVehicle.BodyColor.ToArgb().CompareTo(y.EntityTrackedVehicle.BodyColor.ToArgb()); - if (colorCompare != 0) return colorCompare; + if (x.EntityTrackedVehicle.BodyColor.Name != y.EntityTrackedVehicle.BodyColor.Name) + return x.EntityTrackedVehicle.BodyColor.Name.CompareTo(y.EntityTrackedVehicle.BodyColor.Name); var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed); if (speedCompare != 0) return speedCompare; return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight); diff --git a/HoistingCrane/HoistingCrane/Drawning/StorageEqutables.cs b/HoistingCrane/HoistingCrane/Drawning/StorageEqutables.cs new file mode 100644 index 0000000..c4788f2 --- /dev/null +++ b/HoistingCrane/HoistingCrane/Drawning/StorageEqutables.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Drawning +{ + internal class StorageEqutables + { + } +} diff --git a/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs b/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs index d659852..1175102 100644 --- a/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs +++ b/HoistingCrane/HoistingCrane/Exceptions/ObjectIsPresentInTheCollectionException.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; - +using System.Runtime.Serialization; namespace HoistingCrane.Exceptions { + [Serializable] public class ObjectIsPresentInTheCollectionException : ApplicationException { - public ObjectIsPresentInTheCollectionException(object obj) : base("В коллекции уже присустствует объект " + obj) { } + public ObjectIsPresentInTheCollectionException(int objName) : base("В коллекции уже присустствует объект " + objName) { } public ObjectIsPresentInTheCollectionException() : base() { } - public ObjectIsPresentInTheCollectionException(string message) : base(message) { } public ObjectIsPresentInTheCollectionException(string message, Exception exception) : base(message, exception) { } protected ObjectIsPresentInTheCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index b4cf3d6..3287d4b 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -43,8 +43,8 @@ namespace HoistingCrane } else { - MessageBox.Show("Не удалось добавить объект"); - logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", drawningTrackedVehicle.GetType().Name); + //MessageBox.Show("Не удалось добавить объект"); + logger.LogInformation("Не удалось добавить кран {crane} в коллекцию", drawningTrackedVehicle.GetType().Name); } } catch (CollectionOverflowException ex) diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index 9b3b27e..780fadb 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -13,6 +13,7 @@ + diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 562ee2d..b2baa34 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,8 +1,7 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; -using Serilog.Extensions.Logging; - namespace HoistingCrane { internal static class Program @@ -18,12 +17,25 @@ namespace HoistingCrane } private static void ConfigureServices(ServiceCollection services) { - // Serilog - Log.Logger = new LoggerConfiguration().WriteTo.File("E:\\myLog.log").CreateLogger(); - services.AddSingleton().AddLogging(builder => + + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) { - builder.AddSerilog(); + pathNeed += path[i] + "\\"; + } + + + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); }); } } -} +} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/serilog.json b/HoistingCrane/HoistingCrane/serilog.json new file mode 100644 index 0000000..6660c8d --- /dev/null +++ b/HoistingCrane/HoistingCrane/serilog.json @@ -0,0 +1,17 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log" + } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file