This commit is contained in:
mar-va 2024-06-10 00:58:29 +04:00
parent fa6661bfce
commit c1149954f4
14 changed files with 561 additions and 236 deletions

View File

@ -33,7 +33,7 @@ public abstract class AbstractCompany
public static int operator +(AbstractCompany company, DrawningBus bus) public static int operator +(AbstractCompany company, DrawningBus bus)
{ {
return company._collection.Insert(bus); return company._collection.Insert(bus, new DrawningBusEqutables());
} }
public static DrawningBus operator -(AbstractCompany company, int position) public static DrawningBus operator -(AbstractCompany company, int position)
@ -53,7 +53,6 @@ public abstract class AbstractCompany
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics); DrawBackground(graphics);
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
DrawningBus? obj = _collection?.Get(i); DrawningBus? obj = _collection?.Get(i);
@ -64,6 +63,11 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
public void Sort(IComparer<DrawningBus?> comparer)
{
_collection?.CollectionSort(comparer);
}
protected abstract void DrawBackground(Graphics g); protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus); protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus);

View File

@ -0,0 +1,77 @@
namespace ProjectAccordionBus.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

@ -29,14 +29,14 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@ -62,5 +62,11 @@ public interface ICollectionGenericObjects<T>
/// </summary> /// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns> /// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -1,9 +1,5 @@
using ProjectAccordionBus.Exceptions; using ProjectAccordionBus.Exceptions;
using System; using ProjectAirbus.Exceptions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects; namespace ProjectAccordionBus.CollectionGenericObjects;
@ -14,7 +10,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount; private int _maxCount;
public int MaxCount { public int MaxCount {
get => _maxCount; get =>_maxCount;
set set
{ {
if (value > 0) if (value > 0)
@ -36,28 +32,57 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Get(int position) public T Get(int position)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position]; 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 (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj); _collection.Add(obj);
return Count; 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 (comparer != null)
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); {
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
@ -70,4 +95,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,9 +1,6 @@
using ProjectAccordionBus.Exceptions; using ProjectAccordionBus.Exceptions;
using System; using ProjectAirbus.Exceptions;
using System.Collections.Generic; using ProjectAccordionBus.Drawnings;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.CollectionGenericObjects; namespace ProjectAccordionBus.CollectionGenericObjects;
@ -61,8 +58,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningBus>).Equals(obj as DrawningBus, item as DrawningBus))
{
throw new ObjectNotUniqueException();
}
}
}
// TODO вставка в свободное место набора
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
@ -75,44 +83,56 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
int index = position + 1; else
while (index < _collection.Length)
{ {
if (_collection[index] == null) for (int i = position + 1; i < Count; i++)
{ {
_collection[index] = obj; if (_collection[i] == null)
return index; {
_collection[i] = obj;
return i;
}
} }
++index;
} for (int i = 0; i < position; i++)
index = position - 1;
while (index >= 0)
{
if (_collection[index] == null)
{ {
_collection[index] = obj; if (_collection[i] == null)
return index; {
_collection[i] = obj;
return i;
}
} }
--index;
} }
throw new CollectionOverflowException(Count); throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0)
if (_collection[position] == null) throw new ObjectNotFoundException(position); {
T? temp = _collection[position]; throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
if (obj == null)
{
throw new ObjectNotFoundException(position);
}
_collection[position] = null; _collection[position] = null;
return temp; return obj;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
@ -122,5 +142,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -1,10 +1,6 @@
using ProjectAccordionBus.Drawnings; using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;
using ProjectAccordionBus.Exceptions; using ProjectAccordionBus.Exceptions;
namespace ProjectAccordionBus.CollectionGenericObjects; namespace ProjectAccordionBus.CollectionGenericObjects;
@ -15,12 +11,12 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -41,7 +37,7 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -51,19 +47,21 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (name == null || _storages.ContainsKey(name)) CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
return;
switch (collectionType) if (_storages.ContainsKey(collectionInfo) || collectionInfo.CollectionType == CollectionType.None)
{
return;
}
switch (collectionInfo.CollectionType)
{ {
case CollectionType.None:
return;
case CollectionType.Massive: case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
return; break;
case CollectionType.List: case CollectionType.List:
_storages[name] = new ListGenericObjects<T>(); _storages[collectionInfo] = new ListGenericObjects<T>();
return; break;
default: break;
} }
} }
/// <summary> /// <summary>
@ -72,8 +70,11 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
_storages.Remove(name); if (_storages.ContainsKey(collectionInfo) && collectionInfo != null)
{
_storages.Remove(collectionInfo);
}
} }
/// <summary> /// <summary>
@ -85,11 +86,12 @@ public class StorageCollection<T>
{ {
get get
{ {
if (name == "") CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{ {
return null; return _storages[collectionInfo];
} }
return _storages[name]; return null;
} }
} }
@ -97,29 +99,32 @@ public class StorageCollection<T>
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения"); throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using (StreamWriter writer = new(filename))
using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(Environment.NewLine); StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
writer.Write(value.Key);
writer.Write(_separatorForKeyValue); sb.Append(value.Key);
writer.Write(value.Value.GetCollectionType); sb.Append(_separatorForKeyValue);
writer.Write(_separatorForKeyValue); sb.Append(value.Value.MaxCount);
writer.Write(value.Value.MaxCount); sb.Append(_separatorForKeyValue);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
@ -128,56 +133,65 @@ public class StorageCollection<T>
{ {
continue; continue;
} }
writer.Write(data);
writer.Write(_separatorItems); sb.Append(data);
sb.Append(_separatorItems);
} }
writer.Write(sb);
} }
} }
} }
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException($"{filename} не существует"); throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
throw new IOException("Файл не подходит");
}
if (!line.Equals(_collectionKey))
{
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new IOException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new IOException("В файле неверные данные"); throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null) string strs = "";
while ((strs = fs.ReadLine()) != null)
{ {
string[] record = line.Split(_separatorForKeyValue, string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries); if (record.Length != 3)
if (record.Length != 4)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
if (collection == null) throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
{ ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию"); throw new Exception("Не удалось определить тип коллекции: " + record[1]);
} collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningBus() is T armoredCar) if (elem?.CreateDrawningBus() is T airbus)
{ {
try try
{ {
if (collection.Insert(armoredCar) == -1) if (collection.Insert(airbus) == -1)
{ {
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
} }
@ -188,24 +202,23 @@ public class StorageCollection<T>
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(collectionInfo, collection);
} }
} }
} }
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типа
/// </summary> /// </summary>
/// <param name="collectionType"></param> /// <param name="collectionType"></param>
/// <returns></returns> /// <returns></returns>
private static ICollectionGenericObjects<T>? private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
CreateCollection(CollectionType collectionType) {
return collectionType switch
{ {
return collectionType switch CollectionType.Massive => new MassiveGenericObjects<T>(),
{ CollectionType.List => new ListGenericObjects<T>(),
CollectionType.Massive => new MassiveGenericObjects<T>(), _ => null
CollectionType.List => new ListGenericObjects<T>(), };
_ => null, }
};
}
} }

