This commit is contained in:
Дима 2024-08-30 00:45:20 +04:00
parent acd1b0cce2
commit 18228eeafd
17 changed files with 469 additions and 90 deletions

View File

@ -57,11 +57,11 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="сruiser">Добавляемый объект</param>
/// <param name="locomotive">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningLocomotive сruiser)
public static int operator +(AbstractCompany company, DrawningLocomotive locomotive)
{
return company._collection.Insert(сruiser);
return company._collection.Insert(locomotive, new DrawiningLocomotiveEqutables());
}
/// <summary>
@ -110,6 +110,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningLocomotive?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,75 @@
namespace ProjectLocomotive.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 override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -1,4 +1,7 @@
namespace ProjectLocomotive.CollectionGenericObjects
using ProjectLocomotive.Drawnings;
using ProjectLocomotive.CollectionGenericObjects;
namespace ProjectLocomotive.CollectionGenericObjects
{
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -11,29 +14,35 @@
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? 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<DrawningLocomotive?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@ -51,6 +60,12 @@
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,4 +1,7 @@
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
namespace ProjectLocomotive.CollectionGenericObjects
{
@ -47,23 +50,38 @@ namespace ProjectLocomotive.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
// TODO вставка в конец набора
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO вставка по позиции
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
@ -72,9 +90,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
// TODO выбром позиций, если выход за границы массива
// TODO удаление объекта из списка
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
@ -87,5 +106,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -1,4 +1,7 @@
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
namespace ProjectLocomotive.CollectionGenericObjects
{
@ -55,34 +58,44 @@ namespace ProjectLocomotive.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение
int index = 0;
while (index < Count && _collection[index] != null)
// TODO выброc позиций, если такой объект есть в коллекции
for (int i = 0; i < Count; i++)
{
index++;
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (index < Count)
for (int i = 0; i < Count; i++)
{
_collection[index] = obj;
return index;
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<DrawningLocomotive?>? comparer = null)
{
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
// TODO выбром позиций, если переполнение
// TODO выбром позиций, если выход за границы массива
// TODO вставка
for (int i = 0; i < Count; i++)
{
if (comparer.Equals((_collection[i] as DrawningLocomotive), (obj as DrawningLocomotive))) throw new ObjectAlreadyInCollectionException(i);
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] != null)
@ -143,5 +156,10 @@ namespace ProjectLocomotive.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

View File

@ -1,5 +1,7 @@
using ProjectLocomotive.Drawnings;
using ProjectLocomotive.Exceptions;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Exceptions;
using System.Text;
namespace ProjectLocomotive.CollectionGenericObjects
@ -13,12 +15,12 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -40,7 +42,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -48,29 +50,40 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo name)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return;
if (name == null || _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 (name.CollectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
if (name.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
if (name == null || !_storages.ContainsKey(name))
{
return;
}
_storages.Remove(name);
}
/// <summary>
@ -78,13 +91,16 @@ namespace ProjectLocomotive.CollectionGenericObjects
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
{
return _storages[name];
}
return null;
}
}
@ -111,7 +127,7 @@ namespace ProjectLocomotive.CollectionGenericObjects
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
@ -122,8 +138,6 @@ namespace ProjectLocomotive.CollectionGenericObjects
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
@ -164,27 +178,25 @@ namespace ProjectLocomotive.CollectionGenericObjects
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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 InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T aircraft)
if (elem?.CreateDrawningLocomotive() is T locomotive)
{
try
{
if (collection.Insert(aircraft) == -1)
if (collection.Insert(locomotive, new DrawiningLocomotiveEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
@ -193,9 +205,13 @@ namespace ProjectLocomotive.CollectionGenericObjects
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningLocomotiveEqutables : IEqualityComparer<DrawningLocomotive?>
{
public bool Equals(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return false;
}
if (y == null || y.EntityLocomotive == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityLocomotive.Speed != y.EntityLocomotive.Speed)
{
return false;
}
if (x.EntityLocomotive.Weight != y.EntityLocomotive.Weight)
{
return false;
}
if (x.EntityLocomotive.BodyColor != y.EntityLocomotive.BodyColor)
{
return false;
}
if (x is DrawningTLocomotive && y is DrawningTLocomotive)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningLocomotive obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,34 @@
using ProjectLocomotive.Entities;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByColor : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityLocomotive == null)
{
return 1;
}
if (y == null || y.EntityLocomotive == null)
{
return -1;
}
var bodycolorCompare = x.EntityLocomotive.BodyColor.Name.CompareTo(y.EntityLocomotive.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningLocomotiveCompareByType : IComparer<DrawningLocomotive?>
{
public int Compare(DrawningLocomotive? x, DrawningLocomotive? y)
{
if (x == null || x.EntityLocomotive == null)
{
return 1;
}
if (y == null || y.EntityLocomotive == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityLocomotive.Speed.CompareTo(y.EntityLocomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityLocomotive.Weight.CompareTo(y.EntityLocomotive.Weight);
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive.Exceptions;
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -48,6 +48,7 @@
pictureBoxLocomotive.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxLocomotive.TabIndex = 0;
pictureBoxLocomotive.TabStop = false;
pictureBoxLocomotive.Click += pictureBoxLocomotive_Click;
//
// buttonUp
//

View File

@ -135,5 +135,9 @@ namespace ProjectLocomotive
}
}
private void pictureBoxLocomotive_Click(object sender, EventArgs e)
{
}
}
}

View File

@ -167,9 +167,9 @@
checkBoxHeadlight.AutoSize = true;
checkBoxHeadlight.Location = new Point(6, 217);
checkBoxHeadlight.Name = "checkBoxHeadlight";
checkBoxHeadlight.Size = new Size(193, 24);
checkBoxHeadlight.Size = new Size(211, 24);
checkBoxHeadlight.TabIndex = 8;
checkBoxHeadlight.Text = "Признак наличие люка";
checkBoxHeadlight.Text = "Признак наличие фонаря";
checkBoxHeadlight.UseVisualStyleBackColor = true;
//
// checkBoxFueltank
@ -177,21 +177,21 @@
checkBoxFueltank.AutoSize = true;
checkBoxFueltank.Location = new Point(6, 169);
checkBoxFueltank.Name = "checkBoxFueltank";
checkBoxFueltank.Size = new Size(297, 24);
checkBoxFueltank.Size = new Size(276, 24);
checkBoxFueltank.TabIndex = 7;
checkBoxFueltank.Text = "Признак наличие ракетной установки";
checkBoxFueltank.Text = "Признак наличие топливного бака";
checkBoxFueltank.UseVisualStyleBackColor = true;
checkBoxFueltank.CheckedChanged += checkBoxFueltank_CheckedChanged;
//
// checkBoxPipe
//
checkBoxPipe.AutoSize = true;
checkBoxPipe.Location = new Point(6, 123);
checkBoxPipe.Name = "checkBoxPipe";
checkBoxPipe.Size = new Size(189, 24);
checkBoxPipe.Size = new Size(200, 24);
checkBoxPipe.TabIndex = 6;
checkBoxPipe.Text = "Признак наличие дула";
checkBoxPipe.Text = "Признак наличие трубы";
checkBoxPipe.UseVisualStyleBackColor = true;
checkBoxPipe.CheckedChanged += checkBoxPipe_CheckedChanged;
//
// numericUpDownWeight
//
@ -260,6 +260,7 @@
pictureBoxObject.Size = new Size(183, 125);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
pictureBoxObject.Click += pictureBoxObject_Click;
//
// buttonAdd
//

View File

@ -173,7 +173,12 @@ namespace ProjectLocomotive
}
}
private void checkBoxFueltank_CheckedChanged(object sender, EventArgs e)
private void pictureBoxObject_Click(object sender, EventArgs e)
{
}
private void checkBoxPipe_CheckedChanged(object sender, EventArgs e)
{
}

View File

@ -40,6 +40,8 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
ButtonAddLocomotive = new Button();
buttonRefresh = new Button();
ButtonRemoveLocomotive = new Button();
@ -66,9 +68,9 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(631, 28);
groupBoxTools.Location = new Point(631, 30);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(222, 651);
groupBoxTools.Size = new Size(222, 658);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты";
@ -177,6 +179,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(ButtonAddLocomotive);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ButtonRemoveLocomotive);
@ -185,27 +189,49 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 379);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(216, 274);
panelCompanyTools.Size = new Size(216, 275);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSortByColor.Location = new Point(19, 241);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(186, 31);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Right;
buttonSortByType.Location = new Point(19, 199);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(186, 37);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// ButtonAddLocomotive
//
ButtonAddLocomotive.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddLocomotive.BackgroundImageLayout = ImageLayout.Center;
ButtonAddLocomotive.Location = new Point(18, 3);
ButtonAddLocomotive.Name = "ButtonAddLocomotive";
ButtonAddLocomotive.Size = new Size(186, 40);
ButtonAddLocomotive.Size = new Size(186, 52);
ButtonAddLocomotive.TabIndex = 1;
ButtonAddLocomotive.Text = "добваление установки";
ButtonAddLocomotive.Text = "добваление поезда";
ButtonAddLocomotive.UseVisualStyleBackColor = true;
ButtonAddLocomotive.Click += ButtonAddLocomotive_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(18, 227);
buttonRefresh.Location = new Point(19, 164);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(186, 41);
buttonRefresh.Size = new Size(186, 29);
buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -214,17 +240,17 @@
// ButtonRemoveLocomotive
//
ButtonRemoveLocomotive.Anchor = AnchorStyles.Right;
ButtonRemoveLocomotive.Location = new Point(18, 138);
ButtonRemoveLocomotive.Location = new Point(19, 99);
ButtonRemoveLocomotive.Name = "ButtonRemoveLocomotive";
ButtonRemoveLocomotive.Size = new Size(186, 40);
ButtonRemoveLocomotive.Size = new Size(186, 28);
ButtonRemoveLocomotive.TabIndex = 3;
ButtonRemoveLocomotive.Text = "удалить установку";
ButtonRemoveLocomotive.Text = "удалить поезд";
ButtonRemoveLocomotive.UseVisualStyleBackColor = true;
ButtonRemoveLocomotive.Click += ButtonRemoveLocomotive_Click;
//
// maskedTextBoxPosision
//
maskedTextBoxPosision.Location = new Point(17, 105);
maskedTextBoxPosision.Location = new Point(18, 60);
maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision";
maskedTextBoxPosision.Size = new Size(187, 27);
@ -234,9 +260,9 @@
// buttonGetToTest
//
buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(18, 184);
buttonGetToTest.Location = new Point(18, 132);
buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(186, 40);
buttonGetToTest.Size = new Size(186, 27);
buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true;
@ -245,9 +271,9 @@
// pictureBoxLocomotive
//
pictureBoxLocomotive.Dock = DockStyle.Fill;
pictureBoxLocomotive.Location = new Point(0, 28);
pictureBoxLocomotive.Location = new Point(0, 30);
pictureBoxLocomotive.Name = "pictureBoxLocomotive";
pictureBoxLocomotive.Size = new Size(631, 651);
pictureBoxLocomotive.Size = new Size(631, 658);
pictureBoxLocomotive.TabIndex = 1;
pictureBoxLocomotive.TabStop = false;
pictureBoxLocomotive.Click += pictureBoxLocomotive_Click;
@ -258,7 +284,8 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(853, 28);
menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(853, 30);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
@ -297,13 +324,14 @@
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(853, 679);
ClientSize = new Size(853, 688);
Controls.Add(pictureBoxLocomotive);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormLocomotivesCollection";
Text = "FormLocomotivesCollection";
Load += FormLocomotivesCollection_Load;
groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
@ -342,5 +370,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ProjectLocomotive.CollectionGenericObjects;
using ProjectLocomotive.Drawnings;
using System.Windows.Forms;
namespace ProjectLocomotive
{
@ -174,17 +175,11 @@ namespace ProjectLocomotive
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
/// <summary>
@ -203,7 +198,10 @@ namespace ProjectLocomotive
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@ -216,7 +214,7 @@ namespace ProjectLocomotive
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);
@ -237,8 +235,8 @@ namespace ProjectLocomotive
return;
}
ICollectionGenericObjects<DrawningLocomotive>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningLocomotive>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@ -253,6 +251,7 @@ namespace ProjectLocomotive
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
@ -303,6 +302,45 @@ namespace ProjectLocomotive
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareLocomotives(new DrawningLocomotiveCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareLocomotives(IComparer<DrawningLocomotive?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBoxLocomotive.Image = _company.Show();
}
private void FormLocomotivesCollection_Load(object sender, EventArgs e)
{
}
private void pictureBoxLocomotive_Click(object sender, EventArgs e)
{