In process : wasn't checked [!]

This commit is contained in:
Inna Pruidze 2024-06-16 21:39:45 +04:00
parent 5071187623
commit 9c904ea947
11 changed files with 343 additions and 92 deletions

View File

@ -30,14 +30,19 @@ public abstract class AbstractCompany
} }
// Перегрузка оператора сложения для класса // Перегрузка оператора сложения для класса
// [ ! ] insted of bool:
public static int operator +(AbstractCompany company, public static int operator +(AbstractCompany company,
DrawningBase trasport) => company._collection.Insert(trasport); DrawningBase trasport) =>
company._collection.Insert(trasport, new DrawiningShipEqutables());
// Перегрузка оператора удаления для класса // Перегрузка оператора удаления для класса
public static DrawningBase operator -(AbstractCompany company, public static DrawningBase operator -(AbstractCompany company,
int pos) => company._collection.Remove(pos); int pos) => company._collection.Remove(pos);
// Сортировка ----------------------------------------------------------- [!]
public void Sort(IComparer<DrawningBase?> comparer) =>
_collection?.CollectionSort(comparer);
// Получение случайного объекта из коллекции // Получение случайного объекта из коллекции
public DrawningBase? GetRandomObject() public DrawningBase? GetRandomObject()
{ {

View File

@ -1,4 +1,5 @@
using ProjectCruiser.Exceptions; using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
@ -46,16 +47,19 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
throw new ObjectNotFoundException(index); throw new ObjectNotFoundException(index);
return _collection[index]; return _collection[index];
// CollectionOverflowException
// PositionOutOfCollectionException
// ObjectNotFoundException
} }
public int Insert(T? item) public int Insert(T? item, IEqualityComparer<DrawningBase?>? cmpr = null)
{ {
if (item == null) throw if (item == null) throw
new NullReferenceException("> Inserting item is null"); new NullReferenceException("> Inserting item is null");
else
{
if (cmpr != null && item == cmpr)
{
throw new Exception();
}
}
// выход за границы, курируется CollectionOverflowException // выход за границы, курируется CollectionOverflowException
if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (Count >= _maxCount) throw new CollectionOverflowException(Count);
@ -70,18 +74,23 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
} }
} }
return Count; return Count;
// NullReferenceException
// CollectionOverflowException
} }
public int Insert(T? item, int index) public int Insert(T? item, int index, IEqualityComparer<DrawningBase?>? cmpr = null)
{ {
if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index);
if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (item == null) throw if (item == null) throw
new NullReferenceException("> Inserting item (at position) is null"); new NullReferenceException("> Inserting item (at position) is null");
else
{
if (cmpr != null && item == cmpr)
{
throw new Exception();
}
}
if (_collection[index] == null) if (_collection[index] == null)
{ {
@ -104,10 +113,6 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
_collection[firstNullIndex] = item; _collection[firstNullIndex] = item;
return firstNullIndex; return firstNullIndex;
} }
// PositionOutOfCollectionException
// CollectionOverflowException
// NullReferenceException
} }
public T? Remove(int index) public T? Remove(int index)
@ -124,9 +129,6 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
if (item == null) throw new ObjectNotFoundException(index); if (item == null) throw new ObjectNotFoundException(index);
return item; return item;
// PositionOutOfCollectionException
// ObjectNotFoundException
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
@ -136,5 +138,10 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -0,0 +1,63 @@
namespace ProjectCruiser.CollectionGenericObj;
// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
// Название коллекции
public string Name { get; private set; }
// Тип
public CollectionType CollectionType { get; private set; }
// Описание
public string Description { get; private set; }
// Разделитель для записи информации по объекту в файл
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
// Создание объекта из строки
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType),
strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
// if (Name != other.Name) return false; >>>
// else if (CollectionType != other.CollectionType) return false;
// else if (Description != other.Description) return false;
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,6 @@
namespace ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples;
namespace ProjectCruiser.CollectionGenericObj;
public interface ICollectionGenObj<T> where T : class public interface ICollectionGenObj<T> where T : class
{ {
@ -11,8 +13,8 @@ public interface ICollectionGenObj<T> where T : class
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<DrawningBase?>? cmpr = null);
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<DrawningBase?>? cmpr = null);
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
@ -27,4 +29,8 @@ public interface ICollectionGenObj<T> where T : class
// Получение объектов коллекции по одному // Получение объектов коллекции по одному
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
// Сортировка коллекции
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,4 +1,5 @@
using ProjectCruiser.Exceptions; using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
@ -48,10 +49,17 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T? obj) public int Insert(T? obj, IEqualityComparer<DrawningBase?>? cmpr = null)
{ {
if (obj == null) if (obj == null)
throw new NullReferenceException("> Inserting object is null"); throw new NullReferenceException("> Inserting object is null");
else
{
if (cmpr != null && obj == cmpr)
{
throw new Exception();
}
}
// выход за границы, курируется CollectionOverflowException // выход за границы, курируется CollectionOverflowException
if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (Count >= _maxCount) throw new CollectionOverflowException(Count);
@ -60,7 +68,7 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return Count; return Count;
} }
public int Insert(T? obj, int position) public int Insert(T? obj, int position, IEqualityComparer<DrawningBase?>? cmpr = null)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
throw new PositionOutOfCollectionException(position); throw new PositionOutOfCollectionException(position);
@ -68,6 +76,13 @@ public class ListGenObj<T> : ICollectionGenObj<T>
if (obj == null) if (obj == null)
throw new NullReferenceException("> Inserting object (at position) is null"); throw new NullReferenceException("> Inserting object (at position) is null");
else
{
if (cmpr != null && obj == cmpr)
{
throw new Exception();
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -96,4 +111,9 @@ public class ListGenObj<T> : ICollectionGenObj<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,56 +1,58 @@
using System.Security.Cryptography; using System.CodeDom;
using System.Text; using System.Text;
using ProjectCruiser.DrawningSamples; using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningBase // class where T : DrawningBase // class
{ {
// Разделитель для записи ключа и значения элемента словаря
private readonly string _separatorForKeyValue = "|"; private readonly string _separatorForKeyValue = "|";
// Разделитель для записей коллекции данных в файл
private readonly string _separatorItems = ";"; private readonly string _separatorItems = ";";
// Ключевое слово, с которого должен начинаться файл
private readonly string _collectionKey = "CollectionsStorage"; private readonly string _collectionKey = "CollectionsStorage";
// Словарь (хранилище) с коллекциями < name, type (class) > // Словарь (хранилище) с коллекциями < CollectionInfo, type (class) >
readonly Dictionary<string, ICollectionGenObj<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenObj<T>> _storages;
// Возвращение списка названий коллекций // Возвращение списка коллекций
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenObj<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenObj<T>>();
} }
// Добавление коллекции в хранилище // Добавление коллекции в хранилище
public void AddCollection(string name, CollectionType collType) public void AddCollection(string name, CollectionType collType)
{ {
if (name == null || _storages.ContainsKey(name) // descroption [ ? ] >>>
CollectionInfo coll = new CollectionInfo(name, collType, string.Empty);
if (name == null || _storages.ContainsKey(coll)
|| collType == CollectionType.None) || collType == CollectionType.None)
{ {
throw new NullReferenceException("> Not enough information to save"); throw new NullReferenceException("> Not enough information to save");
} }
ICollectionGenObj<T> collection = CreateCollection(collType); _storages.Add(coll, CreateCollection(collType));
_storages.Add(name, collection);
} }
// Удаление коллекции ( по ключу-строке - её имени ) // Удаление коллекции ( по ключу-строке - её имени )
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) _storages.Remove(name); // descroption [ ? ] >>>
CollectionInfo coll = new CollectionInfo(name,
CollectionType.None, string.Empty);
if (_storages.ContainsKey(coll)) _storages.Remove(coll);
else throw new NullReferenceException("> No such key in the list"); else throw new NullReferenceException("> No such key in the list");
} }
// Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] // Доступ к коллекции , индексатор [!!!]
public ICollectionGenObj<T>? this[string name] public ICollectionGenObj<T>? this[string name]
{ {
get => _storages.ContainsKey(name) ? _storages[name] : null; get => _storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))
? _storages[new CollectionInfo(name, CollectionType.None, string.Empty)] : null;
} }
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по автомобилям в хранилище в файл
@ -68,15 +70,14 @@ public class StorageCollection<T>
sb.Append(_collectionKey); // const sb.Append(_collectionKey); // const
foreach (KeyValuePair<string, ICollectionGenObj<T>> pair in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenObj<T>> pair in _storages)
{ {
sb.Append(Environment.NewLine); // не сохраняем пустые коллекции sb.Append(Environment.NewLine); // не сохраняем пустые коллекции
if (pair.Value.Count == 0) { continue; } if (pair.Value.Count == 0) { continue; }
sb.Append(pair.Key); sb.Append(pair.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(pair.Value.GetCollectionType); // <...>
sb.Append(_separatorForKeyValue);
sb.Append(pair.Value.MaxCount); sb.Append(pair.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
@ -144,18 +145,19 @@ public class StorageCollection<T>
foreach (string data in companies) foreach (string data in companies)
{ {
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) // > if (record.Length != 3) // >
// key | collType | maxcount | all next inf > 4 // [key + collType] | maxcount | all next inf > 4
{ continue; } { continue; }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenObj<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("[!] Failed to decode information : " + record[0]);
if (collection == null)
throw new NullReferenceException("[!] Failed to create collection");
collection.MaxCount = Convert.ToInt32(record[2]); ICollectionGenObj<T>? collection = StorageCollection<T>.CreateCollection(
string[] set = record[3].Split(_separatorItems, collInfo.CollectionType) ??
throw new Exception("[!] Failed to create a collection");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
@ -165,10 +167,6 @@ public class StorageCollection<T>
try try
{ {
collection.Insert(ship); collection.Insert(ship);
// throw new IndexOutOfRangeException IF IT WAS Insert(item, pos)
// NullReferenceException >
// CollectionOverflowException >
} }
catch (Exception e) catch (Exception e)
{ {
@ -176,7 +174,7 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collInfo, collection);
} }
} }
} }

View File

@ -0,0 +1,30 @@
namespace ProjectCruiser.DrawningSamples;
// Сравнение по типу, скорости, весу
public class DrawningShipCompare : IComparer<DrawningBase?>
{
public int Compare(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null)
{
return -1;
}
if (y == null || y.EntityTransport == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight);
}
}