View File

@ -0,0 +1,33 @@
namespace ProjectAccordionBus.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningBusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -0,0 +1,38 @@
namespace ProjectAccordionBus.Drawnings;
/// <summary>
/// Сравнение по типу, скорости и весу
/// </summary>
public class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -0,0 +1,80 @@
using ProjectAccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAccordionBus.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return false;
}
if (y == null || y.EntityBus == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningAccordionBus && y is DrawningAccordionBus)
{
// TODO доделать логику сравнения дополнительных параметров
EntityAccordionBus _x = (EntityAccordionBus)x.EntityBus;
EntityAccordionBus _y = (EntityAccordionBus)y.EntityBus;
if (_x.Compartment != _y.Compartment)
{
if (_x.Entrance != _y.Entrance)
{
return false;
}
if (_x.Windows != _y.Windows)
{
return false;
}
return false;
}
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -12,7 +12,10 @@ public class EntityAccordionBus : EntityBus
{ {
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color; public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
public bool Compartment { get; private set; } public bool Compartment { get; private set; }

View File

@ -14,8 +14,10 @@ public class EntityBus
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public void SetBodyColor(Color color) => BodyColor = color; public void SetBodyColor(Color color)
{
BodyColor = color;
}
public double Step => Speed * 50 / Weight; public double Step => Speed * 50 / Weight;
/// <summary> /// <summary>

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirbus.Exceptions;
/// <summary>
/// Класс, описывающий ошибку наличия такого же объекта в коллекции
/// </summary>
[Serializable]
internal class ObjectNotUniqueException : ApplicationException
{
public ObjectNotUniqueException(int i) : base("В коллекции есть такой же элемент на позиции: " + i) { }
public ObjectNotUniqueException() : base() { }
public ObjectNotUniqueException(string message) : base(message) { }
public ObjectNotUniqueException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotUniqueException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -30,6 +30,8 @@
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonDeleteBus = new Button(); buttonDeleteBus = new Button();
maskedTextBox = new MaskedTextBox(); maskedTextBox = new MaskedTextBox();
buttonRefresh = new Button(); buttonRefresh = new Button();
@ -73,6 +75,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonDeleteBus); panelCompanyTools.Controls.Add(buttonDeleteBus);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -80,15 +84,37 @@
panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 317); panelCompanyTools.Location = new Point(3, 304);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(169, 191); panelCompanyTools.Size = new Size(169, 204);
panelCompanyTools.TabIndex = 10; panelCompanyTools.TabIndex = 10;
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(6, 180);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(160, 21);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(6, 157);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(160, 21);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonDeleteBus // buttonDeleteBus
// //
buttonDeleteBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonDeleteBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDeleteBus.Location = new Point(6, 109); buttonDeleteBus.Location = new Point(6, 72);
buttonDeleteBus.Name = "buttonDeleteBus"; buttonDeleteBus.Name = "buttonDeleteBus";
buttonDeleteBus.Size = new Size(160, 23); buttonDeleteBus.Size = new Size(160, 23);
buttonDeleteBus.TabIndex = 5; buttonDeleteBus.TabIndex = 5;
@ -99,18 +125,17 @@
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(6, 80); maskedTextBox.Location = new Point(6, 43);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(160, 23); maskedTextBox.Size = new Size(160, 23);
maskedTextBox.TabIndex = 5; maskedTextBox.TabIndex = 5;
maskedTextBox.ValidatingType = typeof(int); maskedTextBox.ValidatingType = typeof(int);
maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 167); buttonRefresh.Location = new Point(6, 130);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(160, 21); buttonRefresh.Size = new Size(160, 21);
buttonRefresh.TabIndex = 7; buttonRefresh.TabIndex = 7;
@ -121,7 +146,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 138); buttonGoToCheck.Location = new Point(6, 101);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(160, 23); buttonGoToCheck.Size = new Size(160, 23);
buttonGoToCheck.TabIndex = 6; buttonGoToCheck.TabIndex = 6;
@ -132,7 +157,7 @@
// buttonAddBus // buttonAddBus
// //
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBus.Location = new Point(6, 17); buttonAddBus.Location = new Point(6, 0);
buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(160, 37); buttonAddBus.Size = new Size(160, 37);
buttonAddBus.TabIndex = 2; buttonAddBus.TabIndex = 2;
@ -154,7 +179,7 @@
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19); panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(169, 291); panelStorage.Size = new Size(169, 282);
panelStorage.TabIndex = 8; panelStorage.TabIndex = 8;
// //
// buttonCollectionDel // buttonCollectionDel
@ -178,7 +203,7 @@
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(3, 81); buttonCollectionAdd.Location = new Point(6, 81);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(163, 23); buttonCollectionAdd.Size = new Size(163, 23);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 4;
@ -236,7 +261,6 @@
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(160, 23); comboBoxSelectorCompany.Size = new Size(160, 23);
comboBoxSelectorCompany.TabIndex = 1; comboBoxSelectorCompany.TabIndex = 1;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
// //
// labelCollectionName // labelCollectionName
// //
@ -246,7 +270,6 @@
labelCollectionName.Size = new Size(122, 15); labelCollectionName.Size = new Size(122, 15);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции"; labelCollectionName.Text = "Название коллекции";
labelCollectionName.Click += labelCollectionName_Click;
// //
// pictureBox // pictureBox
// //
@ -347,5 +370,9 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button button2;
private Button button1;
private Button buttonSortByType;
private Button buttonSortByColor;
} }
} }

