This commit is contained in:
Anastasia Yazykova 2024-06-10 03:49:04 +04:00
parent d4da4c02ae
commit 2d339f7d20
13 changed files with 472 additions and 85 deletions

View File

@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection.Insert(bus);
return company._collection.Insert(bus,new DrawiningBusEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
namespace TrolleybusProject.CollectionGenericObjects;
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

@ -21,20 +21,20 @@ 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>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <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>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@ -51,4 +51,9 @@ int Insert(T obj, int position);
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,8 +1,10 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects;
@ -48,27 +50,48 @@ 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 + 1 > _maxCount)
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return 1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position > Count)
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
throw new PositionOutOfCollectionException(position);
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
if (Count + 1 > _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
return 1;
}
_collection.Insert(position, obj);
return position;
}
public T? Remove(int position)
{
@ -89,6 +112,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -3,8 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects;
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@ -51,13 +53,26 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -66,12 +81,27 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
throw new CollectionOverflowException(Count);
}
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)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -117,4 +147,13 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);
value.Sort(comparer);
value.CopyTo(_collection, 0);
}
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectTrolleybus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -15,12 +16,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();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -42,7 +43,7 @@ public class StorageCollection<T>
///
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -51,29 +52,36 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name) && name == "")
{
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo))
return;
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[collectionInfo] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
default:
break;
}
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
else
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
_storages.Remove(name);
}
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
}
/// <summary>
/// Доступ к коллекции
/// </summary>
@ -83,11 +91,12 @@ public class StorageCollection<T>
{
get
{
if (name == "")
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return null;
return _storages[collectionInfo];
}
return _storages[name];
return null;
}
}
@ -102,10 +111,13 @@ public class StorageCollection<T>
{
File.Delete(filename);
}
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -141,42 +153,42 @@ public class StorageCollection<T>
{
throw new FileNotFoundException("Файл не существует!");
}
using (StreamReader reader = new(filename))
using (StreamReader sr = new(filename))
{
string line = reader.ReadLine();
string? line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
if (line != _collectionKey)
{
throw new InvalidDataException("В файле неверные данные");
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Не удалось определить тип коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T boat)
if (elem?.CreateDrawningBus() is T bus)
{
try
{
if (collection.Insert(boat) < 0)
if (collection.Insert(bus) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
@ -189,10 +201,9 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.CollectionGenericObjects;
namespace TrolleybusProject;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
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

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings;
internal class DrawiningBusEqutables: 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 DrawningTrolleybus && y is DrawningTrolleybus)
{
if (((EntityTrolleybus)x.EntityBus).AdditionalColor !=
((EntityTrolleybus)y.EntityBus).AdditionalColor)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Roga !=
((EntityTrolleybus)y.EntityBus).Roga)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Otsek !=
((EntityTrolleybus)y.EntityBus).Otsek)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Doors !=
((EntityTrolleybus)y.EntityBus).Doors)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.Drawnings;
public class DrawningBusCompareByColor: IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? 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,14 @@
using System.Runtime.Serialization;
using TrolleybusProject;
namespace ProjectTrolleybus.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -55,6 +55,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonByType = new Button();
ByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -71,7 +73,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(904, 33);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(300, 623);
groupBoxTools.Size = new Size(300, 702);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -88,7 +90,9 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ByColor);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonDelTrolleybus);
@ -96,7 +100,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 397);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(294, 259);
panelCompanyTools.Size = new Size(294, 305);
panelCompanyTools.TabIndex = 9;
//
// buttonRefresh
@ -250,7 +254,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(904, 623);
pictureBox.Size = new Size(904, 702);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -314,11 +318,33 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonByType
//
buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByType.Location = new Point(6, 259);
buttonByType.Name = "buttonByType";
buttonByType.Size = new Size(268, 34);
buttonByType.TabIndex = 8;
buttonByType.Text = "Сравнить по типу";
buttonByType.UseVisualStyleBackColor = true;
buttonByType.Click += button1_Click;
//
// ByColor
//
ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ByColor.Location = new Point(23, 215);
ByColor.Name = "ByColor";
ByColor.Size = new Size(247, 38);
ByColor.TabIndex = 7;
ByColor.Text = "Сравнить по цвету";
ByColor.UseVisualStyleBackColor = true;
ByColor.Click += ByColor_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1204, 656);
ClientSize = new Size(1204, 735);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -366,5 +392,7 @@
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem save_ToolStripMenuItem;
private ToolStripMenuItem load_ToolStripMenuItem;
private Button buttonByType;
private Button ByColor;
}
}

View File

@ -45,24 +45,26 @@ public partial class FormBusCollection : Form
}
private void SetBus(DrawningBus bus)
{
if (_company == null || bus == null)
{
return;
}
try
{
if (_company == null || bus == null)
{
return;
}
if (_company + bus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave());
}
int addingObject = (_company + bus);
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
catch (CollectionOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (CollectionInsertException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка:обьект повторяется {0}", bus);
}
}
@ -156,7 +158,7 @@ public partial class FormBusCollection : Form
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -184,7 +186,7 @@ public partial class FormBusCollection : Form
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);
@ -281,6 +283,31 @@ public partial class FormBusCollection : Form
}
private void button1_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void ByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}