View File

@ -0,0 +1,34 @@
namespace ProjectCruiser.DrawningSamples;
public class DrawningShipCompareByColor : IComparer<DrawningBase?>
{
public int Compare(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null)
{
return 1;
}
if (y == null || y.EntityTransport == null)
{
return -1;
}
var bodycolorCompare = x.EntityTransport.MainColor.Name.CompareTo(
y.EntityTransport.MainColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight);
}
}

View File

@ -0,0 +1,43 @@
using System.Diagnostics.CodeAnalysis;
using ProjectCruiser.Entities;
namespace ProjectCruiser.DrawningSamples;
// Реализация сравнения двух объектов класса-прорисовки
public class DrawiningShipEqutables : IEqualityComparer<DrawningBase?>
{
public bool Equals(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null) return false;
if (y == null || y.EntityTransport == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityTransport.Speed != y.EntityTransport.Speed) return false;
if (x.EntityTransport.Weight != y.EntityTransport.Weight) return false;
if (x.EntityTransport.MainColor != y.EntityTransport.MainColor) return false;
if (x is DrawningCruiser && y is DrawningCruiser)
{
/*
public Color AdditionalColor { get; private set; } // доп. цвет
// признаки (наличия)
public bool HelicopterPads { get; private set; } // вертолетная площадка
public bool Hangars { get; private set; } // ангар
*/
if (((EntityCruiser)x.EntityTransport).AdditionalColor
!= ((EntityCruiser)y.EntityTransport).AdditionalColor) return false;
if (((EntityCruiser)x.EntityTransport).HelicopterPads
!= ((EntityCruiser)y.EntityTransport).HelicopterPads) return false;
if (((EntityCruiser)x.EntityTransport).Hangars
!= ((EntityCruiser)y.EntityTransport).Hangars) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBase obj)
{
return obj.GetHashCode();
}
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
btnSortType = new Button();
btnSortColor = new Button();
groupBox.SuspendLayout(); groupBox.SuspendLayout();
companyPanel.SuspendLayout(); companyPanel.SuspendLayout();
toolPanel.SuspendLayout(); toolPanel.SuspendLayout();
@ -64,7 +66,7 @@
comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
comboBoxArrList.FormattingEnabled = true; comboBoxArrList.FormattingEnabled = true;
comboBoxArrList.Items.AddRange(new object[] { "Storage" }); comboBoxArrList.Items.AddRange(new object[] { "Storage" });
comboBoxArrList.Location = new Point(17, 51); comboBoxArrList.Location = new Point(17, 38);
comboBoxArrList.Name = "comboBoxArrList"; comboBoxArrList.Name = "comboBoxArrList";
comboBoxArrList.Size = new Size(241, 40); comboBoxArrList.Size = new Size(241, 40);
comboBoxArrList.TabIndex = 0; comboBoxArrList.TabIndex = 0;
@ -77,9 +79,9 @@
groupBox.Controls.Add(toolPanel); groupBox.Controls.Add(toolPanel);
groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(btnCreateCompany);
groupBox.Controls.Add(comboBoxArrList); groupBox.Controls.Add(comboBoxArrList);
groupBox.Location = new Point(1421, 47); groupBox.Location = new Point(1421, 43);
groupBox.Name = "groupBox"; groupBox.Name = "groupBox";
groupBox.Size = new Size(273, 934); groupBox.Size = new Size(273, 964);
groupBox.TabIndex = 2; groupBox.TabIndex = 2;
groupBox.TabStop = false; groupBox.TabStop = false;
groupBox.Text = "Tool panel"; groupBox.Text = "Tool panel";
@ -93,17 +95,17 @@
companyPanel.Controls.Add(rBtnArray); companyPanel.Controls.Add(rBtnArray);
companyPanel.Controls.Add(maskedTxtBoxCName); companyPanel.Controls.Add(maskedTxtBoxCName);
companyPanel.Controls.Add(label); companyPanel.Controls.Add(label);
companyPanel.Location = new Point(17, 98); companyPanel.Location = new Point(17, 83);
companyPanel.Name = "companyPanel"; companyPanel.Name = "companyPanel";
companyPanel.Size = new Size(243, 391); companyPanel.Size = new Size(243, 359);
companyPanel.TabIndex = 7; companyPanel.TabIndex = 7;
// //
// btnDeleteCollection // btnDeleteCollection
// //
btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnDeleteCollection.Location = new Point(15, 312); btnDeleteCollection.Location = new Point(16, 276);
btnDeleteCollection.Name = "btnDeleteCollection"; btnDeleteCollection.Name = "btnDeleteCollection";
btnDeleteCollection.Size = new Size(214, 73); btnDeleteCollection.Size = new Size(214, 76);
btnDeleteCollection.TabIndex = 11; btnDeleteCollection.TabIndex = 11;
btnDeleteCollection.Text = "Remove Collection"; btnDeleteCollection.Text = "Remove Collection";
btnDeleteCollection.UseVisualStyleBackColor = true; btnDeleteCollection.UseVisualStyleBackColor = true;
@ -112,17 +114,17 @@
// listBox // listBox
// //
listBox.FormattingEnabled = true; listBox.FormattingEnabled = true;
listBox.Location = new Point(16, 174); listBox.Location = new Point(16, 171);
listBox.Name = "listBox"; listBox.Name = "listBox";
listBox.Size = new Size(214, 132); listBox.Size = new Size(214, 100);
listBox.TabIndex = 10; listBox.TabIndex = 10;
// //
// btnAddCollection // btnAddCollection
// //
btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnAddCollection.Location = new Point(15, 119); btnAddCollection.Location = new Point(15, 118);
btnAddCollection.Name = "btnAddCollection"; btnAddCollection.Name = "btnAddCollection";
btnAddCollection.Size = new Size(214, 50); btnAddCollection.Size = new Size(214, 49);
btnAddCollection.TabIndex = 7; btnAddCollection.TabIndex = 7;
btnAddCollection.Text = "Add Collection"; btnAddCollection.Text = "Add Collection";
btnAddCollection.UseVisualStyleBackColor = true; btnAddCollection.UseVisualStyleBackColor = true;
@ -142,7 +144,7 @@
// rBtnArray // rBtnArray
// //
rBtnArray.AutoSize = true; rBtnArray.AutoSize = true;
rBtnArray.Location = new Point(16, 80); rBtnArray.Location = new Point(16, 79);
rBtnArray.Name = "rBtnArray"; rBtnArray.Name = "rBtnArray";
rBtnArray.Size = new Size(100, 36); rBtnArray.Size = new Size(100, 36);
rBtnArray.TabIndex = 8; rBtnArray.TabIndex = 8;
@ -169,23 +171,25 @@
// //
// toolPanel // toolPanel
// //
toolPanel.Controls.Add(btnSortColor);
toolPanel.Controls.Add(btnSortType);
toolPanel.Controls.Add(btnUpdate); toolPanel.Controls.Add(btnUpdate);
toolPanel.Controls.Add(btnTest); toolPanel.Controls.Add(btnTest);
toolPanel.Controls.Add(maskedTextBoxPosition); toolPanel.Controls.Add(maskedTextBoxPosition);
toolPanel.Controls.Add(btnDelete); toolPanel.Controls.Add(btnDelete);
toolPanel.Controls.Add(btnAddCruiser); toolPanel.Controls.Add(btnAddCruiser);
toolPanel.Enabled = false; toolPanel.Enabled = false;
toolPanel.Location = new Point(26, 608); toolPanel.Location = new Point(26, 537);
toolPanel.Name = "toolPanel"; toolPanel.Name = "toolPanel";
toolPanel.Size = new Size(226, 317); toolPanel.Size = new Size(226, 415);
toolPanel.TabIndex = 13; toolPanel.TabIndex = 13;
// //
// btnUpdate // btnUpdate
// //
btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnUpdate.Location = new Point(16, 257); btnUpdate.Location = new Point(16, 350);
btnUpdate.Name = "btnUpdate"; btnUpdate.Name = "btnUpdate";
btnUpdate.Size = new Size(192, 41); btnUpdate.Size = new Size(193, 57);
btnUpdate.TabIndex = 6; btnUpdate.TabIndex = 6;
btnUpdate.Text = "Update"; btnUpdate.Text = "Update";
btnUpdate.UseVisualStyleBackColor = true; btnUpdate.UseVisualStyleBackColor = true;
@ -194,9 +198,9 @@
// btnTest // btnTest
// //
btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnTest.Location = new Point(17, 162); btnTest.Location = new Point(17, 142);
btnTest.Name = "btnTest"; btnTest.Name = "btnTest";
btnTest.Size = new Size(192, 89); btnTest.Size = new Size(192, 80);
btnTest.TabIndex = 5; btnTest.TabIndex = 5;
btnTest.Text = "Choose\r\nfor testing"; btnTest.Text = "Choose\r\nfor testing";
btnTest.UseVisualStyleBackColor = true; btnTest.UseVisualStyleBackColor = true;
@ -205,7 +209,7 @@
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(17, 68); maskedTextBoxPosition.Location = new Point(17, 55);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(192, 39); maskedTextBoxPosition.Size = new Size(192, 39);
@ -215,9 +219,9 @@
// btnDelete // btnDelete
// //
btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnDelete.Location = new Point(16, 113); btnDelete.Location = new Point(17, 99);
btnDelete.Name = "btnDelete"; btnDelete.Name = "btnDelete";
btnDelete.Size = new Size(192, 43); btnDelete.Size = new Size(192, 41);
btnDelete.TabIndex = 4; btnDelete.TabIndex = 4;
btnDelete.Text = "Delete"; btnDelete.Text = "Delete";
btnDelete.UseVisualStyleBackColor = true; btnDelete.UseVisualStyleBackColor = true;
@ -226,9 +230,9 @@
// btnAddCruiser // btnAddCruiser
// //
btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnAddCruiser.Location = new Point(17, 13); btnAddCruiser.Location = new Point(16, 4);
btnAddCruiser.Name = "btnAddCruiser"; btnAddCruiser.Name = "btnAddCruiser";
btnAddCruiser.Size = new Size(192, 49); btnAddCruiser.Size = new Size(192, 48);
btnAddCruiser.TabIndex = 2; btnAddCruiser.TabIndex = 2;
btnAddCruiser.Text = "Add cruiser"; btnAddCruiser.Text = "Add cruiser";
btnAddCruiser.UseVisualStyleBackColor = true; btnAddCruiser.UseVisualStyleBackColor = true;
@ -237,9 +241,9 @@
// btnCreateCompany // btnCreateCompany
// //
btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnCreateCompany.Location = new Point(16, 510); btnCreateCompany.Location = new Point(17, 447);
btnCreateCompany.Name = "btnCreateCompany"; btnCreateCompany.Name = "btnCreateCompany";
btnCreateCompany.Size = new Size(245, 79); btnCreateCompany.Size = new Size(245, 85);
btnCreateCompany.TabIndex = 12; btnCreateCompany.TabIndex = 12;
btnCreateCompany.Text = "Create or switch to Company"; btnCreateCompany.Text = "Create or switch to Company";
btnCreateCompany.UseVisualStyleBackColor = true; btnCreateCompany.UseVisualStyleBackColor = true;
@ -295,6 +299,28 @@
// //
openFileDialog.Filter = "txt file|*.txt"; openFileDialog.Filter = "txt file|*.txt";
// //
// btnSortType
//
btnSortType.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnSortType.Location = new Point(16, 232);
btnSortType.Name = "btnSortType";
btnSortType.Size = new Size(192, 52);
btnSortType.TabIndex = 7;
btnSortType.Text = "Sort by type";
btnSortType.UseVisualStyleBackColor = true;
btnSortType.Click += btnSortType_Click;
//
// btnSortColor
//
btnSortColor.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnSortColor.Location = new Point(16, 285);
btnSortColor.Name = "btnSortColor";
btnSortColor.Size = new Size(192, 52);
btnSortColor.TabIndex = 8;
btnSortColor.Text = "Sort by color";
btnSortColor.UseVisualStyleBackColor = true;
btnSortColor.Click += btnSortColor_Click;
//
// ServiceForm2 // ServiceForm2
// //
AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleDimensions = new SizeF(13F, 32F);
@ -344,5 +370,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button btnSortColor;
private Button btnSortType;
} }
} }

View File

@ -177,7 +177,8 @@ public partial class ServiceForm2 : Form
{ {
MessageBox.Show("Collection was not choosed"); MessageBox.Show("Collection was not choosed");
return; return;
} if (MessageBox.Show("Are you sure?", "Removing", }
if (MessageBox.Show("Are you sure?", "Removing",
MessageBoxButtons.OK, MessageBoxIcon.Question) MessageBoxButtons.OK, MessageBoxIcon.Question)
!= DialogResult.OK) return; != DialogResult.OK) return;
@ -199,7 +200,8 @@ public partial class ServiceForm2 : Form
listBox.Items.Clear(); listBox.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? collName = _storageCollection.Keys?[i]; string? collName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(collName)) if (!string.IsNullOrEmpty(collName))
{ {
listBox.Items.Add(collName); listBox.Items.Add(collName);
@ -264,12 +266,6 @@ public partial class ServiceForm2 : Form
try try
{ {
_storageCollection.LoadData(openFileDialog.FileName); _storageCollection.LoadData(openFileDialog.FileName);
// LoadData() : Exceptions
// FileNotFoundException
// NullReferenceException
// InvalidDataException
// IndexOutOfRangeException
// CollectionOverflowException
MessageBox.Show(" < Loaded succesfully >", MessageBox.Show(" < Loaded succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
@ -285,4 +281,25 @@ public partial class ServiceForm2 : Form
} }
} }
} }
// Сортировка по сравнителю
private void CompareShips(IComparer<DrawningBase?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void btnSortType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompare());
}
private void btnSortColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByColor());
}
} }