View File

@ -2,15 +2,7 @@
using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.CollectionGenericObjects;
using ProjectAccordionBus.Drawnings; using ProjectAccordionBus.Drawnings;
using ProjectAccordionBus.Exceptions; using ProjectAccordionBus.Exceptions;
using System; using ProjectAirbus.Exceptions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectAccordionBus; namespace ProjectAccordionBus;
@ -52,61 +44,6 @@ public partial class FormBusCollection : Form
form.AddEvent(SetBus); form.AddEvent(SetBus);
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создания объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningBus drawningBus;
switch (type)
{
case nameof(DrawningBus):
drawningBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningAccordionBus):
drawningBus = new DrawningAccordionBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningBus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Выбор цвета
/// </summary>
/// <param name="random"></param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
private void buttonAddBus_Click(object sender, EventArgs e) private void buttonAddBus_Click(object sender, EventArgs e)
{ {
FormBusConfig form = new(); FormBusConfig form = new();
@ -122,18 +59,26 @@ public partial class FormBusCollection : Form
{ {
return; return;
} }
if (_company + bus != -1) if (_company + bus != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: {0}", bus.GetDataForSave()); _logger.LogInformation("Добавлен объект: " + bus.GetDataForSave());
} }
}
catch (ObjectNotFoundException ex)
{
} }
catch (CollectionOverflowException ex) catch (CollectionOverflowException ex)
{ {
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}"); _logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotUniqueException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -215,43 +160,33 @@ public partial class FormBusCollection : Form
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void labelCollectionName_Click(object sender, EventArgs e)
{
}
private void buttonCollectionAdd_Click(object sender, EventArgs e) private void buttonCollectionAdd_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return; return;
} }
CollectionType collectionType = CollectionType.None; try
if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
} }
else if (radioButtonList.Checked) catch (Exception ex)
{ {
collectionType = CollectionType.List; _logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RefreshListBoxItems();
} }
private void RefreshListBoxItems() private void RefreshListBoxItems()
@ -259,7 +194,7 @@ public partial class FormBusCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -270,20 +205,31 @@ public partial class FormBusCollection : Form
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {name}"); if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
RefreshListBoxItems(); {
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
@ -349,4 +295,25 @@ public partial class FormBusCollection : Form
} }
} }
} }
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
} }