This commit is contained in:
rakhaliullov 2024-05-16 01:57:54 +03:00
parent 8efbfd9691
commit 74d29aca6b
21 changed files with 606 additions and 137 deletions

View File

@ -56,11 +56,12 @@ public abstract class AbstractCompany
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса
/// </summary> /// </summary>
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="сruiser">Добавляемый объект</param> /// <param name="aircraft">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAircraft aircraft) public static int operator +(AbstractCompany company, DrawningAircraft aircraft)
{ {
return company._collection.Insert(aircraft); return company._collection?.Insert(aircraft, new DrawningAircraftEquitables()) ??
throw new DrawningEquitablesException();
} }
/// <summary> /// <summary>
@ -83,7 +84,11 @@ public abstract class AbstractCompany
Random rnd = new(); Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount)); return _collection?.Get(rnd.Next(GetMaxCount));
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAircraft?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод всей коллекции /// Вывод всей коллекции
/// </summary> /// </summary>

View File

@ -0,0 +1,84 @@
using Stormtrooper.CollectionGenericObjects;
namespace Stormtrooper;
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 bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -5,7 +5,7 @@
/// </summary> /// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam> /// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Количество объектов в коллекции /// Количество объектов в коллекции
@ -22,7 +22,7 @@ where T : class
/// </summary> /// </summary>
/// <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<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@ -30,14 +30,14 @@ where T : class
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</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>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns> /// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position); T Remove(int position);
/// <summary> /// <summary>
/// Получение объекта по позиции /// Получение объекта по позиции
@ -56,4 +56,11 @@ where T : class
/// </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

@ -55,17 +55,39 @@ where T : class
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 (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
public int Insert(T obj, int position)
{ {
if (Count == _maxCount) throw new CollectionOverflowException(Count); if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@ -85,5 +107,9 @@ public IEnumerable<T?> GetItems()
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -61,8 +61,20 @@ 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)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
// вставка в свободное место набора // вставка в свободное место набора
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
@ -76,11 +88,22 @@ 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 < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
if (_collection[position] != null) if (_collection[position] != null)
{ {
bool pushed = false; bool pushed = false;
@ -113,11 +136,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
// вставка
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
// проверка позиции // проверка позиции
@ -129,6 +152,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null; _collection[position] = null;
return temp; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < _collection.Length; ++i) for (int i = 0; i < _collection.Length; ++i)
@ -136,4 +160,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> value = new List<T?>(_collection);
value.Sort(comparer);
value.CopyTo(_collection, 0);
}
} }

View File

