7 Commits

Author SHA1 Message Date
e6f0b327af Лаб 8 2024-06-14 08:58:30 +04:00
3a938f6349 , 2024-06-14 08:14:29 +04:00
75c7be6da3 Исправления 2024-06-12 19:58:09 +04:00
f58ea26eb5 lab 7/0 2024-06-12 17:36:43 +04:00
8322c1fcaf Лаб 7 2024-06-12 15:15:23 +04:00
e44a184f2e Lab 6 2024-05-22 23:13:09 +04:00
ef133ccb2c Лаба 6 правки 2024-05-22 23:03:52 +04:00
25 changed files with 1091 additions and 116 deletions

View File

@@ -28,7 +28,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместитьв окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight)) - 1;
/// <summary>
/// Конструктор
/// </summary>
@@ -41,7 +41,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
@@ -51,7 +51,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, Drawningplane plane)
{
return company._collection.Insert(plane);
return company._collection.Insert(plane, new DrawningPlaneEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@@ -81,11 +81,16 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
Drawningplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
Drawningplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
}
@@ -98,4 +103,10 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<Drawningplane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAiroplane.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

@@ -1,4 +1,5 @@
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
@@ -13,20 +14,25 @@ where T : class
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? compaper = 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?>? compaper = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@@ -39,4 +45,15 @@ where T : class
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,4 +1,7 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Exceptions;
namespace ProjectAiroplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
@@ -11,7 +14,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
private int _maxCount;
public int Count => _collection.Count;//свойство
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@@ -19,37 +39,63 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
_collection = new();
}
public T? Get(int position)
public T Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
return _collection[position];// индексатор
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? compaper = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
_collection.Add(obj);//метод
if (compaper != null)
{
if (_collection.Contains(obj, compaper))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException();
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? compaper = null)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj);//метод
if (compaper != null)
{
if (_collection.Contains(obj, compaper))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position);//метод
return obj;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T temp = _collection[position];
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,7 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using ProjectAiroplane.Exceptions;
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -12,8 +15,14 @@ where T : class
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -29,6 +38,9 @@ where T : class
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -36,15 +48,27 @@ where T : class
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{ return null; }
{ throw new PositionOutOfCollectionException(position); }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? compaper = null)
{
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<Drawningplane>).Equals(obj as Drawningplane, item as Drawningplane))
throw new ObjectIsEqualException();
}
}
// TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
@@ -57,17 +81,28 @@ where T : class
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? compaper = null)
{
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<Drawningplane>).Equals(obj as Drawningplane, item as Drawningplane))
throw new ObjectIsEqualException();
}
}
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -93,7 +128,7 @@ where T : class
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
@@ -101,10 +136,26 @@ where T : class
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ return null; }
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -34,11 +34,12 @@ public class PlaneSharingService : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection.Get(i) != null)
try
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 2);
}
catch (Exception) { }
if (curWidth > 0)
curWidth--;
else

View File

@@ -1,25 +1,29 @@
namespace ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using ProjectAiroplane.Exceptions;
using System.Text;
namespace ProjectAiroplane.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : Drawningplane
{
/// <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>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@@ -31,12 +35,13 @@ public class StorageCollection<T>
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return;
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
@@ -44,9 +49,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
@@ -58,10 +63,175 @@ public class StorageCollection<T>
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count < 1)
{
throw new InvalidDataException("В хранилище отсутсвуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningplane() is T airoplane)//////////////////////////////////////////////////////////////////CreateDrawningplane()
{
try
{
if (collection.Insert(airoplane) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -15,15 +15,20 @@ public class DrawningAiroplane : Drawningplane
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="toplivbak">Признак наличия бака</param>
/// <param name="radar">Признак наличия радара</param>
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170,85)
public DrawningAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(170, 85)
{
Entityplane = new EntityAiroplane(speed, weight, bodyColor, additionalColor, toplivbak, radar);
}
public DrawningAiroplane(EntityAiroplane airoplane) : base(170, 85)
{
Entityplane = new EntityAiroplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor, airoplane.AdditionalColor, airoplane.Toplivbak, airoplane.Radar);
}
public override void DrawTransport(Graphics g)
{
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane|| !_startPosX.HasValue || !_startPosY.HasValue)
if (Entityplane == null || Entityplane is not EntityAiroplane airoplane || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
@@ -33,9 +38,9 @@ public class DrawningAiroplane : Drawningplane
Brush additionalBrush = new SolidBrush(airoplane.AdditionalColor);
if (airoplane.Toplivbak)
{
g.FillRectangle(additionalBrush, _startPosX.Value + 65,_startPosY.Value + 20, 30, 15);
g.FillRectangle(additionalBrush, _startPosX.Value + 65, _startPosY.Value + 20, 30, 15);
}
//Радар
if (airoplane.Radar)
{

View File

@@ -0,0 +1,72 @@
namespace ProjectAiroplane.Drawnings;
using ProjectAiroplane.Entities;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningPlaneEqutables : IEqualityComparer<Drawningplane?>
{
public bool Equals(Drawningplane? x, Drawningplane? y)
{
if (x == null || x.Entityplane == null)
{
return false;
}
if (y == null || y.Entityplane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.Entityplane.Speed != y.Entityplane.Speed)
{
return false;
}
if (x.Entityplane.Weight != y.Entityplane.Weight)
{
return false;
}
if (x.Entityplane.BodyColor != y.Entityplane.BodyColor)
{
return false;
}
if (x is EntityAiroplane && y is EntityAiroplane)
{
// TODO доделать логику сравнения дополнительных параметров
EntityAiroplane _x = (EntityAiroplane)x.Entityplane ;
EntityAiroplane _y = (EntityAiroplane)x.Entityplane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Toplivbak != _y.Toplivbak)
{
return false;
}
if (_x.Radar != _y.Radar)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] Drawningplane? obj)
{
return obj.GetHashCode();
}
}

View File

@@ -73,6 +73,12 @@ public class Drawningplane
Entityplane = new Entityplane(speed, weight, bodyColor);
}
public Drawningplane(Entityplane airoplane) : this()
{
Entityplane = new Entityplane(airoplane.Speed, airoplane.Weight, airoplane.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@@ -0,0 +1,50 @@
using ProjectAiroplane.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAiroplane.Drawnings;
public static class ExtentionDrawningPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static Drawningplane? CreateDrawningplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
Entityplane? airoplane = EntityAiroplane.CreateEntityAiroplane(strs);
if (airoplane != null)
{
return new DrawningAiroplane((EntityAiroplane)airoplane);
}
airoplane = Entityplane.CreateEntityplane(strs);
if (airoplane != null)
{
return new Drawningplane(airoplane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningplane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this Drawningplane drawningplane)
{
string[]? array = drawningplane?.Entityplane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

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

View File

@@ -1,4 +1,6 @@
namespace ProjectAiroplane.Entities;
using System.Net.Sockets;
namespace ProjectAiroplane.Entities;
public class EntityAiroplane : Entityplane
{
/// <summary>
@@ -13,7 +15,7 @@ public class EntityAiroplane : Entityplane
/// Признак (опция) наличия радара
/// </summary>
public bool Radar { get; private set; }
/// <summary>
/// Инициализация полей класса
/// </summary>
@@ -23,7 +25,7 @@ public class EntityAiroplane : Entityplane
/// <param name="additionalColor"></Дополнительный цвет>
/// <param name="toplivbak"></ Признак наличия бака>
/// <param name="radar"></Признак (опция) наличия радара>
public EntityAiroplane(int speed, double weight, Color bodyColor, Color additionalColor, bool toplivbak, bool radar) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
@@ -39,6 +41,28 @@ public class EntityAiroplane : Entityplane
{
AdditionalColor = color;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAiroplane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Toplivbak.ToString(), Radar.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAiroplane? CreateEntityAiroplane(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAiroplane))
{
return null;
}
return new EntityAiroplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
@@ -52,5 +53,27 @@ public class Entityplane
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(Entityplane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static Entityplane? CreateEntityplane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(Entityplane))
{
return null;
}
return new Entityplane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

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

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAiroplane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится одинаковый элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ProjectAiroplane.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -30,6 +30,7 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddPlane = new Button();
buttonGoToCheck = new Button();
buttonDelPlane = new Button();
maskedTextBox1 = new MaskedTextBox();
@@ -45,11 +46,19 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
buttonAddPlane = new Button();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,29 +68,41 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Location = new Point(859, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(277, 680);
groupBoxTools.Size = new Size(277, 689);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddPlane);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonDelPlane);
panelCompanyTools.Controls.Add(maskedTextBox1);
panelCompanyTools.Controls.Add(buttonReFresh);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(9, 380);
panelCompanyTools.Location = new Point(9, 364);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(268, 322);
panelCompanyTools.Size = new Size(268, 338);
panelCompanyTools.TabIndex = 9;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(4, 3);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(7, 189);
buttonGoToCheck.Location = new Point(4, 131);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(254, 42);
buttonGoToCheck.TabIndex = 5;
@@ -91,7 +112,7 @@
//
// buttonDelPlane
//
buttonDelPlane.Location = new Point(7, 140);
buttonDelPlane.Location = new Point(4, 82);
buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(254, 43);
buttonDelPlane.TabIndex = 4;
@@ -101,7 +122,7 @@
//
// maskedTextBox1
//
maskedTextBox1.Location = new Point(7, 107);
maskedTextBox1.Location = new Point(6, 49);
maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(252, 27);
@@ -110,7 +131,7 @@
//
// buttonReFresh
//
buttonReFresh.Location = new Point(7, 237);
buttonReFresh.Location = new Point(4, 179);
buttonReFresh.Name = "buttonReFresh";
buttonReFresh.Size = new Size(252, 40);
buttonReFresh.TabIndex = 6;
@@ -120,7 +141,7 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(13, 346);
buttonCreateCompany.Location = new Point(13, 330);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(252, 28);
buttonCreateCompany.TabIndex = 8;
@@ -140,7 +161,7 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(271, 283);
panelStorage.Size = new Size(271, 270);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
@@ -216,7 +237,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(13, 312);
comboBoxSelectorCompany.Location = new Point(13, 296);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(252, 28);
comboBoxSelectorCompany.TabIndex = 0;
@@ -225,29 +246,82 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(859, 680);
pictureBox.Size = new Size(859, 689);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// buttonAddPlane
// menuStrip1
//
buttonAddPlane.Location = new Point(7, 14);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(252, 40);
buttonAddPlane.TabIndex = 1;
buttonAddPlane.Text = "Добавление самолёта";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += ButtonAddPlane_Click;
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1136, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click_1;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click_1;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(4, 225);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(254, 42);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировать по Типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(4, 273);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(252, 40);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировать по Цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1136, 680);
ClientSize = new Size(1136, 717);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormPlaneCollection";
Text = "Коллекция самолётов";
groupBoxTools.ResumeLayout(false);
@@ -256,7 +330,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -279,5 +356,13 @@
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private Button buttonAddPlane;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@@ -1,5 +1,7 @@
using ProjectAiroplane.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAiroplane.CollectionGenericObjects;
using ProjectAiroplane.Drawnings;
using ProjectAiroplane.Exceptions;
using System.Windows.Forms;
namespace ProjectAiroplane;
@@ -14,15 +16,20 @@ public partial class FormPlaneCollection : Form
/// <summary>
/// Хранилище коллеций
/// </summary>
///
private readonly StorageCollection<Drawningplane> _storageCollection;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Выбор компании
@@ -39,35 +46,47 @@ public partial class FormPlaneCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddPlane_Click(object sender, EventArgs e)//вопрос 2 ...........................................................
private void ButtonAddPlane_Click(object sender, EventArgs e)
{
FormPlanConfig form = new();
// TODO передать метод
form.Show();
form.AddEvent(SetPlane); //////////////////////////////
form.AddEvent(SetPlane);
}
/// <summary>
/// Добавление самолёта в коллекцию
/// </summary>
/// <param name="excavator"></param>
/// <param name="plane"></param>
private void SetPlane(Drawningplane? plane)
{
if (_company == null || plane == null)
try
{
return;
if (_company == null || plane == null)
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
}
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -87,15 +106,23 @@ public partial class FormPlaneCollection : Form
{
return;
}
int pos = Convert.ToInt32(maskedTextBox1.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);//отсюда идут в ткс2
}
}
/// <summary>
@@ -152,21 +179,30 @@ public partial class FormPlaneCollection : Form
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
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);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
@@ -185,12 +221,20 @@ public partial class FormPlaneCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
@@ -201,7 +245,7 @@ public partial class FormPlaneCollection : 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);
@@ -238,4 +282,68 @@ public partial class FormPlaneCollection : Form
RerfreshListBoxItems();
}
private void saveToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void loadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
ComparePlane(new PlaneCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
ComparePlane(new PlaneCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void ComparePlane(IComparer<Drawningplane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>

View File

@@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectAiroplane
{
internal static class Program
@@ -11,7 +17,31 @@ namespace ProjectAiroplane
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormPlaneCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider servicesProvider = services.BuildServiceProvider();
Application.Run(servicesProvider.GetRequiredService<FormPlaneCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +35,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}