5 Commits
Lab05 ... Lab08

25 changed files with 1116 additions and 123 deletions

View File

@@ -48,7 +48,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns> /// <returns></returns>
public static bool operator +(AbstractCompany company, DrawningAircraft aircraft) public static bool operator +(AbstractCompany company, DrawningAircraft aircraft)
{ {
return company._collection?.Insert(aircraft) ?? false; return company._collection?.Insert(aircraft, new DrawningAircraftEqutables()) ?? false;
} }
/// <summary> /// <summary>
@@ -102,6 +102,14 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningAircraft?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackGround(Graphics g); protected abstract void DrawBackGround(Graphics g);
protected abstract void SetObjectPosition(Graphics g); protected abstract void SetObjectPosition(Graphics g);
} }

View File

@@ -16,7 +16,6 @@ public class AircraftSharingService : AbstractCompany
private int? _startPosY; private int? _startPosY;
private int? ObjPositionX; private int? ObjPositionX;
private int? ObjPositionY; private int? ObjPositionY;
private void DrawPlace(Graphics g) private void DrawPlace(Graphics g)
{ {
Pen pen = new(Color.Black); Pen pen = new(Color.Black);

View File

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

View File

@@ -23,14 +23,14 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка прошла не успешно</returns> /// <returns>true - вставка прошла успешно, false - вставка прошла не успешно</returns>
bool Insert(T obj); bool Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
@@ -38,7 +38,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла успешно, false - вставка прошла не успешно</returns> /// <returns>true - вставка прошла успешно, false - вставка прошла не успешно</returns>
bool Insert(T obj, int position); bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@@ -53,4 +53,21 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }

View File

@@ -1,9 +1,13 @@
using System; using ProectMilitaryAircraft.Draw;
using ProectMilitaryAircraft.Exceptions;
using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProectMilitaryAircraft.CollectionGenericObjects; namespace ProectMilitaryAircraft.CollectionGenericObjects;
@@ -11,8 +15,8 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects;
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
/// <typeparam name="T">Параметр : ограничение - ссылочный тип</typeparam> /// <typeparam name="T">Параметр : ограничение - ссылочный тип</typeparam>
public class ListgenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : DrawningAircraft
{ {
/// <summary> /// <summary>
/// Список объектов, которые храним /// Список объектов, которые храним
@@ -26,14 +30,25 @@ public class ListgenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List; public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public ListgenericObjects() public ListGenericObjects()
{ {
_collection = new(); _collection = new();
} }
@@ -41,29 +56,52 @@ public class ListgenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) return null; if (position < 0 || position >= Count)
{
return null;
}
if (position > _maxCount)
{
new CollectionOverflowException();
return null;
}
return _collection[position]; return _collection[position];
} }
public bool Insert(T obj) public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
if (Count != _maxCount) if (Count == _maxCount)
{ {
_collection.Add(obj); throw new CollectionOverflowException(Count);
return true;
} }
if (_collection.Contains(obj, comparer))
{
MessageBox.Show("Такой объект уже существует");
return false; return false;
} }
public bool Insert(T obj, int position) _collection.Add(obj);
{
if (position > 0 && position <= _maxCount && Count != _maxCount)
{
_collection.Insert(position, obj);
return true; return true;
} }
return false;
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position < 0 || position >= _maxCount)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection.Contains(obj, comparer))
{
throw new Exception("Такой объект уже существует в коллекции");
}
_collection.Insert(position, obj);
return true;
} }
public bool Remove(int position) public bool Remove(int position)
@@ -73,6 +111,23 @@ public class ListgenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position); _collection.RemoveAt(position);
return true; return true;
} }
if (!(position >= 0 && position < Count))
{
throw new ObjectNotFoundException(position);
}
return false; return false;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@@ -1,5 +1,9 @@
using System; using ProectMilitaryAircraft.Draw;
using ProectMilitaryAircraft.Exceptions;
using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -16,75 +20,102 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
/// <summary> /// <summary>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collections;
public int Count => _collection.Length; public int Count => _collections.Length;
public int SetMaxCount public int MaxCount {
get
{ {
return _collections.Length;
}
set set
{ {
if (value > 0) if (value > 0)
{ {
if (_collection.Length > 0) if (_collections.Length > 0)
{ {
Array.Resize(ref _collection, value); Array.Resize(ref _collections, value);
} }
else else
{ {
_collection = new T?[value]; _collections = new T?[value];
} }
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public MassiveGenericObjects() public MassiveGenericObjects()
{ {
_collection = Array.Empty<T?>(); _collections = Array.Empty<T?>();
} }
public T? Get(int position) public T? Get(int position)
{ {
if (_collection[position] != null) if (position < 0 || position >= _collections.Length)
{ {
return _collection[position]; throw new PositionOutOfCollectionException(position);
}
else
{
return null;
} }
return _collections[position];
} }
public bool Insert(T obj) public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
for (int i = 0; i < _collection.Length; i++) if (_collections.Contains(obj, comparer))
{ {
if (_collection[i] == null) MessageBox.Show("Объект уже существует");
return false;
}
for (int i = 0; i < _collections.Length; ++i)
{ {
_collection[i] = obj; if (_collections[i] == null)
{
_collections[i] = obj;
return true; return true;
} }
} }
return false; return false;
} }
public bool Insert(T obj, int position) public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
if (_collection[position] == null) if (_collections[position] == null)
{ {
_collection[position] = obj; _collections[position] = obj;
return true; return true;
} }
if (_collection[position] != null) if (position > Count)
{ {
for (int i = position; i < _collection.Length; i++) throw new CollectionOverflowException(Count);
}
if (!(position >= 0 && position <= Count))
{ {
if (_collection[i] == null) throw new Exception("Неверная позиция для вставки");
}
if (comparer != null)
{ {
_collection[i] = obj; if (_collections.Contains(obj, comparer))
{
MessageBox.Show("Объект уже существует");
return false;
}
}
if (_collections[position] != null)
{
for (int i = position; i < _collections.Length; i++)
{
if (_collections[i] == null)
{
_collections[i] = obj;
return true; return true;
} }
break; break;
@@ -92,9 +123,9 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
for (int i = position; i <= 0; i--) for (int i = position; i <= 0; i--)
{ {
if (_collection[i] == null) if (_collections[i] == null)
{ {
_collection[i] = obj; _collections[i] = obj;
return true; return true;
} }
break; break;
@@ -105,14 +136,36 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
public bool Remove(int position) public bool Remove(int position)
{ {
if (_collection[position] != null) if (_collections[position] != null)
{ {
_collection[position] = null; _collections[position] = null;
return true; return true;
} }
if (position >= 0 && position < Count)
{
throw new ObjectNotFoundException(position);
}
return false; return false;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collections.Length; ++i)
{
yield return _collections[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
;
if (_collections != null && _collections.Length > 0)
{
Array.Sort(_collections, comparer);
_collections = _collections.OrderBy(element => element == null).ToArray();
}
}
} }
} }

View File

@@ -1,4 +1,6 @@
using ProectMilitaryAircraft.MovementStrategy; using ProectMilitaryAircraft.Draw;
using ProectMilitaryAircraft.Exceptions;
using ProectMilitaryAircraft.MovementStrategy;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -8,53 +10,210 @@ using System.Threading.Tasks;
namespace ProectMilitaryAircraft.CollectionGenericObjects; namespace ProectMilitaryAircraft.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningAircraft
{ {
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<Collectioninfo, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList(); public List<Collectioninfo> Keys => _storages.Keys.ToList();
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<Collectioninfo, ICollectionGenericObjects<T>>();
} }
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
public void AddCollection (string name, CollectionType collectionType) public void AddCollection (string name, CollectionType collectionType)
{ {
if (name != null && !_storages.ContainsKey(name)) if (name != null && !_storages.ContainsKey(new Collectioninfo(name, collectionType, string.Empty)))
{ {
if (collectionType == CollectionType.Massive) if (collectionType == CollectionType.Massive)
{ {
_storages.Add(name, new MassiveGenericObjects<T>()); _storages.Add(new Collectioninfo(name, collectionType,
string.Empty), new MassiveGenericObjects<T>());
} }
if (collectionType == CollectionType.List) if (collectionType == CollectionType.List)
{ {
_storages.Add(name, new ListgenericObjects<T>()); _storages.Add(new Collectioninfo(name, collectionType,
string.Empty), new ListGenericObjects<T>());
} }
} }
} }
public void DelCollection (string name) public void DelCollection (string name, CollectionType collectionType)
{ {
if (!_storages.ContainsKey(name)) if (!_storages.ContainsKey(new Collectioninfo(name, collectionType, string.Empty)))
{ {
return; return;
} }
_storages.Remove(name); _storages.Remove(new Collectioninfo(name, collectionType, string.Empty));
} }
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[string name, CollectionType collectionType]
{ {
get get
{ {
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(new Collectioninfo(name, collectionType, string.Empty)))
{ {
return _storages[name]; return _storages[new Collectioninfo(name, collectionType, string.Empty)];
} }
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствует коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<Collectioninfo, ICollectionGenericObjects<T>> value in _storages)
{
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);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (!strs[0].Equals(_collectionKey))
{
throw new Exception("В файле неверные данные");
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.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("Не удалось определить тип коллекции:" + record[0]);
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningCar() is T car)
{
try
{
if (!collection.Insert(car))
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[2]);
}
}
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

@@ -37,12 +37,12 @@ public class DrawningAircraft
/// <summary> /// <summary>
/// Ширина прорисовки самолета /// Ширина прорисовки самолета
/// </summary> /// </summary>
private readonly int _drawningMilitaryAircraftWidth = 120; private readonly int _drawningAircraftWidth = 120;
/// <summary> /// <summary>
/// Высота прорисовки самолета /// Высота прорисовки самолета
/// </summary> /// </summary>
private readonly int _drawingMilitaryAircraftHeight = 110; private readonly int _drawingAircraftHeight = 110;
/// <summary> /// <summary>
@@ -58,17 +58,17 @@ public class DrawningAircraft
/// <summary> /// <summary>
/// Ширина объекта /// Ширина объекта
/// </summary> /// </summary>
public int GetWidth => _drawningMilitaryAircraftWidth; public int GetWidth => _drawningAircraftWidth;
/// <summary> /// <summary>
/// Высота объекта /// Высота объекта
/// </summary> /// </summary>
public int GetHeight => _drawingMilitaryAircraftHeight; public int GetHeight => _drawingAircraftHeight;
/// <summary> /// <summary>
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
private DrawningAircraft() public DrawningAircraft()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@@ -85,7 +85,7 @@ public class DrawningAircraft
public DrawningAircraft(int speed, double weight, Color bodyColor, int width, int height) : this() public DrawningAircraft(int speed, double weight, Color bodyColor, int width, int height) : this()
{ {
if (width < _drawingMilitaryAircraftHeight || height < _drawningMilitaryAircraftWidth) if (width < _drawingAircraftHeight || height < _drawningAircraftWidth)
{ {
return; return;
} }
@@ -102,16 +102,28 @@ public class DrawningAircraft
protected DrawningAircraft(int speed, double weight, Color bodyColor, int width, int height, int drawningMilitaryAircraftWidth, int drawingMilitaryAircraftHeight) : this() protected DrawningAircraft(int speed, double weight, Color bodyColor, int width, int height, int drawningMilitaryAircraftWidth, int drawingMilitaryAircraftHeight) : this()
{ {
if (width < _drawingMilitaryAircraftHeight || height < _drawningMilitaryAircraftWidth) if (width < _drawingAircraftHeight || height < _drawningAircraftWidth)
{ {
return; return;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
_drawningMilitaryAircraftWidth = drawningMilitaryAircraftWidth; _drawningAircraftWidth = drawningMilitaryAircraftWidth;
_drawingMilitaryAircraftHeight = drawingMilitaryAircraftHeight; _drawingAircraftHeight = drawingMilitaryAircraftHeight;
EntityAircraft = new EntityAircraft(speed, weight, bodyColor); EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
} }
/// <summary>
/// Конструктор для Drawning
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public DrawningAircraft(EntityAircraft entityAircraft)
{
EntityAircraft = entityAircraft;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@@ -120,10 +132,6 @@ public class DrawningAircraft
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns> /// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetpictureSize(int width, int height) public bool SetpictureSize(int width, int height)
{ {
if (width <= _drawningMilitaryAircraftWidth || height <= _drawingMilitaryAircraftHeight)
{
return false;
}
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
return true; return true;
@@ -176,7 +184,7 @@ public class DrawningAircraft
//Вправо //Вправо
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + _drawningMilitaryAircraftWidth + EntityAircraft.Step < _pictureWidth) if (_startPosX.Value + _drawningAircraftWidth + EntityAircraft.Step < _pictureWidth)
{ {
_startPosX += (int)EntityAircraft.Step; _startPosX += (int)EntityAircraft.Step;
} }
@@ -186,7 +194,7 @@ public class DrawningAircraft
//Влево //Влево
case DirectionType.Down: case DirectionType.Down:
if (_startPosY.Value + _drawingMilitaryAircraftHeight + EntityAircraft.Step < _pictureHeight) if (_startPosY.Value + _drawingAircraftHeight + EntityAircraft.Step < _pictureHeight)
{ {
_startPosY += (int)EntityAircraft.Step; _startPosY += (int)EntityAircraft.Step;
} }

View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Draw;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningAircraftCompareByColor : IComparer<DrawningAircraft?>
{
public int Compare(DrawningAircraft? x, DrawningAircraft? y)
{
if (x == null || x.EntityAircraft == null)
{
return -1;
}
if (y == null || y.EntityAircraft == null)
{
return 1;
}
if (x.EntityAircraft.BodyColor.Name != y.EntityAircraft.BodyColor.Name)
{
return x.EntityAircraft.BodyColor.Name.CompareTo(y.EntityAircraft.BodyColor.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,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Draw;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningAircraftCompareByType : IComparer<DrawningAircraft?>
{
public int Compare(DrawningAircraft? x, DrawningAircraft? y)
{
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,63 @@
using ProectMilitaryAircraft.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Draw;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningAircraftEqutables : IEqualityComparer<DrawningAircraft?>
{
public bool Equals(DrawningAircraft? x, DrawningAircraft? y)
{
if (x == null || x.EntityAircraft == null)
{
return false;
}
if (y == null || y.EntityAircraft == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (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 DrawningMilitaryAircraft && y is DrawningMilitaryAircraft)
{
EntityMilitaryAircraft EntityX =
(EntityMilitaryAircraft)x.EntityAircraft;
EntityMilitaryAircraft EntityY =
(EntityMilitaryAircraft)y.EntityAircraft;
if (EntityX.Pin != EntityY.Pin)
return false;
if (EntityX.Symbolism != EntityY.Symbolism)
return false;
if (EntityX.Rokets != EntityY.Rokets)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAircraft obj)
{
return obj.GetHashCode();
}
}

View File

@@ -15,6 +15,8 @@ namespace ProectMilitaryAircraft.Draw;
/// </summary> /// </summary>
public class DrawningMilitaryAircraft : DrawningAircraft public class DrawningMilitaryAircraft : DrawningAircraft
{ {
private DrawningAircraft aircraft;
/// <summary> /// <summary>
/// Констуктор /// Констуктор
/// </summary> /// </summary>
@@ -34,6 +36,25 @@ public class DrawningMilitaryAircraft : DrawningAircraft
} }
} }
/// <summary>
/// Конструктор для DrawningAircraft2
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="additionalColor"></param>
/// <param name="pin"></param>
/// <param name="rokets"></param>
/// <param name="symbolism"></param>
public DrawningMilitaryAircraft(EntityAircraft entityAircraft)
{
if (entityAircraft != null)
{
EntityAircraft = entityAircraft;
}
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityAircraft is not EntityMilitaryAircraft airCraft || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityAircraft is not EntityMilitaryAircraft airCraft || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -0,0 +1,59 @@
using ProectMilitaryAircraft.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Draw;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtensionDrawningAircraft
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningAircraft? CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityAircraft? aircraft = EntityMilitaryAircraft.CreateEntityMilitaryAircraft(strs);
if (aircraft != null)
{
return new DrawningMilitaryAircraft(aircraft);
}
aircraft = EntityAircraft.CreateEntityAircraft(strs);
if (aircraft != null)
{
return new DrawningAircraft(aircraft);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAircraft">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAircraft drawningAircraft)
{
string[]? array = drawningAircraft?.EntityAircraft?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -45,4 +45,27 @@ public class EntityAircraft
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAircraft? CreateEntityAircraft(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityAircraft))
{
return null;
}
return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@@ -43,4 +43,27 @@ public class EntityMilitaryAircraft : EntityAircraft
Rokets = rokets; Rokets = rokets;
Symbolism = symbolism; Symbolism = symbolism;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityMilitaryAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Pin.ToString(), Rokets.ToString(),Symbolism.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMilitaryAircraft? CreateEntityMilitaryAircraft(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityMilitaryAircraft))
{
return null;
}
return new EntityMilitaryAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
} }

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Exceptions;
/// <summary>
/// Класс, Описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указаной позиции нет элемента
/// </summary>
[Serializable]
public class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Exceptions;
/// <summary>
/// Класс, описывающий ошибку наличия такого же объекта в коллекции
/// </summary>
[Serializable]
internal class ObjectNotUniqueException : ApplicationException
{
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProectMilitaryAircraft.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
public 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

@@ -46,10 +46,19 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -59,15 +68,17 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(607, 0); groupBoxTools.Location = new Point(607, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(194, 563); groupBoxTools.Size = new Size(194, 560);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = " Инструменты"; groupBoxTools.Text = " Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddAircraft); panelCompanyTools.Controls.Add(buttonAddAircraft);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
@@ -93,7 +104,7 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(4, 229); buttonRefresh.Location = new Point(4, 176);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(178, 45); buttonRefresh.Size = new Size(178, 45);
buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
@@ -103,7 +114,7 @@
// //
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(4, 98); maskedTextBox.Location = new Point(4, 45);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(178, 23); maskedTextBox.Size = new Size(178, 23);
@@ -113,7 +124,7 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(4, 178); buttonGoToCheck.Location = new Point(4, 125);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(178, 45); buttonGoToCheck.Size = new Size(178, 45);
buttonGoToCheck.TabIndex = 4; buttonGoToCheck.TabIndex = 4;
@@ -124,7 +135,7 @@
// buttonRemoveAircraft // buttonRemoveAircraft
// //
buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveAircraft.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveAircraft.Location = new Point(4, 127); buttonRemoveAircraft.Location = new Point(4, 74);
buttonRemoveAircraft.Name = "buttonRemoveAircraft"; buttonRemoveAircraft.Name = "buttonRemoveAircraft";
buttonRemoveAircraft.Size = new Size(178, 45); buttonRemoveAircraft.Size = new Size(178, 45);
buttonRemoveAircraft.TabIndex = 3; buttonRemoveAircraft.TabIndex = 3;
@@ -239,19 +250,83 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(607, 563); pictureBox.Size = new Size(607, 560);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(801, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 229);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(85, 45);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(94, 229);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(85, 45);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormAircraftCollection // FormAircraftCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(801, 563); ClientSize = new Size(801, 584);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormAircraftCollection"; Name = "FormAircraftCollection";
Text = "Коллекция самолетов"; Text = "Коллекция самолетов";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -260,7 +335,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -283,5 +361,13 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@@ -1,5 +1,7 @@
using ProectMilitaryAircraft.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProectMilitaryAircraft.CollectionGenericObjects;
using ProectMilitaryAircraft.Draw; using ProectMilitaryAircraft.Draw;
using ProectMilitaryAircraft.Exceptions;
using ProectMilitaryAircraft.MovementStrategy; using ProectMilitaryAircraft.MovementStrategy;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -28,14 +30,19 @@ public partial class FormAircraftCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormAircraftCollection() public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@@ -55,7 +62,7 @@ public partial class FormAircraftCollection : Form
private void ButtonAddAircraft_Click(object sender, EventArgs e) private void ButtonAddAircraft_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex == -1) return; if (listBoxCollection.SelectedIndex == -1) return;
var obj = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty]; var obj = _storageCollection[listBoxCollection.SelectedItem?.ToString() ?? string.Empty, new CollectionType()];
if (obj == null) return; if (obj == null) return;
FormAircraftConfig form = new(); FormAircraftConfig form = new();
@@ -74,15 +81,25 @@ public partial class FormAircraftCollection : Form
return; return;
} }
try
{
if (_company + aircraft) if (_company + aircraft)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен", _company);
} }
else else
{ {
MessageBox.Show("не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Не удалось добавить объект");
}
}
catch (CollectionOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}. Не удалось добавить объект", ex.Message);
} }
} }
@@ -104,14 +121,20 @@ public partial class FormAircraftCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - pos) if (_company - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален", _company);
} }
else
}
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -129,6 +152,8 @@ public partial class FormAircraftCollection : Form
DrawningAircraft? aircraft = null; DrawningAircraft? aircraft = null;
int counter = 100; int counter = 100;
while (aircraft == null) while (aircraft == null)
{
try
{ {
aircraft = _company.GetRandomObject(); aircraft = _company.GetRandomObject();
counter--; counter--;
@@ -136,6 +161,14 @@ public partial class FormAircraftCollection : Form
{ {
break; break;
} }
_logger.LogInformation("Рандомный объект", _company);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
if (aircraft == null) { return; } if (aircraft == null) { return; }
@@ -203,7 +236,7 @@ public partial class FormAircraftCollection : Form
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() _storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString()
?? string.Empty); ?? string.Empty, new CollectionType()) ;
RefreshListBoxItems(); RefreshListBoxItems();
} }
@@ -214,7 +247,7 @@ 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]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@@ -235,7 +268,7 @@ public partial class FormAircraftCollection : Form
return; return;
} }
ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString()?? string.Empty]; ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty, new CollectionType()];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллкция не проиницилизирована"); MessageBox.Show("Коллкция не проиницилизирована");
@@ -253,4 +286,72 @@ public partial class FormAircraftCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RefreshListBoxItems(); RefreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия на "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(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);
}
}
}
/// <summary>
/// Обработка нажатия на "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_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)
{
CompareAircraft(new DrawningAircraftCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareAircraft(new DrawningAircraftCompareByColor());
}
private void CompareAircraft(IComparer<DrawningAircraft?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }

View File

@@ -117,4 +117,16 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>16, 5</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 5</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>260, 5</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>48</value>
</metadata>
</root> </root>

View File

@@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +28,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProectMilitaryAircraft namespace ProectMilitaryAircraft
{ {
internal static class Program internal static class Program
@@ -10,8 +14,28 @@ namespace ProectMilitaryAircraft
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormAircraftCollection()); ServiceCollection services = new();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAircraftCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>