Лабораторная работа 8
This commit is contained in:
parent
ccdd7b9c59
commit
e210c12c20
@ -1,4 +1,6 @@
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
using ProjectDumpTruck.Exceptions;
|
||||
|
||||
namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
|
||||
public abstract class AbstractCompany
|
||||
@ -53,9 +55,9 @@ public abstract class AbstractCompany
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="car">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningTrack car)
|
||||
public static int operator +(AbstractCompany company, DrawningTrack track)
|
||||
{
|
||||
return company._collection.Insert(car);
|
||||
return company._collection.Insert(track, new DrawningTrackEqutables()) ;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -69,6 +71,13 @@ public abstract class AbstractCompany
|
||||
return company._collection.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawningTrack?> comparer) =>
|
||||
_collection?.CollectionSort(comparer);
|
||||
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
|
@ -0,0 +1,84 @@
|
||||
|
||||
|
||||
namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
|
||||
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 bool IsEmpty()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Name.GetHashCode();
|
||||
}
|
||||
}
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
|
||||
namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
|
||||
|
||||
@ -23,16 +25,18 @@ public interface ICollectionGenericObjects<T>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="comparer">Сравнение двух объектов</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>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
@ -58,4 +62,13 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
void CollectionSort<T>(Comparison<T> comparison) where T : DrawningTrack;
|
||||
}
|
||||
|
||||
|
||||
|
@ -8,21 +8,21 @@ namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
public int _maxCount;
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
public int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
@ -43,30 +43,47 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
public T Get(int position)
|
||||
{
|
||||
public T Get(int position)
|
||||
{
|
||||
//TODO выброс ошибки если выход за границу
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
public int Insert(T obj)
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
|
||||
// TODO выброс ошибки если переполнение
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new CollectionInsertException();
|
||||
}
|
||||
|
||||
}
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
// TODO выброс ошибки если переполнение
|
||||
|
||||
|
||||
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO выброс ошибки если переполнение
|
||||
// TODO выброс ошибки если за границу
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new CollectionInsertException();
|
||||
}
|
||||
}
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
@ -88,5 +105,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectDumpTruck.Exceptions;
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
using ProjectDumpTruck.Exceptions;
|
||||
namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
|
||||
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
@ -52,11 +53,23 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
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<DrawningTrack>).Equals(obj as DrawningTrack, item as DrawningTrack))
|
||||
throw new CollectionInsertException("An item with the same value already exists in the collection: ProjectDumpTrack.Drawnings.DrawningTrack");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
int index = 0;
|
||||
while (index < _collection.Length - 1)
|
||||
{
|
||||
@ -67,13 +80,22 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
|
||||
|
||||
// TODO выброс ошибки если выход за границу
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? item in _collection)
|
||||
{
|
||||
if ((comparer as IEqualityComparer<DrawningTrack>).Equals(obj as DrawningTrack, item as DrawningTrack)) { throw new CollectionInsertException($"An item with the same value already exists in the collection: {obj}"); }
|
||||
}
|
||||
}
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
@ -121,6 +143,11 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,35 +1,35 @@
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
using System.Text;
|
||||
using ProjectDumpTruck.Exceptions;
|
||||
using ProjectDumpTruck.Drawnings;
|
||||
|
||||
namespace ProjectDumpTruck.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningTrack
|
||||
{
|
||||
/// <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>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
@ -41,35 +41,36 @@ public class StorageCollection<T>
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
/// <param name="collectionInfo">тип коллекции</param>
|
||||
public void AddCollection(CollectionInfo collectionInfo)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (_storages.ContainsKey(name)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
else if (collectionType == CollectionType.List)
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
|
||||
if (collectionInfo.CollectionType == CollectionType.None)
|
||||
throw new CollectionTypeException("Пустой тип коллекции");
|
||||
if (collectionInfo.CollectionType == CollectionType.Massive)
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
else if (collectionInfo.CollectionType == CollectionType.List)
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
/// <param name="collectionInfo">Название коллекции</param>
|
||||
public void DelCollection(CollectionInfo collectionInfo)
|
||||
{
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -77,13 +78,13 @@ public class StorageCollection<T>
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (_storages.ContainsKey(name))
|
||||
return _storages[name];
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -97,27 +98,29 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
throw new EmptyFileException();
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
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 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())
|
||||
@ -127,14 +130,14 @@ public class StorageCollection<T>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
|
||||
writer.Write(sb);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -146,66 +149,68 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exception("Файл не существует");
|
||||
throw new FileNotFoundException(filename);
|
||||
}
|
||||
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
throw new Exception("В файле нет данных");
|
||||
throw new EmptyFileException(filename);
|
||||
}
|
||||
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
throw new Exception("В файле неверные данные");
|
||||
throw new FileFormatException(filename);
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
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<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
CollectionInfo? collectionInfo =
|
||||
CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
|
||||
|
||||
ICollectionGenericObjects<T>? collection =
|
||||
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
|
||||
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTrack() is T track)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(track) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
collection.Insert(track);
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
throw new FileFormatException(filename, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
private static ICollectionGenericObjects<T>?
|
||||
CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
@ -214,6 +219,6 @@ public class StorageCollection<T>
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
using ProjectDumpTrack.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace ProjectDumpTrack.Drawnings;
|
||||
|
||||
/// <summary>
|
||||
/// Реализация сравнения двух объектов класса-прорисовки
|
||||
/// </summary>
|
||||
public class DrawningTrackEqutables : IEqualityComparer<DrawningTrack?>
|
||||
{
|
||||
public bool Equals(DrawningTrack? x, DrawningTrack? y)
|
||||
{
|
||||
if (x == null || x.EntityTrack == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityTrack == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityTrack.Speed != y.EntityTrack.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityTrack.Weight != y.EntityTrack.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityTrack.BodyColor != y.EntityTrack.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x is DrawningDumpTrack && y is DrawningDumpTrack)
|
||||
{
|
||||
// TODO доделать логику сравнения дополнительных параметров
|
||||
EntityDumpTrack xDumpTruck = (EntityDumpTrack)x.EntityTrack;
|
||||
EntityDumpTrack yDumpTruck = (EntityDumpTrack)y.EntityTrack;
|
||||
|
||||
if (xDumpTruck.AdditionalColor != yDumpTruck.AdditionalColor)
|
||||
return false;
|
||||
|
||||
if (xDumpTruck.AdditionalAwningColor != yDumpTruck.AdditionalAwningColor)
|
||||
return false;
|
||||
|
||||
if (xDumpTruck.Awning != yDumpTruck.Awning)
|
||||
return false;
|
||||
|
||||
if (xDumpTruck.Bodywork != yDumpTruck.Bodywork)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawningTrack obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
|
||||
namespace ProjectDumpTruck.Drawnings;
|
||||
internal class TrackCompareByColor : IComparer<DrawningTrack?>
|
||||
{
|
||||
public int Compare(DrawningTrack? x, DrawningTrack? y)
|
||||
{
|
||||
if (x == null || x.EntityTrack == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityTrack == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
var bodycolorCompare = x.EntityTrack.BodyColor.Name.CompareTo(y.EntityTrack.BodyColor.Name);
|
||||
if (bodycolorCompare != 0)
|
||||
{
|
||||
return bodycolorCompare;
|
||||
}
|
||||
var speedCompare = x.EntityTrack.Speed.CompareTo(y.EntityTrack.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityTrack.Weight.CompareTo(y.EntityTrack.Weight);
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
namespace ProjectDumpTruck.Drawnings;
|
||||
internal class TrackCompareByType : IComparer<DrawningTrack?>
|
||||
{
|
||||
public int Compare(DrawningTrack? x, DrawningTrack? y)
|
||||
{
|
||||
if (x == null || x.EntityTrack == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (y == null || y.EntityTrack == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
var speedCompare = x.EntityTrack.Speed.CompareTo(y.EntityTrack.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityTrack.Weight.CompareTo(y.EntityTrack.Weight);
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using ProjectDumpTruck.CollectionGenericObjects;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
|
||||
[Serializable]
|
||||
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) { }
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
|
||||
public class CollectionInfoException : Exception
|
||||
{
|
||||
public CollectionInfoException() : base() { }
|
||||
public CollectionInfoException(string message) : base(message) { }
|
||||
public CollectionInfoException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionInfoException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
[Serializable]
|
||||
public class CollectionInsertException : Exception
|
||||
|
||||
|
||||
{
|
||||
public CollectionInsertException(int i) : base("В коллекции содержится равный элемент: " + i) { }
|
||||
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) { }
|
||||
}
|
||||
|
@ -0,0 +1,18 @@
|
||||
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
|
||||
[Serializable]
|
||||
|
||||
public class CollectionTypeException : Exception
|
||||
{
|
||||
public CollectionTypeException() : base() { }
|
||||
public CollectionTypeException(string message) : base(message) { }
|
||||
public CollectionTypeException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected CollectionTypeException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
|
||||
public class DrawningEqutablesException : Exception
|
||||
{
|
||||
public DrawningEqutablesException() : base("Объекты прорисовки одинаковые") { }
|
||||
public DrawningEqutablesException(string message) : base(message) { }
|
||||
public DrawningEqutablesException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected DrawningEqutablesException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
|
||||
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectDumpTruck.Exceptions;
|
||||
public class EmptyFileException : Exception
|
||||
{
|
||||
public EmptyFileException(string name) : base($"Файл {name} пустой ") { }
|
||||
public EmptyFileException() : base("В хранилище отсутствуют коллекции для сохранения") { }
|
||||
public EmptyFileException(string name, string message) : base(message) { }
|
||||
public EmptyFileException(string name, string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected EmptyFileException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -52,6 +52,8 @@
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
@ -66,15 +68,17 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(790, 24);
|
||||
groupBoxTools.Location = new Point(470, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(216, 538);
|
||||
groupBoxTools.Size = new Size(216, 712);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonAddTrack);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox);
|
||||
@ -82,12 +86,12 @@
|
||||
panelCompanyTools.Controls.Add(buttonDelTrack);
|
||||
panelCompanyTools.Location = new Point(3, 354);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(210, 231);
|
||||
panelCompanyTools.Size = new Size(210, 358);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonAddTrack
|
||||
//
|
||||
buttonAddTrack.Location = new Point(9, 14);
|
||||
buttonAddTrack.Location = new Point(9, 32);
|
||||
buttonAddTrack.Name = "buttonAddTrack";
|
||||
buttonAddTrack.Size = new Size(192, 30);
|
||||
buttonAddTrack.TabIndex = 1;
|
||||
@ -97,7 +101,7 @@
|
||||
//
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Location = new Point(9, 197);
|
||||
buttonRefresh.Location = new Point(9, 219);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(192, 25);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@ -116,7 +120,7 @@
|
||||
//
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Location = new Point(9, 162);
|
||||
buttonGoToCheck.Location = new Point(9, 184);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(192, 29);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
@ -243,7 +247,7 @@
|
||||
pictureBox.Enabled = false;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(790, 538);
|
||||
pictureBox.Size = new Size(470, 712);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -252,7 +256,7 @@
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(1006, 24);
|
||||
menuStrip.Size = new Size(686, 24);
|
||||
menuStrip.TabIndex = 2;
|
||||
menuStrip.Text = "menuStrip1";
|
||||
//
|
||||
@ -286,12 +290,33 @@
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Location = new Point(9, 309);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(192, 37);
|
||||
buttonSortByColor.TabIndex = 8;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Location = new Point(9, 268);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(192, 35);
|
||||
buttonSortByType.TabIndex = 7;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += ButtonSortByType_Click;
|
||||
|
||||
//
|
||||
// FormTrackCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1006, 562);
|
||||
ClientSize = new Size(686, 736);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
@ -310,6 +335,9 @@
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
private GroupBox groupBoxTools;
|
||||
@ -336,5 +364,7 @@
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
@ -3,6 +3,8 @@ using Microsoft.Extensions.Logging;
|
||||
using ProjectDumpTruck.CollectionGenericObjects;
|
||||
using ProjectDumpTrack.Drawnings;
|
||||
using ProjectDumpTruck.Exceptions;
|
||||
using ProjectDumpTruck.Drawnings;
|
||||
|
||||
namespace ProjectDumpTruck;
|
||||
|
||||
/// <summary>
|
||||
@ -94,6 +96,11 @@ public partial class FormTrackCollection : Form
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (CollectionInsertException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -226,7 +233,7 @@ public partial class FormTrackCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, ""));
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
}
|
||||
@ -245,10 +252,10 @@ public partial class FormTrackCollection : Form
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
CollectionInfo? col = _storageCollection.Keys?[i];
|
||||
if (!col!.IsEmpty())
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
listBoxCollection.Items.Add(col);
|
||||
}
|
||||
}
|
||||
|
||||
@ -277,7 +284,9 @@ public partial class FormTrackCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
|
||||
_storageCollection.DelCollection(collectionInfo!);
|
||||
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||
}
|
||||
@ -301,7 +310,10 @@ public partial class FormTrackCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningTrack>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
ICollectionGenericObjects<DrawningTrack>? collection =
|
||||
_storageCollection[
|
||||
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
|
||||
new CollectionInfo("", CollectionType.None, "")];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
@ -362,6 +374,41 @@ public partial class FormTrackCollection : Form
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по типу
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareCars(new TrackCompareByType());
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareCars(new TrackCompareByColor());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
private void CompareCars(IComparer<DrawningTrack?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -126,4 +126,7 @@
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>25</value>
|
||||
</metadata>
|
||||
</root>
|
@ -6,6 +6,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user