@ -19,11 +19,11 @@ where T : DrawningAircraft
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages; private 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>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -45,92 +45,82 @@ where T : DrawningAircraft
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="collectionInfo">тип коллекции</param>
/// <param name="collectionType">тип коллекции</param> public void AddCollection(CollectionInfo collectionInfo)
public void AddCollection(string name, CollectionType collectionType)
{ {
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo)) throw new CollectionAlreadyExistsException(collectionInfo);
return; if (collectionInfo.CollectionType == CollectionType.None)
switch (collectionType) throw new CollectionTypeException("Пустой тип коллекции");
{ if (collectionInfo.CollectionType == CollectionType.Massive)
case CollectionType.List: _storages[collectionInfo] = new MassiveGenericObjects<T>();
_storages.Add(name, new ListGenericObjects<T>()); else if (collectionInfo.CollectionType == CollectionType.List)
break; _storages[collectionInfo] = new ListGenericObjects<T>();
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
break;
default:
break;
}
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="collectionInfo">тип коллекции</param>
public void DelCollection(string name) public void DelCollection(CollectionInfo collectionInfo)
{ {
// TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(collectionInfo))
if (_storages.ContainsKey(name)) { _storages.Remove(name); } _storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="collectionInfo"></param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{ {
get get
{ {
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value)) if (_storages.ContainsKey(collectionInfo))
return value; return _storages[collectionInfo];
return null; return null;
} }
} }
/// <summary> /// <summary>
/// Сохранение информации по самолетам в хранилище в файл /// Сохранение информации по самолетам в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename"></param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <exception cref="EmptyFileExeption"></exception>
public void SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new Exception("В хранилище отсутствуют коллекции для сохранения"); throw new EmptyFileExeption();
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using FileStream fs = new(filename, FileMode.Create); using (StreamWriter writer = new StreamWriter(filename))
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
streamWriter.Write(Environment.NewLine); writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
streamWriter.Write(value.Key); sb.Append(value.Key);
streamWriter.Write(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType); sb.Append(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -139,70 +129,80 @@ where T : DrawningAircraft
continue; continue;
} }
sb.Append(data);
sb.Append(_separatorItems);
}
streamWriter.Write(data); writer.Write(sb);
streamWriter.Write(_separatorItems);
} }
} }
} }
/// <summary> /// <summary>
/// Загрузка информации по кораблям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не существует"); throw new FileNotFoundException(filename);
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string? str; string str = fs.ReadLine();
str = sr.ReadLine(); if (string.IsNullOrEmpty(str))
if (str != _collectionKey.ToString()) {
throw new FormatException("В файле неверные данные"); throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
throw new FileFormatException(filename);
}
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) string strs = "";
while ((strs = fs.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]); CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new CollectionInfoException("Не удалось определить информацию коллекции:" + record[0]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningAircraft() is T aircraft) if (elem?.CreateDrawningAircraft() is T ship)
{ {
try try
{ {
if (collection.Insert(aircraft) == -1) collection.Insert(ship);
}
catch (Exception ex)
{ {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); throw new FileFormatException(filename, ex);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
} }
} }
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{ {
return collectionType switch return collectionType switch
{ {

View File

@ -0,0 +1,37 @@
using Stormtrooper.Drawnings;
namespace Stormtrooper;
public class DrawningAircraftCompareByColor : IComparer<DrawningAircraft?>
{
public int Compare(DrawningAircraft? x, DrawningAircraft? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityAircraft == null)
{
return 1;
}
if (y == null || y.EntityAircraft == null)
{
return -1;
}
if (ToHex(x.EntityAircraft.BodyColor) != ToHex(y.EntityAircraft.BodyColor))
{
return String.Compare(ToHex(x.EntityAircraft.BodyColor), ToHex(y.EntityAircraft.BodyColor),
StringComparison.Ordinal);
}
var speedCompare = x.EntityAircraft.Speed.CompareTo(y. EntityAircraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAircraft.Weight.CompareTo(y.EntityAircraft.Weight);
}
private static String ToHex(Color c)
=> $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

View File

@ -0,0 +1,33 @@
using Stormtrooper.Drawnings;
namespace Stormtrooper;
public class DrawningAircraftCompareByType : IComparer<DrawningAircraft?>
{
public int Compare(DrawningAircraft? x, DrawningAircraft? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityAircraft == null)
{
return 1;
}
if (y == null || y.EntityAircraft == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityAircraft.Speed.CompareTo(y.EntityAircraft.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityAircraft.Weight.CompareTo(y.EntityAircraft.Weight);
}
}

View File

@ -0,0 +1,59 @@
using Stormtrooper.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Stormtrooper.Drawnings;
public class DrawningAircraftEquitables : IEqualityComparer<DrawningAircraft?>
{
public bool Equals(DrawningAircraft? x, DrawningAircraft? y)
{
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityAircraft != null && y.EntityAircraft != null && x.EntityAircraft.Speed != y.EntityAircraft.Speed)
{
return false;
}
if (x.EntityAircraft.Weight != y.EntityAircraft.Weight)
{
return false;
}
if (x.EntityAircraft.BodyColor != y.EntityAircraft.BodyColor)
{
return false;
}
if (x is DrawningStormtrooper && y is DrawningStormtrooper)
{
if (((EntityStormtrooper)x.EntityAircraft).AdditionalColor !=
((EntityStormtrooper)y.EntityAircraft).AdditionalColor)
{
return false;
}
if (((EntityStormtrooper)x.EntityAircraft).Rocket!=
((EntityStormtrooper)y.EntityAircraft).Rocket)
{
return false;
}
if (((EntityStormtrooper)x.EntityAircraft).Bomb!=
((EntityStormtrooper)y.EntityAircraft).Bomb)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAircraft obj)
{
return obj.GetHashCode();
}
}

View File

@ -55,6 +55,7 @@ public class EntityAircraft
return null; return null;
} }
return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); return new EntityAircraft(Convert.ToInt32(strs[1]),
Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
} }
} }

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base($"Коллекция {collectionInfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class CollectionInfoException : Exception
{
public CollectionInfoException() : base() { }
public CollectionInfoException(string message) : base(message) { }
public CollectionInfoException(string message, Exception exception) :
base(message, exception) { }
protected CollectionInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} не удволетворяет уникальности") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception) { }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class CollectionTypeException : Exception
{
public CollectionTypeException() : base() { }
public CollectionTypeException(string message) : base(message) { }
public CollectionTypeException(string message, Exception exception) :
base(message, exception) { }
protected CollectionTypeException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class DrawningEquitablesException : Exception
{
public DrawningEquitablesException() : base("Объекты прорисовки одинаковые") { }
public DrawningEquitablesException(string message) : base(message) { }
public DrawningEquitablesException(string message, Exception exception) :
base(message, exception) { }
protected DrawningEquitablesException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception) { }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,13 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class FileFormatException : Exception
{
public FileFormatException() : base() { }
public FileFormatException(string message) : base(message) { }
public FileFormatException(string name, Exception exception) :
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { }
protected FileFormatException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
namespace Stormtrooper;
public class FileNotFoundException : Exception
{
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
public FileNotFoundException() : base() { }
public FileNotFoundException(string name, string message) : base(message) { }
public FileNotFoundException(string name, string message, Exception exception) :
base(message, exception) { }
protected FileNotFoundException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

View File

@ -30,7 +30,9 @@
{ {
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonAddAiracft = new Button(); buttonAddAiracft = new Button();
buttonSortByType = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox(); maskedTextBox = new MaskedTextBox();
buttonGoToCheck = new Button(); buttonGoToCheck = new Button();
@ -52,11 +54,13 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
pictureBox1 = new PictureBox();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -68,7 +72,7 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(959, 28); groupBoxTools.Location = new Point(959, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(264, 660); groupBoxTools.Size = new Size(264, 714);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Tag = ""; groupBoxTools.Tag = "";
@ -76,7 +80,9 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddAiracft); panelCompanyTools.Controls.Add(buttonAddAiracft);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
@ -84,9 +90,20 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 391); panelCompanyTools.Location = new Point(3, 391);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(258, 262); panelCompanyTools.Size = new Size(258, 323);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 272);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(252, 41);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonAddAiracft // buttonAddAiracft
// //
buttonAddAiracft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddAiracft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -98,10 +115,21 @@
buttonAddAiracft.UseVisualStyleBackColor = true; buttonAddAiracft.UseVisualStyleBackColor = true;
buttonAddAiracft.Click += ButtonAddAircraft_Click; buttonAddAiracft.Click += ButtonAddAircraft_Click;
// //
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 225);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(252, 41);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(0, 207); buttonRefresh.Location = new Point(3, 178);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(252, 41); buttonRefresh.Size = new Size(252, 41);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -112,7 +140,7 @@
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(0, 80); maskedTextBox.Location = new Point(3, 51);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(252, 27); maskedTextBox.Size = new Size(252, 27);
@ -122,7 +150,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(0, 160); buttonGoToCheck.Location = new Point(3, 131);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(252, 41); buttonGoToCheck.Size = new Size(252, 41);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -133,7 +161,7 @@
// buttonRemoveAircraft // buttonRemoveAircraft
// //
buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAircraft.Location = new Point(0, 113); buttonRemoveAircraft.Location = new Point(3, 84);
buttonRemoveAircraft.Name = "buttonRemoveAircraft"; buttonRemoveAircraft.Name = "buttonRemoveAircraft";
buttonRemoveAircraft.Size = new Size(252, 41); buttonRemoveAircraft.Size = new Size(252, 41);
buttonRemoveAircraft.TabIndex = 4; buttonRemoveAircraft.TabIndex = 4;
@ -250,7 +278,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(959, 660); pictureBox.Size = new Size(959, 714);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -295,11 +323,21 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// pictureBox1
//
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.Location = new Point(0, 28);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(959, 714);
pictureBox1.TabIndex = 7;
pictureBox1.TabStop = false;
//
// FormAircraftCollection // FormAircraftCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1223, 688); ClientSize = new Size(1223, 742);
Controls.Add(pictureBox1);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -314,6 +352,7 @@
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false); menuStrip.ResumeLayout(false);
menuStrip.PerformLayout(); menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@ -344,5 +383,8 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
private PictureBox pictureBox1;
} }
} }

