PIbd-14 Antonova_A.A. LabWork08 Simple #7

Closed
Anitonchik wants to merge 1 commits from LabWork08 into LabWork07
12 changed files with 394 additions and 54 deletions
Showing only changes of commit 3ecffd4d54 - Show all commits

View File

@ -38,6 +38,7 @@ public abstract class AbstractCompany
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -60,7 +61,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTruck truck)
{
return company._collection.Insert(truck);
return company._collection.Insert(truck, new DrawiningTruckEqutables());
}
/// <summary>
@ -105,6 +106,13 @@ public abstract class AbstractCompany
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTruck?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>
@ -114,4 +122,6 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.CollectionGenericObjects;
public class 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,6 @@
using System;
using ProjectDumpTruck.Drawnings;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -27,14 +29,14 @@ where T : class
/// </summary>
/// <param name="obj">Добавляемый объект</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>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -57,6 +59,10 @@ where T : class
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,4 +1,5 @@
using ProjectDumpTruck.Exceptions;
using ProjectDumpTruck.Drawnings;
using ProjectDumpTruck.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -27,7 +28,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
get
{
return MaxCount;
return _maxCount;
}
set
{
@ -56,8 +57,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectsEqualException();
}
}
if (_collection.Count >= _maxCount)
{
throw new CollectionOverflowException(MaxCount);
@ -66,8 +74,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection.Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectsEqualException(position);
}
}
if (position < 0 || position > _maxCount)
{
throw new PositionOutOfCollectionException(position);
@ -99,5 +114,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -63,25 +63,45 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
for (int i = 0; i < MaxCount; ++i)
if (comparer != null)
{
if (_collection[i] == null)
for (int i = 0; i < MaxCount; ++i)
{
_collection[i] = obj;
return i;
if ((comparer as IEqualityComparer<DrawningTruck>).Equals(obj as DrawningTruck, _collection[i] as DrawningTruck))
{
throw new ObjectsEqualException(i);
}
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<T?>? comparer = null)
{
if (position < 0 || position >= MaxCount)
{
throw new PositionOutOfCollectionException(Count);
}
if (comparer != null)
{
for (int i = 0; i < position; i++)
{
if (_collection[i] != null)
{
if ((comparer as IEqualityComparer<DrawningTruck>).Equals(obj as DrawningTruck, _collection[i] as DrawningTruck))
{
throw new ObjectsEqualException(i);
}
}
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
@ -127,5 +147,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -18,11 +18,11 @@ public class StorageCollection<T>
/// <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>
/// Ключевое слово, с которого должен начинаться файл
@ -42,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -52,7 +52,8 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name))
CollectionInfo info = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(info))
{
return;
}
@ -61,13 +62,13 @@ public class StorageCollection<T>
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(info, new MassiveGenericObjects<T>());
break;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(info, new ListGenericObjects<T>());
break;
}
}
}
/// <summary>
/// Удаление коллекции
@ -75,9 +76,10 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
CollectionInfo info = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(info))
{
_storages.Remove(name);
_storages.Remove(info);
}
}
@ -91,9 +93,10 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
CollectionInfo info = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(info))
{
return _storages[name];
return _storages[info];
}
return null;
}
@ -121,16 +124,14 @@ public class StorageCollection<T>
wr.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
wr.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
wr.Write(value.Key);
wr.Write(_separatorForKeyValue);
wr.Write(value.Value.GetCollectionType);
wr.Write(value.Key.ToString());
wr.Write(_separatorForKeyValue);
wr.Write(value.Value.MaxCount);
wr.Write(_separatorForKeyValue);
@ -177,18 +178,21 @@ public class StorageCollection<T>
while ((strs = rd.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? col_info = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]); ;
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(col_info.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекции");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTruck() is T truck)
@ -207,7 +211,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(col_info, collection);
}
}

View File

@ -0,0 +1,63 @@
using ProjectDumpTruck.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
public class DrawiningTruckEqutables : IEqualityComparer<DrawningTruck?>
{
public bool Equals(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return false;
}
if (y == null || y.EntityTruck == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTruck.Speed != y.EntityTruck.Speed)
{
return false;
}
if (x.EntityTruck.Weight != y.EntityTruck.Weight)
{
return false;
}
if (x.EntityTruck.BodyColor != y.EntityTruck.BodyColor)
{
return false;
}
if (x is DrawningDumpTruck && y is DrawningDumpTruck)
{
EntityDumpTruck dump_truck_x = (EntityDumpTruck)x.EntityTruck;
EntityDumpTruck dump_truck_y = (EntityDumpTruck)y.EntityTruck;
if (dump_truck_x.Body != dump_truck_y.Body)
{
return false;
}
if (dump_truck_x.Tent != dump_truck_y.Tent)
{
return false;
}
if (dump_truck_x.AdditionalColor != dump_truck_y.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTruck? obj)
{
throw new NotImplementedException();
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Drawnings;
public class DrawningTruckCompareByColor : IComparer<DrawningTruck?>
{
public int Compare(DrawningTruck? x, DrawningTruck? y)
{
if (x == null || x.EntityTruck == null)
{
return 1;
}
if (y == null || y.EntityTruck == null)
{
return -1;
}
var bodycolorCompare = x.EntityTruck.BodyColor.Name.CompareTo(y.EntityTruck.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTruck.Speed.CompareTo(y.EntityTruck.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTruck.Weight.CompareTo(y.EntityTruck.Weight);
}
}

View File

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

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.Exceptions;
public class ObjectsEqualException : ApplicationException
{
public ObjectsEqualException(int i) : base("В коллекции находится такой же элемент на позиции " + i) { }
public ObjectsEqualException() : base( "В коллекции находится такой же элемент") { }
public ObjectsEqualException(string message) : base(message) { }
public ObjectsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -68,22 +70,24 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(832, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 799);
groupBoxTools.Size = new Size(250, 925);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTruck);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToChek);
panelCompanyTools.Controls.Add(buttonRemoveTruck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 464);
panelCompanyTools.Location = new Point(3, 479);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(244, 332);
panelCompanyTools.Size = new Size(244, 443);
panelCompanyTools.TabIndex = 4;
//
// buttonAddTruck
@ -245,7 +249,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(832, 799);
pictureBox.Size = new Size(832, 925);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
@ -291,11 +295,31 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(15, 371);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(220, 57);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(15, 308);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(220, 57);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormTruckCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1082, 827);
ClientSize = new Size(1082, 953);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -340,5 +364,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -79,17 +79,22 @@ public partial class FormTruckCollection : Form
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен");
_logger.LogInformation("Объект добавлен");
}
}
catch (Exception ex)
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка: {ex.Message}");
MessageBox.Show("Коллекция переполнена");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectsEqualException ex)
{
MessageBox.Show("Такой объект уже существует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -118,7 +123,8 @@ public partial class FormTruckCollection : Form
_logger.LogInformation("Объект удален");
}
}
catch (Exception ex) {
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
@ -205,7 +211,7 @@ public partial class FormTruckCollection : Form
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);
@ -286,18 +292,43 @@ public partial class FormTruckCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
catch (Exception ex)
{
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTrucks(new DrawningTruckCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTrucks(IComparer<DrawningTruck?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}