законченная 8ая лабораторная

This commit is contained in:
tyxz0 2024-06-05 12:15:04 +04:00
parent 038b8261a5
commit 82132e0d25
13 changed files with 364 additions and 50 deletions

View File

@ -66,7 +66,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int? operator +(AbstractCompany company, DrawingBus bus)
{
return company._collection?.Insert(bus);
return company._collection?.Insert(bus, new DrawiningBusEqutables());
}
/// <summary>
@ -125,4 +125,6 @@ public abstract class AbstractCompany
/// </summary>
protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawingBus?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.CollectionGenericObjects;
public class CollectionInfo : IEquatable<CollectionInfo>
{
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] : string.Empty);
}
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();
}
}

View File

@ -28,7 +28,7 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление элемента на конкретную позицию
@ -36,7 +36,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -54,6 +54,8 @@ public interface ICollectionGenericObjects<T>
CollectionType GetCollectionType { get; }
IEnumerable<T?> GetItems();
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,5 @@
using DoubleDeckerBus.Exceptions;
using DoubleDeckerBus.Drawnings;
using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -44,17 +45,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count >= _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (comparer != null)
{
foreach (T? item in _collection)
{
if (((IEqualityComparer<DrawingBus>)comparer).Equals(obj as DrawingBus, item as DrawingBus))
{
throw new EqualCollectionObjectException(obj as DrawingBus);
}
}
}
_collection.Add(obj);
return _collection.IndexOf(obj);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= _maxCount)
{
@ -66,6 +78,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
if (comparer != null)
{
foreach (T? item in _collection)
{
if (((IEqualityComparer<DrawingBus>)comparer).Equals(obj as DrawingBus, item as DrawingBus))
{
throw new EqualCollectionObjectException(obj as DrawingBus);
}
}
}
if (position > Count && position < _maxCount)
{
return Insert(obj);
@ -95,4 +118,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using DoubleDeckerBus.Exceptions;
using DoubleDeckerBus.Drawnings;
using DoubleDeckerBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -62,8 +63,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if (((IEqualityComparer<DrawingBus>)comparer).Equals(obj as DrawingBus, item as DrawingBus))
{
throw new EqualCollectionObjectException(obj as DrawingBus);
}
}
}
try
{
return Insert(obj, 0);
@ -72,16 +83,25 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
throw new CollectionOverflowException(ex.Message);
}
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
foreach (T? item in _collection)
{
if (((IEqualityComparer<DrawingBus>)comparer).Equals(obj as DrawingBus, item as DrawingBus))
{
throw new EqualCollectionObjectException(obj as DrawingBus);
}
}
}
int copy_of_position = position - 1;
while (position < Count)
@ -130,4 +150,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -19,12 +19,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage";
@ -35,12 +35,17 @@ public class StorageCollection<T>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
if (string.IsNullOrEmpty(name))
{
return;
}
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return;
}
@ -48,11 +53,11 @@ public class StorageCollection<T>
{
case CollectionType.List:
ListGenericObjects<T> _listToAdd = new ListGenericObjects<T>();
_storages.Add(name, _listToAdd);
_storages.Add(collectionInfo, _listToAdd);
return;
case CollectionType.Massive:
MassiveGenericObjects<T> _arrayToAdd = new MassiveGenericObjects<T>();
_storages.Add(name, _arrayToAdd);
_storages.Add(collectionInfo, _arrayToAdd);
return;
case CollectionType.None:
return;
@ -62,9 +67,10 @@ public class StorageCollection<T>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -72,9 +78,10 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return _storages[name];
return _storages[collectionInfo];
}
return null;
}
@ -98,7 +105,7 @@ public class StorageCollection<T>
sw.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
@ -109,8 +116,6 @@ public class StorageCollection<T>
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
@ -152,22 +157,18 @@ public class StorageCollection<T>
{
string[] record = bufferLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Failed to define the collection information: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Failed to create a collection");
if (collection == null)
{
throw new ArgumentNullException("Failed to create a collection");
}
collection.MaxCount = Convert.ToInt32(record[2]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
@ -184,7 +185,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -11,7 +11,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />

View File

@ -0,0 +1,34 @@
using DoubleDeckerBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Drawnings;
public class DrawingBusCompareByColor : IComparer<DrawingBus?>
{
public int Compare(DrawingBus? x, DrawingBus? y)
{
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
var bodyColorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Drawnings;
public class DrawingBusCompareByType : IComparer<DrawingBus?>
{
public int Compare(DrawingBus? x, DrawingBus? y)
{
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);
}
}

View File

@ -0,0 +1,63 @@
using DoubleDeckerBus.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Drawnings;
public class DrawiningBusEqutables : IEqualityComparer<DrawingBus?>
{
public bool Equals(DrawingBus? x, DrawingBus? 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 DrawingDoubleDeckerBus && y is DrawingDoubleDeckerBus)
{
EntityDoubleDeckerBus _x = (EntityDoubleDeckerBus)x.EntityBus;
EntityDoubleDeckerBus _y = (EntityDoubleDeckerBus)y.EntityBus;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.SecondFloor != _y.SecondFloor)
{
return false;
}
if (_x.Stripes != _y.Stripes)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,23 @@
using DoubleDeckerBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDeckerBus.Exceptions;
[Serializable]
internal class EqualCollectionObjectException : ApplicationException
{
public EqualCollectionObjectException(DrawingBus? bus) : base("The same element already exists in the collection: " + bus?.GetType()) { }
public EqualCollectionObjectException() : base() { }
public EqualCollectionObjectException(string message) : base(message) { }
public EqualCollectionObjectException(string message, Exception exception) : base(message, exception) { }
protected EqualCollectionObjectException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -90,7 +94,7 @@
// buttonAddBus
//
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBus.Location = new Point(0, 13);
buttonAddBus.Location = new Point(0, 0);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(191, 35);
buttonAddBus.TabIndex = 1;
@ -100,7 +104,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(0, 95);
maskedTextBox.Location = new Point(0, 41);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(188, 23);
@ -110,7 +114,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 206);
buttonRefresh.Location = new Point(0, 152);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(191, 35);
buttonRefresh.TabIndex = 6;
@ -121,7 +125,7 @@
// buttonRemoveBus
//
buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBus.Location = new Point(0, 124);
buttonRemoveBus.Location = new Point(0, 70);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(191, 35);
buttonRemoveBus.TabIndex = 4;
@ -132,7 +136,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 165);
buttonGoToCheck.Location = new Point(0, 111);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(191, 35);
buttonGoToCheck.TabIndex = 5;
@ -272,7 +276,7 @@
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(180, 22);
saveToolStripMenuItem.Size = new Size(140, 22);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
@ -280,7 +284,7 @@
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(180, 22);
loadToolStripMenuItem.Size = new Size(140, 22);
loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
@ -292,6 +296,28 @@
//
saveFileDialog.Filter = "txt file|*.txt";
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(0, 193);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(191, 28);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Sort by type";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(0, 227);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(191, 28);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Sort by color";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -341,5 +367,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -58,12 +58,12 @@ public partial class FormBusCollection : Form
pictureBox.Image = _company.Show();
_logger.LogInformation("Object added: {obj}", bus.GetDataForSave());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Failed to add object", ex.Message);
_logger.LogError("Failed to add object: {Message}", ex.Message);
}
}
@ -90,7 +90,7 @@ public partial class FormBusCollection : Form
pictureBox.Image = _company.Show();
_logger.LogInformation("Object removed {obj}", removedObj?.GetDataForSave());
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Failed to remove object", ex.Message);
@ -167,7 +167,7 @@ public partial class FormBusCollection : Form
listBoxCollectionItems.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))
{
listBoxCollectionItems.Items.Add(colName);
@ -234,7 +234,7 @@ public partial class FormBusCollection : Form
MessageBox.Show("Save succeeded", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Saving to the file: {filename}", saveFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Unable to save", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
@ -253,13 +253,34 @@ public partial class FormBusCollection : Form
_logger.LogInformation("Loading from the file: {filename}", openFileDialog.FileName);
RefreshListBoxItems();
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Unable to load", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Error: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareBuses(new DrawingBusCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareBuses(new DrawingBusCompareByColor());
}
private void CompareBuses(IComparer<DrawingBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}