View File

@ -44,12 +44,18 @@ public partial class FormAircraftCollection : Form
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
panelCompanyTools.Enabled = false; switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AircraftHangarService(pictureBox1.Width, pictureBox1.Height,
new MassiveGenericObjects<DrawningAircraft>());
break;
}
} }
/// <summary> /// <summary>
/// Добавление автомобиля /// Добавление самолета
/// </summary> /// /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddAircraft_Click(object sender, EventArgs e) private void ButtonAddAircraft_Click(object sender, EventArgs e)
@ -61,7 +67,7 @@ public partial class FormAircraftCollection : Form
} }
/// <summary> /// <summary>
/// Добавление автомобиля в коллекцию /// Добавление самолета в коллекцию
/// </summary> /// </summary>
/// <param name="aircraft"></param> /// <param name="aircraft"></param>
private void SetAircraft(DrawningAircraft aircraft) private void SetAircraft(DrawningAircraft aircraft)
@ -75,7 +81,7 @@ public partial class FormAircraftCollection : Form
var res = _company + aircraft; var res = _company + aircraft;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}"); _logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show(); pictureBox1.Image = _company.Show();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -109,7 +115,7 @@ public partial class FormAircraftCollection : Form
var res = _company - pos; var res = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}"); _logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show(); pictureBox1.Image = _company.Show();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -155,7 +161,7 @@ public partial class FormAircraftCollection : Form
return; return;
} }
pictureBox.Image = _company.Show(); pictureBox1.Image = _company.Show();
} }
/// <summary> /// <summary>
@ -184,7 +190,7 @@ public partial class FormAircraftCollection : Form
try try
{ {
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "2"));
_logger.LogInformation("Добавление коллекции"); _logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -193,7 +199,6 @@ public partial class FormAircraftCollection : Form
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message); _logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
@ -215,11 +220,13 @@ public partial class FormAircraftCollection : Form
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена"); _logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// Создание компании /// Создание компании
/// </summary> /// </summary>
@ -234,7 +241,9 @@ public partial class FormAircraftCollection : Form
} }
ICollectionGenericObjects<DrawningAircraft>? collection = ICollectionGenericObjects<DrawningAircraft>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; _storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@ -244,7 +253,7 @@ public partial class FormAircraftCollection : Form
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection); _company = new AircraftHangarService(pictureBox1.Width, pictureBox1.Height, collection);
_logger.LogInformation("Компания создана"); _logger.LogInformation("Компания создана");
break; break;
} }
@ -260,10 +269,10 @@ public partial class FormAircraftCollection : 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]; CollectionInfo? col = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName)) if (!col!.IsEmpty())
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(col);
} }
} }
} }
@ -314,4 +323,39 @@ public partial class FormAircraftCollection : Form
} }
} }
} }
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareAircrafts(new DrawningAircraftCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareAircrafts(new DrawningAircraftCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareAircrafts(IComparer<DrawningAircraft?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox1.Image = _company.Show();
}
} }

View File

@ -47,16 +47,9 @@ public partial class FormAircraftConfig : Form
/// </summary> /// </summary>
/// <param name="aircraftDelegate"></param> /// <param name="aircraftDelegate"></param>
public void AddEvent(Action<DrawningAircraft> aircraftDelegate) public void AddEvent(Action<DrawningAircraft> aircraftDelegate)
{
if (AircraftDelegate != null)
{
AircraftDelegate = aircraftDelegate;
}
else
{ {
AircraftDelegate += aircraftDelegate; AircraftDelegate += aircraftDelegate;
} }
}
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта