4 Commits
Lab06 ... Lab08

Author SHA1 Message Date
f577b5ac4f Убраны некоторые лишние пустые строки 2024-06-12 21:34:13 +04:00
4ed898c5a2 Сделал лаб08 2024-06-12 20:17:17 +04:00
f9a01c77fa Доделал лаб07 2024-06-12 16:40:18 +04:00
b614557ff8 Поделал лаб07 2024-05-21 22:03:41 +04:00
20 changed files with 694 additions and 177 deletions

View File

@@ -10,32 +10,26 @@ public abstract class AbstractCompany
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 180;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 100;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция cамолетов
/// </summary>
protected ICollectionGenericObjects<DrawingBasicSeaplane>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight))-15;
/// <summary>
/// Конструктор
/// </summary>
@@ -49,7 +43,6 @@ public abstract class AbstractCompany
_collection = collection;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
@@ -58,9 +51,8 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingBasicSeaplane seaplane)
{
return company._collection.Insert(seaplane);
return company._collection.Insert(seaplane, new DrawingSeaplaneEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
@@ -71,7 +63,6 @@ public abstract class AbstractCompany
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
@@ -81,7 +72,6 @@ public abstract class AbstractCompany
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
@@ -95,21 +85,28 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawingBasicSeaplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try {
DrawingBasicSeaplane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawingBasicSeaplane?> comparer) => _collection?.CollectionSort(comparer);
}

View File

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

@@ -11,34 +11,29 @@ public interface ICollectionGenericObjects<T>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <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>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@@ -54,4 +49,9 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,4 +1,8 @@
namespace ProjectSeaplane.CollectionGenericObjects;

using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
@@ -27,7 +31,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@@ -38,24 +41,38 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
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;
if (compaper != null)
{
if (_collection.Contains(obj, compaper))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_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;
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;
}
@@ -63,12 +80,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
@@ -76,4 +92,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,8 @@
namespace ProjectSeaplane.CollectionGenericObjects;

using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -35,7 +39,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
@@ -48,17 +51,22 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position >= _collection.Length || position < 0) 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)
{
// TODO вставка в свободное место набора
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<DrawingBasicSeaplane>).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
@@ -70,28 +78,34 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (compaper != null)
{
foreach (T? item in _collection)
{
if ((compaper as IEqualityComparer<DrawingBasicSeaplane>).Equals(obj as DrawingBasicSeaplane, item as DrawingBasicSeaplane))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
@@ -100,7 +114,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
@@ -109,22 +122,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position >= _collection.Length || position < 0) 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++)
@@ -132,4 +141,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -1,4 +1,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -49,11 +50,18 @@ public class PlanePark : AbstractCompany
}
for (int x = _pictureWidth - 200; x - 120 > 0; x -= _placeSizeHeight + 75)
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(x, y);
count++;
if (count < _collection?.Count)
{
try
{
_collection?.Get(count)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(count)?.SetPosition(x, y);
count++;
}
catch (ObjectNotFoundException) { }
}
}
}
}
}

View File

@@ -1,4 +1,5 @@
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System.Text;
namespace ProjectSeaplane.CollectionGenericObjects;
@@ -12,34 +13,29 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@@ -51,12 +47,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>
/// Удаление коллекции
@@ -65,10 +62,10 @@ public class StorageCollection<T>
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>
/// Доступ к коллекции
/// </summary>
@@ -79,24 +76,25 @@ 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>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при
///сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@@ -105,7 +103,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
@@ -116,8 +114,6 @@ public class StorageCollection<T>
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
@@ -134,29 +130,29 @@ public class StorageCollection<T>
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке
///данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
string strs = "";
@@ -164,31 +160,37 @@ public class StorageCollection<T>
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBasicSeaplane() is T seaplane)
{
if (collection.Insert(seaplane) == -1)
try
{
return false;
if (collection.Insert(seaplane) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
} catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
return true;
}
}
/// <summary>

