1 Commits
lab08 ... lab07

Author SHA1 Message Date
9c133a375b лаб7_фин 2024-06-17 14:16:24 +04:00
17 changed files with 75 additions and 543 deletions

View File

@@ -50,8 +50,7 @@ public abstract class AbstractCompany
/// <param name="picWidth">Ширина окна</param> /// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param> /// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param> /// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrain> collection)
ICollectionGenericObjects<DrawningTrain> collection)
{ {
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
@@ -65,10 +64,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param> /// <param name="car">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrain trans) public static int operator +(AbstractCompany company, DrawningTrain train)
{ {
return company._collection?.Insert(trans, new DrawingTransEquitables()) ?? return company._collection.Insert(train);
throw new DrawingEquitablesException();
} }
/// <summary> /// <summary>
@@ -82,8 +80,6 @@ public abstract class AbstractCompany
return company._collection?.Remove(position); return company._collection?.Remove(position);
} }
public void Sort(IComparer<DrawningTrain?> comparer) =>
_collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Получение случайного объекта из коллекции /// Получение случайного объекта из коллекции

View File

@@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.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();
}
}

View File

@@ -1,65 +0,0 @@
using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.CollectionGenericObjects;
public class DrawingTrainEquitables : IEqualityComparer<DrawningTrain?>
{
public bool Equals(DrawningTrain? x, DrawningTrain? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrain != null && y.EntityTrain != null && x.EntityTrain.Speed != y.EntityTrain.Speed)
{
return false;
}
if (x.EntityTrain.Weight != y.EntityTrain.Weight)
{
return false;
}
if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor)
{
return false;
}
if (x is DrawningRoadTrain && y is DrawningRoadTrain)
{
if (((EntityRoadTrain)x.EntityTrain).BodyTankColor !=
((EntityRoadTrain)y.EntityTrain).BodyTankColor)
{
return false;
}
if (((EntityRoadTrain)x.EntityTrain).WaterTank !=
((EntityRoadTrain)y.EntityTrain).WaterTank)
{
return false;
}
if (((EntityRoadTrain)x.EntityTrain).CleanBrush !=
((EntityRoadTrain)y.EntityTrain).CleanBrush)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrain obj)
{
return obj.GetHashCode();
}
}

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectRoadTrain.CollectionGenericObjects;
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
@@ -22,7 +22,7 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<T?>? comparer = null); int Insert(T obj);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@@ -30,7 +30,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null); int Insert(T obj, int position);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@@ -51,5 +51,4 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
} }

View File

@@ -48,20 +48,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj, IEqualityComparer<T?>? comparer = null) public int Insert(T obj)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); 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); _collection.Add(obj);
return Count; return Count;
} }
@@ -72,29 +61,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null) public int Insert(T obj, int position)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
public T Remove(int position) public T Remove(int position)
{ {

View File

@@ -51,20 +51,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj, IEqualityComparer<T?>? comparer = null) public int Insert(T obj)
{ {
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++) for (int i = 0; i < Count; i++)
{ {
@@ -78,22 +66,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null) public int Insert(T obj, int position)
{ {
// проверка позиции // проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); 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 (_collection[position] != null) if (_collection[position] != null)
{ {
bool pushed = false; bool pushed = false;
@@ -126,6 +106,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
// вставка
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
@@ -149,8 +130,4 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@@ -1,4 +1,4 @@
 using ProjectRoadTrain.CollectionGenericObjects;
using ProjectRoadTrain.Drawnings; using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Exceptions; using ProjectRoadTrain.Exceptions;
using System; using System;
@@ -6,43 +6,43 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectRoadTrain.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningTrain where T : DrawningTrain
{ {
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
public List<CollectionInfo> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
public void AddCollection(CollectionInfo collectionInfo)
{
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>();
}
public void DelCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
} }
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo] public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name);
if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции");
if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
public ICollectionGenericObjects<T>? this[string name]
{ {
get get
{ {
if (_storages.ContainsKey(collectionInfo)) if (_storages.ContainsKey(name))
return _storages[collectionInfo]; return _storages[name];
return null; return null;
} }
} }
@@ -70,7 +70,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
@@ -110,11 +110,11 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException(filename); return false;
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
@@ -122,7 +122,8 @@ public class StorageCollection<T>
string str = fs.ReadLine(); string str = fs.ReadLine();
if (string.IsNullOrEmpty(str)) if (string.IsNullOrEmpty(str))
{ {
throw new EmptyFileExeption(filename); throw new FileNotFoundException(filename);
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
@@ -135,21 +136,20 @@ public class StorageCollection<T>
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3) if (record.Length != 4)
{ {
continue; continue;
} }
CollectionInfo? collectionInfo = CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
CollectionInfo.GetCollectionInfo(record[0]) ?? ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]); if (collection == null)
{
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]); }
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateTrain() is T ship) if (elem?.CreateTrain() is T ship)
@@ -165,8 +165,11 @@ public class StorageCollection<T>
} }
} }
_storages.Add(collectionInfo, collection); _storages.Add(record[0], collection);
} }
return true;
} }
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawningEquitablesException : Exception
{
public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawningEquitablesException(string message) : base(message) { }
public DrawningEquitablesException(string message, Exception exception) :
base(message, exception)
{ }
protected DrawningEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -1,64 +0,0 @@
using ProjectRoadTrain.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawingTransEquitables : IEqualityComparer<DrawningTrain?>
{
public bool Equals(DrawningTrain? x, DrawningTrain? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrain != null && y.EntityTrain != null && x.EntityTrain.Speed != y.EntityTrain.Speed)
{
return false;
}
if (x.EntityTrain.Weight != y.EntityTrain.Weight)
{
return false;
}
if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor)
{
return false;
}
if (x is DrawningRoadTrain && y is DrawningRoadTrain)
{
if (((EntityRoadTrain)x.EntityTrain).BodyTankColor !=
((EntityRoadTrain)y.EntityTrain).BodyTankColor)
{
return false;
}
if (((EntityRoadTrain)x.EntityTrain).WaterTank !=
((EntityRoadTrain)y.EntityTrain).WaterTank)
{
return false;
}
if (((EntityRoadTrain)x.EntityTrain).CleanBrush !=
((EntityRoadTrain)y.EntityTrain).CleanBrush)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrain obj)
{
return obj.GetHashCode();
}
}

