Лабораторная работа №8 готова!

This commit is contained in:
ENDORFIT 2024-05-19 23:06:30 +04:00
parent 0fc655a6e3
commit 13830593a9
12 changed files with 334 additions and 43 deletions

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonByColor = new Button();
buttonSortByType = new Button();
buttonAddMonorail = new Button();
maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button();
@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddMonorail);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -88,10 +92,30 @@
panelCompanyTools.Size = new Size(235, 322);
panelCompanyTools.TabIndex = 8;
//
// buttonByColor
//
buttonByColor.Location = new Point(8, 279);
buttonByColor.Name = "buttonByColor";
buttonByColor.Size = new Size(217, 23);
buttonByColor.TabIndex = 8;
buttonByColor.Text = "Сортировать по значению";
buttonByColor.UseVisualStyleBackColor = true;
buttonByColor.Click += buttonByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(8, 250);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(217, 23);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddMonorail
//
buttonAddMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMonorail.Location = new Point(8, 32);
buttonAddMonorail.Location = new Point(8, 5);
buttonAddMonorail.Name = "buttonAddMonorail";
buttonAddMonorail.Size = new Size(221, 48);
buttonAddMonorail.TabIndex = 1;
@ -101,7 +125,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(5, 130);
maskedTextBox.Location = new Point(5, 59);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(223, 23);
@ -111,7 +135,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(8, 267);
buttonRefresh.Location = new Point(8, 196);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(219, 48);
buttonRefresh.TabIndex = 6;
@ -122,7 +146,7 @@
// buttonRemoveMonorail
//
buttonRemoveMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMonorail.Location = new Point(8, 159);
buttonRemoveMonorail.Location = new Point(8, 88);
buttonRemoveMonorail.Name = "buttonRemoveMonorail";
buttonRemoveMonorail.Size = new Size(221, 48);
buttonRemoveMonorail.TabIndex = 4;
@ -133,7 +157,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(8, 213);
buttonGoToCheck.Location = new Point(8, 142);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(220, 48);
buttonGoToCheck.TabIndex = 5;
@ -351,5 +375,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonByColor;
private Button buttonSortByType;
}
}

@ -95,7 +95,7 @@ namespace ProjectMonorail
_logger.LogInformation("Объект удален");
}
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
LogException(ex);
@ -137,7 +137,7 @@ namespace ProjectMonorail
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);
@ -312,10 +312,35 @@ namespace ProjectMonorail
{
_logger.LogError("Ошибка {Message}", ((PositionOutOfCollectionException)ex).Message);
}
else if (ex is ObjectIsEqualException)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
else
{
_logger.LogError("Ошибка {Message}", ex.Message);
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareMonorail(new DrawningMonorailCompareByType());
}
private void buttonByColor_Click(object sender, EventArgs e)
{
CompareMonorail(new DrawningMonorailCompareByColor());
}
private void CompareMonorail(IComparer<DrawingMonorail?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.Scripts.Exceptions
{
[Serializable]
public class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

@ -113,5 +113,11 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawingMonorail?> comparer) => _collection?.CollectionSort(comparer);
}
}

@ -0,0 +1,51 @@
namespace ProjectMonorail.Scripts.Monorail.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();
}
}
}

@ -24,7 +24,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -32,7 +32,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// <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>
/// Удаление объекта из коллекции с конкретной позиции
@ -58,5 +58,11 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// </summary>
/// <returns>Поэлементный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

@ -44,22 +44,39 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (_collection.Count + 1 > _maxCount) throw new CollectionOverflowException(_maxCount);
_collection.Add(obj);
return _collection.Count + 1;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (position < 0 || position > _collection.Count || _collection[position] != null) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
@ -88,5 +105,10 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

@ -1,4 +1,5 @@
using ProjectMonorail.Scripts.Exceptions;
using ProjectMonorail.Scripts.Monorail.Drawnings;
namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{
@ -52,9 +53,18 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO вставка в свободное место набора
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawingMonorail>).Equals(obj as DrawingMonorail, item as DrawingMonorail))
throw new ObjectIsEqualException();
}
}
for (int i = 0; i < Count; i++)
{
if (InsertingElementCollection(i, obj)) return i;
@ -63,13 +73,22 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
throw new CollectionOverflowException("Превышение лимита Count");
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawingMonorail>).Equals(obj as DrawingMonorail, item as DrawingMonorail))
throw new ObjectIsEqualException();
}
}
if (!(position >= 0 && position < Count)) throw new PositionOutOfCollectionException(position);
if (InsertingElementCollection(position, obj)) return position;
@ -120,5 +139,10 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

@ -14,12 +14,12 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// <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();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -41,7 +41,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -53,24 +53,13 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (!_storages.ContainsKey(name))
{
ICollectionGenericObjects<T> collection;
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
switch (collectionType)
{
case CollectionType.List:
collection = new ListGenericObjects<T>();
break;
case CollectionType.Massive:
collection = new MassiveGenericObjects<T>();
break;
default:
return;
}
if (_storages.ContainsKey(collectionInfo)) return;
_storages.Add(name, collection);
}
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) _storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
@ -81,7 +70,9 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{
// TODO Прописать логику для удаления коллекции
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
@ -95,7 +86,9 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
{
// TODO Продумать логику получения
if (_storages.TryGetValue(name, out var value)) return value;
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -118,7 +111,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(Environment.NewLine);
@ -130,8 +123,6 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
stringBuilder.Append(value.Key);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.GetCollectionType);
stringBuilder.Append(_separatorForKeyValue);
stringBuilder.Append(value.Value.MaxCount);
stringBuilder.Append(_separatorForKeyValue);
@ -181,18 +172,21 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
while ((strs = streamRader.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 Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exceptions.ObjectNotFoundException();
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingMonorail() is T ship)
@ -203,7 +197,7 @@ namespace ProjectMonorail.Scripts.Monorail.CollectionGenericObjects
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

@ -0,0 +1,59 @@
using ProjectMonorail.Scripts.Monorail.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectMonorail.Scripts.Monorail.Drawnings
{
public class DrawiningMonorailEqutables : IEqualityComparer<DrawingMonorail?>
{
public bool Equals(DrawingMonorail? x, DrawingMonorail? y)
{
if (x == null || x.EntityMonorail == null)
{
return false;
}
if (y == null || y.EntityMonorail == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityMonorail.Speed != y.EntityMonorail.Speed)
{
return false;
}
if (x.EntityMonorail.Weight != y.EntityMonorail.Weight)
{
return false;
}
if (x.EntityMonorail.BodyColor != y.EntityMonorail.BodyColor)
{
return false;
}
if (x is DrawingModernMonorail && y is DrawingModernMonorail)
{
EntityModernMonorail _x = (EntityModernMonorail)x.EntityMonorail;
EntityModernMonorail _y = (EntityModernMonorail)x.EntityMonorail;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Cabin != _y.Cabin)
{
return false;
}
if (_x.MonorailTrack != _y.MonorailTrack)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingMonorail obj)
{
return obj.GetHashCode();
}
}
}

@ -0,0 +1,29 @@
namespace ProjectMonorail.Scripts.Monorail.Drawnings
{
public class DrawningMonorailCompareByColor : IComparer<DrawingMonorail?>
{
public int Compare(DrawingMonorail? x, DrawingMonorail? y)
{
if (x == null || x.EntityMonorail == null)
{
return 1;
}
if (y == null || y.EntityMonorail == null)
{
return -1;
}
var bodycolorCompare = x.EntityMonorail.BodyColor.Name.CompareTo(y.EntityMonorail.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityMonorail.Speed.CompareTo(y.EntityMonorail.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMonorail.Weight.CompareTo(y.EntityMonorail.Weight);
}
}
}

@ -0,0 +1,30 @@
namespace ProjectMonorail.Scripts.Monorail.Drawnings
{
public class DrawningMonorailCompareByType : IComparer<DrawingMonorail?>
{
public int Compare(DrawingMonorail? x, DrawingMonorail? y)
{
if (x == null || x.EntityMonorail == null)
{
return 1;
}
if (y == null || y.EntityMonorail == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityMonorail.Speed.CompareTo(y.EntityMonorail.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMonorail.Weight.CompareTo(y.EntityMonorail.Weight);
}
}
}