View File

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

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Drawnings;
/// <summary>
/// сравнение по цвету, скорости и весу
/// </summary>
public class SeaplaneCompareByColor : IComparer<DrawingBasicSeaplane?>
{
public int Compare(DrawingBasicSeaplane? x, DrawingBasicSeaplane? y)
{
if (x == null || x.EntityBasicSeaplane == null)
{
return 1;
}
if (y == null || y.EntityBasicSeaplane == null)
{
return -1;
}
var bodycolorCompare = x.EntityBasicSeaplane.BodyColor.Name.CompareTo(y.EntityBasicSeaplane.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBasicSeaplane.Speed.CompareTo(y.EntityBasicSeaplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBasicSeaplane.Weight.CompareTo(y.EntityBasicSeaplane.Weight);
}
}

View File

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

View File

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

@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@@ -75,15 +77,17 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddBasicSeaplane);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonDelSeaplane);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 361);
panelCompanyTools.Location = new Point(3, 301);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(174, 226);
panelCompanyTools.Size = new Size(174, 286);
panelCompanyTools.TabIndex = 9;
//
// buttonAddBasicSeaplane
@@ -102,7 +106,7 @@
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.FlatStyle = FlatStyle.Flat;
buttonRefresh.Location = new Point(0, 183);
buttonRefresh.Location = new Point(0, 148);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(174, 31);
buttonRefresh.TabIndex = 6;
@@ -112,7 +116,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(0, 83);
maskedTextBox.Location = new Point(0, 48);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(174, 23);
@@ -123,7 +127,7 @@
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.FlatStyle = FlatStyle.Flat;
buttonGoToCheck.Location = new Point(0, 148);
buttonGoToCheck.Location = new Point(0, 113);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 5;
@@ -135,7 +139,7 @@
//
buttonDelSeaplane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelSeaplane.FlatStyle = FlatStyle.Flat;
buttonDelSeaplane.Location = new Point(0, 112);
buttonDelSeaplane.Location = new Point(0, 77);
buttonDelSeaplane.Name = "buttonDelSeaplane";
buttonDelSeaplane.Size = new Size(174, 30);
buttonDelSeaplane.TabIndex = 4;
@@ -145,9 +149,9 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(3, 334);
buttonCreateCompany.Location = new Point(3, 269);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(171, 26);
buttonCreateCompany.Size = new Size(174, 26);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -165,12 +169,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(174, 280);
panelStorage.Size = new Size(174, 219);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(0, 234);
buttonCollectionDel.Location = new Point(0, 189);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(171, 26);
buttonCollectionDel.TabIndex = 6;
@@ -184,7 +188,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 104);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(168, 124);
listBoxCollection.Size = new Size(168, 79);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
@@ -240,9 +244,9 @@
СomboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
СomboBoxSelectorCompany.FormattingEnabled = true;
СomboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
СomboBoxSelectorCompany.Location = new Point(3, 305);
СomboBoxSelectorCompany.Location = new Point(3, 240);
СomboBoxSelectorCompany.Name = "СomboBoxSelectorCompany";
СomboBoxSelectorCompany.Size = new Size(171, 23);
СomboBoxSelectorCompany.Size = new Size(174, 23);
СomboBoxSelectorCompany.TabIndex = 0;
СomboBoxSelectorCompany.SelectedIndexChanged += СomboBoxSelectorCompany_SelectedIndexChanged;
//
@@ -295,6 +299,30 @@
//
saveFileDialog.Filter = "txt file |*.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.FlatStyle = FlatStyle.Flat;
buttonSortByColor.Location = new Point(0, 230);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(171, 37);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.FlatStyle = FlatStyle.Flat;
buttonSortByType.Location = new Point(0, 185);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(171, 39);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@@ -344,5 +372,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,5 +1,8 @@
using ProjectSeaplane.CollectionGenericObjects;

using Microsoft.Extensions.Logging;
using ProjectSeaplane.CollectionGenericObjects;
using ProjectSeaplane.Drawnings;
using ProjectSeaplane.Exceptions;
using System.Windows.Forms;
namespace ProjectSeaplane;
@@ -19,13 +22,16 @@ public partial class FormPlaneCollection : Form
/// </summary>
AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
public FormPlaneCollection(ILogger<FormPlaneCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@@ -56,23 +62,37 @@ public partial class FormPlaneCollection : Form
/// <param name="plane"></param>
private void SetPlane(DrawingBasicSeaplane plane)
{
if (_company == null || plane == null)
try
{
return;
}
if (_company == null || plane == null)
{
return;
}
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + plane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + plane.GetDataForSave());
}
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Выход за границы коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект, такой объект уже является частью коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
/// Удаление объекта
/// </summary>
@@ -84,24 +104,26 @@ public partial class FormPlaneCollection : Form
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.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);
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
@@ -116,28 +138,35 @@ public partial class FormPlaneCollection : Form
DrawingBasicSeaplane? seaplane = null;
int counter = 100;
while (seaplane == null)
try
{
seaplane = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (seaplane == null)
{
break;
seaplane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
}
if (seaplane == null)
{
return;
}
if (seaplane == null)
{
return;
}
FormSeaplane form = new()
FormSeaplane form = new()
{
SetSeaplane = seaplane
};
form.ShowDialog();
}
catch (Exception ex)
{
SetSeaplane = seaplane
};
form.ShowDialog();
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
@@ -152,9 +181,6 @@ public partial class FormPlaneCollection : Form
pictureBox.Image = _company.Show();
}
/// <summary>
/// добавление коллекции
/// </summary>
@@ -168,17 +194,27 @@ public partial class FormPlaneCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error);
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>
/// Обновление списка в ListboxCollection
@@ -188,14 +224,13 @@ 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);
}
}
}
/// <summary>
/// удаление коллекции
/// </summary>
@@ -208,12 +243,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>
/// создание компании
@@ -244,7 +287,6 @@ public partial class FormPlaneCollection : Form
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
@@ -254,19 +296,21 @@ public partial class FormPlaneCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
@@ -276,18 +320,51 @@ public partial class FormPlaneCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
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 buttonSortByType_Click(object sender, EventArgs e)
{
CompareSeaplane(new SeaplaneCompareByType());
}
/// <summary>
/// Cортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareSeaplane(new SeaplaneCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareSeaplane(IComparer<DrawingBasicSeaplane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -126,4 +126,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>50</value>
</metadata>
</root>

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectSeaplane
{
internal static class Program
@@ -11,7 +16,30 @@ namespace ProjectSeaplane
// 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,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +34,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"
}
}
}