View File

@@ -1,41 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawingTransCompareByColor : IComparer<DrawningTrain?>
{
public int Compare(DrawningTrain? x, DrawningTrain? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityTrain == null)
{
return 1;
}
if (y == null || y.EntityTrain == null)
{
return -1;
}
if (ToHex(x.EntityTrain.BodyColor) != ToHex(y.EntityTrain.BodyColor))
{
return String.Compare(ToHex(x.EntityTrain.BodyColor), ToHex(y.EntityTrain.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
private static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawingTransCompareByType : IComparer<DrawningTrain?>
{
public int Compare(DrawningTrain? x, DrawningTrain y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityTrain == null)
{
return 1;
}
if (y == null || y.EntityTrain == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
}

View File

@@ -1,5 +1,4 @@
using ProjectRoadTrain.CollectionGenericObjects; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization; using System.Runtime.Serialization;
@@ -11,7 +10,7 @@ namespace ProjectRoadTrain.Exceptions;
public class CollectionAlreadyExistsException : Exception public class CollectionAlreadyExistsException : Exception
{ {
public CollectionAlreadyExistsException() : base() { } public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { } public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) : public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception) base($"Коллекция {name} уже существует!", exception)
{ } { }

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.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) { }
}

View File

@@ -9,7 +9,6 @@ namespace ProjectRoadTrain.Exceptions;
public class CollectionInsertException : Exception public class CollectionInsertException : Exception
{ {
public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { }
public CollectionInsertException() : base() { } public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { } public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) : public CollectionInsertException(string message, Exception exception) :

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
public class DrawingEquitablesException : Exception
{
public DrawingEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawingEquitablesException(string message) : base(message) { }
public DrawingEquitablesException(string message, Exception exception) :
base(message, exception)
{ }
protected DrawingEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@@ -54,8 +54,6 @@ namespace ProjectRoadTrain
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@@ -72,15 +70,13 @@ namespace ProjectRoadTrain
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(952, 0); groupBoxTools.Location = new Point(952, 0);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(218, 842); groupBoxTools.Size = new Size(218, 780);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты"; groupBoxTools.Text = "инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTrain); panelCompanyTools.Controls.Add(buttonAddTrain);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@@ -90,7 +86,7 @@ namespace ProjectRoadTrain
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 407); panelCompanyTools.Location = new Point(3, 407);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(212, 432); panelCompanyTools.Size = new Size(212, 370);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonAddTrain // buttonAddTrain
@@ -106,7 +102,7 @@ namespace ProjectRoadTrain
// //
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(3, 104); maskedTextBox.Location = new Point(3, 137);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(244, 27); maskedTextBox.Size = new Size(244, 27);
@@ -116,9 +112,9 @@ namespace ProjectRoadTrain
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 264); buttonRefresh.Location = new Point(3, 294);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 55); buttonRefresh.Size = new Size(206, 56);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@@ -127,7 +123,7 @@ namespace ProjectRoadTrain
// buttonDelTrain // buttonDelTrain
// //
buttonDelTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonDelTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelTrain.Location = new Point(3, 137); buttonDelTrain.Location = new Point(3, 170);
buttonDelTrain.Name = "buttonDelTrain"; buttonDelTrain.Name = "buttonDelTrain";
buttonDelTrain.Size = new Size(206, 56); buttonDelTrain.Size = new Size(206, 56);
buttonDelTrain.TabIndex = 4; buttonDelTrain.TabIndex = 4;
@@ -138,7 +134,7 @@ namespace ProjectRoadTrain
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 199); buttonGoToCheck.Location = new Point(3, 232);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 56); buttonGoToCheck.Size = new Size(206, 56);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@@ -255,7 +251,7 @@ namespace ProjectRoadTrain
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(952, 842); pictureBox.Size = new Size(952, 780);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@@ -300,33 +296,11 @@ namespace ProjectRoadTrain
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 328);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(206, 42);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 376);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(206, 53);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormTrainCollection // FormTrainCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1170, 842); ClientSize = new Size(1170, 780);
Controls.Add(menuStrip); Controls.Add(menuStrip);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
@@ -371,7 +345,5 @@ namespace ProjectRoadTrain
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
} }
} }

View File

@@ -30,12 +30,13 @@ public partial class FormTrainCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
CollectionInfo? col = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i];
if (!col!.IsEmpty()) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(col); listBoxCollection.Items.Add(colName);
} }
} }
} }
private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e)
@@ -200,7 +201,7 @@ public partial class FormTrainCollection : Form
try try
{ {
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ")); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции"); _logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@@ -209,6 +210,7 @@ public partial class FormTrainCollection : Form
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message); _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
@@ -271,11 +273,11 @@ public partial class FormTrainCollection : Form
return; return;
} }
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена"); _logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void ButtonCreateCompany_Click(object sender, EventArgs e) private void ButtonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
@@ -285,9 +287,7 @@ public partial class FormTrainCollection : Form
} }
ICollectionGenericObjects<DrawningTrain>? collection = ICollectionGenericObjects<DrawningTrain>? collection =
_storageCollection[ _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@@ -305,39 +305,5 @@ public partial class FormTrainCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawingTransCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawingTransCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawningTrain?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }