PIbd-13_Ladyagin_P.D. LabWork08 Simple #10

Closed
F1rsTTeaM wants to merge 1 commits from LabWork08 into LabWork07.2
12 changed files with 410 additions and 48 deletions
Showing only changes of commit f26076703d - Show all commits

View File

@ -60,7 +60,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirplane airplane)
{
return company._collection.Insert(airplane);
return company._collection.Insert(airplane, new DrawningAirplaneEqutables());
}
/// <summary>
@ -128,5 +128,11 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAirplane?> comparer) => _collection?.CollectionSort(comparer);
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -23,16 +23,18 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>1 - вставка прошла удачно, -1 - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -59,5 +61,10 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -55,20 +55,28 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
{
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistException();
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
if (position < 0 || position > Count)
throw new PositionOutOfCollectionException(position); ;
throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistException(position);
}
_collection.Insert(position, obj);
return position;
}
@ -90,5 +98,10 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -1,4 +1,5 @@

using System;
using ProjectAirplaneWithRadar.Exceptions;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
@ -59,8 +60,13 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistException(index);
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -72,8 +78,12 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistException(position);
}
if (position >= Count || position < 0)
throw new PositionOutOfCollectionException(position);
@ -128,5 +138,14 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}
}

View File

@ -1,4 +1,5 @@
using System.Data;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;
using ProjectAirplaneWithRadar.Drawnings;
@ -16,12 +17,12 @@ namespace ProjectAirplaneWithRadar.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>
/// Ключевое слово, с которого должен начинаться файл
@ -43,7 +44,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -53,18 +54,19 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name))
return;
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
return;
switch (collectionType)
switch (collectionInfo.CollectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
}
}
@ -75,8 +77,10 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if(_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo.Name == null || !_storages.ContainsKey(collectionInfo))
return;
_storages.Remove(collectionInfo);
}
/// <summary>
@ -88,10 +92,11 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
{
get
{
if (name == null || !_storages.ContainsKey(name))
return null;
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, "");
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo))
return null;
return _storages[name];
return _storages[collectionInfo];
}
}
@ -112,7 +117,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
using (StreamWriter sw = new(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
if (value.Value.Count == 0)
@ -122,8 +127,6 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
@ -171,21 +174,20 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
while (!sr.EndOfStream)
{
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAirplane() is T airplane)
@ -201,7 +203,7 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectAirplaneWithRadar.Entities;
namespace ProjectAirplaneWithRadar.Drawnings
{
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningAirplaneEqutables : IEqualityComparer<DrawningAirplane?>
{
public bool Equals(DrawningAirplane? x, DrawningAirplane? y)
{
if (x == null || x.EntityAirplane == null)
{
return false;
}
if (y == null || y.EntityAirplane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityAirplane.Speed != y.EntityAirplane.Speed)
{
return false;
}
if (x.EntityAirplane.Weight != y.EntityAirplane.Weight)
{
return false;
}
if (x.EntityAirplane.BodyColor != y.EntityAirplane.BodyColor)
{
return false;
}
if (x is DrawingAirplaneWithRadar && y is DrawingAirplaneWithRadar)
{
EntityAirplaneWithRadar entityX = (EntityAirplaneWithRadar)x.EntityAirplane;
EntityAirplaneWithRadar entityY = (EntityAirplaneWithRadar)y.EntityAirplane;
if (entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
if (entityX.Wheels != entityY.Wheels)
{
return false;
}
if (entityX.Radar != entityY.Radar)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAirplane obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirplaneWithRadar.Exceptions
{
[Serializable]
internal class ObjectExistException : ApplicationException
{
public ObjectExistException(int count) : base("Вставка уже существующего объекта") { }
public ObjectExistException() : base() { }
public ObjectExistException(string message) : base(message) { }
public ObjectExistException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddAirplane = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
@ -66,15 +68,17 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(445, 24);
groupBoxTools.Location = new Point(653, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(206, 523);
groupBoxTools.Size = new Size(206, 584);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAirplane);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -82,17 +86,39 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 333);
panelCompanyTools.Location = new Point(3, 335);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 187);
panelCompanyTools.Size = new Size(200, 246);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(103, 185);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(97, 56);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сорт. по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(0, 185);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(97, 56);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сорт. по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonAddAirplane
//
buttonAddAirplane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirplane.Location = new Point(0, 3);
buttonAddAirplane.Name = "buttonAddAirplane";
buttonAddAirplane.Size = new Size(97, 56);
buttonAddAirplane.Size = new Size(197, 56);
buttonAddAirplane.TabIndex = 1;
buttonAddAirplane.Text = "Добавить самолет";
buttonAddAirplane.UseVisualStyleBackColor = true;
@ -249,7 +275,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(445, 523);
pictureBox.Size = new Size(653, 584);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -258,7 +284,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(651, 24);
menuStrip.Size = new Size(859, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
@ -297,7 +323,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(651, 547);
ClientSize = new Size(859, 608);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -342,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -82,7 +82,12 @@ namespace ProjectAirplaneWithRadar
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
catch (ObjectExistException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
}
/// <summary>
@ -237,7 +242,7 @@ namespace ProjectAirplaneWithRadar
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);
}
@ -322,5 +327,26 @@ namespace ProjectAirplaneWithRadar
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareAirplanes(new DrawningAirplaneCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareAirplanes(new DrawningAirplaneCompareByColor());
}
private void CompareAirplanes(IComparer<DrawningAirplane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}