Лабоораторная работа №8

This commit is contained in:
Роман Пермяков 2024-05-15 22:33:27 +04:00
parent c34c2b42a0
commit 83ad81dd09
12 changed files with 354 additions and 43 deletions

View File

@ -31,7 +31,7 @@ namespace AccordionBus.CollectionGenericObjects
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)
@ -62,6 +62,8 @@ namespace AccordionBus.CollectionGenericObjects
return bitmap;
}
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus);

View File

@ -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<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] : "");
}
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

@ -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
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <returns></returns>
bool Insert(T obj);
bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// вставить по позиции
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <param name="position">индекс</param>
/// <returns></returns>
bool Insert(T obj, int position);
bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// удаление
/// </summary>
@ -53,5 +54,11 @@ namespace AccordionBus.CollectionGenericObjects
/// </summary>
/// <returns></returns>
IEnumerable<T> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,4 +1,5 @@
using AccordionBus.Exceptions;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -37,23 +38,47 @@ namespace AccordionBus.CollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) throw new PozitionOutOfCollectionException(position);
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null;
return _collection[position];
}
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null)
{
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<DrawningBus?>? 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;
}
@ -73,5 +98,10 @@ namespace AccordionBus.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -1,4 +1,5 @@
using AccordionBus.Exceptions;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -47,8 +48,20 @@ namespace AccordionBus.CollectionGenericObjects
return _collection[position];
}
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? 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)
@ -60,10 +73,22 @@ namespace AccordionBus.CollectionGenericObjects
throw new CollectionOverflowException(Count);
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null)
{
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)
{
_collection[position] = obj;
@ -108,5 +133,10 @@ namespace AccordionBus.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

View File

@ -12,9 +12,9 @@ namespace AccordionBus.CollectionGenericObjects
public class StorageCollection<T>
where T: DrawningBus
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storage;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storage;
public List<string> Keys => _storage.Keys.ToList();
public List<CollectionInfo> Keys => _storage.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
@ -24,27 +24,29 @@ namespace AccordionBus.CollectionGenericObjects
public StorageCollection()
{
_storage = new Dictionary<string, ICollectionGenericObjects<T>>();
_storage = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
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<T>? 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, "")];
}
}
@ -61,7 +63,7 @@ namespace AccordionBus.CollectionGenericObjects
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storage)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storage)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
@ -72,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())
@ -113,18 +113,19 @@ namespace AccordionBus.CollectionGenericObjects
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<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new InvalidOperationException("Не удалось определить информацию об коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
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)
@ -133,9 +134,13 @@ namespace AccordionBus.CollectionGenericObjects
{
if (!collection.Insert(bus))
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[3]);
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[2]);
}
}
catch(ObjectExistsException ex)
{
throw new InvalidOperationException(ex.Message);
}
catch (CollectionOverflowException ex)
{
throw new InvalidOperationException("Коллекция переполнена", ex);
@ -143,7 +148,7 @@ namespace AccordionBus.CollectionGenericObjects
}
}
_storage.Add(record[0], collection);
_storage.Add(collectionInfo, collection);
}
}
}

View File

@ -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<DrawningBus?>
{
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);
}
}
}

View File

@ -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<DrawningBus?>
{
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);
}
}
}

View File

@ -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<DrawningBus?>
{
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();
}
}
}

View File

@ -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) { }
}
}

View File

@ -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;
}
}

View File

@ -57,6 +57,11 @@ namespace AccordionBus
_logger.LogInformation("Объект добавлен в коллекцию, " + bus.GetDataForSave());
}
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {message}", ex.Message);
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
@ -106,7 +111,8 @@ namespace AccordionBus
bus = _company.GetRandomObject();
counter--;
}
} catch(PozitionOutOfCollectionException ex)
}
catch (PozitionOutOfCollectionException ex)
{
_logger.LogError("Ошибка: {message}", ex.Message);
}
@ -144,7 +150,7 @@ namespace AccordionBus
_logger.LogInformation("Добавлена новая коллекция {0}", textBoxCollectionName.Text);
textBoxCollectionName.Text = "";
RefreshListBoxItems();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -163,7 +169,7 @@ namespace AccordionBus
{
MessageBox.Show("Не удалось удалить компанию");
_logger.LogError("Ошибка: не удалось удалить компанию");
}
}
}
@ -188,6 +194,7 @@ namespace AccordionBus
case "Станция":
_company = new BusStation(pictureBox.Width, pictureBox.Height, collection);
pictureBox.Image = _company.Show();
break;
}
@ -199,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);
@ -217,8 +224,8 @@ namespace AccordionBus
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);
@ -247,5 +254,23 @@ namespace AccordionBus
}
}
}
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<DrawningBus?> comparer)
{
if (_company == null) return;
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}