Pibd_13_Fathutdinov_A.I. labWork_07 Simple #8
@ -1,9 +1,12 @@
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Абстракция компании, хранящий коллекцию лайнеров
|
||||
/// Абстракция компании, хранящий коллекцию автомобилей
|
||||
/// </summary>
|
||||
public abstract class AbstractCompany
|
||||
{
|
||||
@ -15,7 +18,7 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 110;
|
||||
protected readonly int _placeSizeHeight = 150;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
@ -28,21 +31,21 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
protected readonly int _pictureHeight;
|
||||
|
||||
/// <summary>
|
||||
/// Коллекция лайнеров
|
||||
/// Коллекция автомобилей
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningCommonLiner>? _collection = null;
|
||||
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина окна</param>
|
||||
/// <param name="picHeight">Высота окна</param>
|
||||
/// <param name="collection">Коллекция лайнеров</param>
|
||||
/// <param name="collection">Коллекция автомобилей</param>
|
||||
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningCommonLiner> collection)
|
||||
{
|
||||
_pictureWidth = picWidth;
|
||||
@ -55,12 +58,11 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="Liner">Добавляемый объект</param>
|
||||
/// <param name="airplane">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
|
||||
public static int operator +(AbstractCompany company, DrawningCommonLiner airplan)
|
||||
public static int operator +(AbstractCompany company, DrawningCommonLiner airplane)
|
||||
{
|
||||
return company._collection.Insert(airplan);
|
||||
return company._collection.Insert(airplane);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -71,7 +73,7 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// <returns></returns>
|
||||
public static DrawningCommonLiner operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company._collection.Remove(position) ;
|
||||
return company._collection.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -81,7 +83,14 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
public DrawningCommonLiner? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
try
|
||||
{
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -97,8 +106,15 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningCommonLiner? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningCommonLiner? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
|
@ -1,64 +1,67 @@
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
|
||||
namespace ProjectLiner.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Реализация абстрактной компании - лайнер
|
||||
/// </summary>
|
||||
public class LinerSharingService : AbstractCompany
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина</param>
|
||||
/// <param name="picHeight">Высота</param>
|
||||
/// <param name="collection">Коллекция</param>
|
||||
public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningCommonLiner> collection) : base(picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
public class LinerSharingService : AbstractCompany
|
||||
{
|
||||
Pen pen = new(Color.Black, 4);
|
||||
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
|
||||
public LinerSharingService(int picWidth, int picHeight, ICollectionGenericObjects<DrawningCommonLiner> collection) : base(picWidth, picHeight, collection)
|
||||
{
|
||||
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
|
||||
}
|
||||
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
Pen pen = new(Color.Black, 4);
|
||||
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
|
||||
{
|
||||
g.DrawLine(pen, i * _placeSizeWidth, (int)(j * _placeSizeHeight * 1.3),
|
||||
i * _placeSizeWidth + _placeSizeWidth - 40, (int)(j * _placeSizeHeight * 1.3));
|
||||
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
|
||||
{
|
||||
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight,
|
||||
i * _placeSizeWidth + _placeSizeWidth - 40, j * _placeSizeHeight);
|
||||
}
|
||||
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 5);
|
||||
}
|
||||
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
{
|
||||
curWidth = width - 1;
|
||||
curHeight++;
|
||||
}
|
||||
if (curHeight > height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (_collection?.Get(i) != null)
|
||||
{
|
||||
_collection.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 10, (int)(curHeight * _placeSizeHeight * 1.3));
|
||||
}
|
||||
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
{
|
||||
curWidth = width - 1;
|
||||
curHeight++;
|
||||
}
|
||||
if (curHeight > height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,76 +1,97 @@
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
private readonly Dictionary<int, T> _collection;
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public int Count => _collection.Keys.Count;
|
||||
public int MaxCount
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
get
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
return _maxCount;
|
||||
get
|
||||
{
|
||||
return _maxCount;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
if (value > 0)
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= Count || position < 0)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count >= _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
throw new CollectionOverflowException(Count);
|
||||
if (position < 0 || position > Count)
|
||||
throw new PositionOutOfCollectionException(position); ;
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
_maxCount = value;
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
return _collection[position];
|
||||
}
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count > _maxCount) return -1;
|
||||
_collection[Count-1] = obj;
|
||||
return Count;
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count > _maxCount) return -1;
|
||||
_collection[position] = obj;
|
||||
return 1;
|
||||
}
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (_collection.ContainsKey(position)) return null;
|
||||
T? temp = _collection[position];
|
||||
_collection.Remove(position);
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,8 @@
|
||||
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
@ -12,7 +16,7 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount
|
||||
@ -51,7 +55,9 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
return null;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
@ -65,17 +71,20 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return -1;
|
||||
if (position >= Count || position < 0)
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
int temp = position + 1;
|
||||
while (temp < Count)
|
||||
{
|
||||
@ -84,29 +93,30 @@ namespace ProjectLiner.CollectionGenericObjects
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
++temp;
|
||||
temp++;
|
||||
}
|
||||
|
||||
temp = position - 1;
|
||||
while (temp >= 0)
|
||||
while (temp > 0)
|
||||
{
|
||||
if (_collection[temp] == null)
|
||||
{
|
||||
_collection[temp] = obj;
|
||||
return temp;
|
||||
}
|
||||
--temp;
|
||||
temp--;
|
||||
}
|
||||
return -1;
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
|
||||
//if (_collection[position] == null) return null;
|
||||
if (_collection[position] == null)
|
||||
throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
|
@ -1,208 +1,226 @@
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningCommonLiner
|
||||
namespace ProjectLiner.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> 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()
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningCommonLiner
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (name == null || _storages.ContainsKey(name)) { return; }
|
||||
switch (collectionType)
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> 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()
|
||||
{
|
||||
case CollectionType.None:
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (name == null || _storages.ContainsKey(name))
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
return;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (name == null || !_storages.ContainsKey(name)) { return null; }
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по лайнерам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
return false;
|
||||
|
||||
if (File.Exists(filename))
|
||||
File.Delete(filename);
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter sw = new StreamWriter(fs);
|
||||
sw.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sw.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
switch (collectionType)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(value.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.GetCollectionType);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.MaxCount);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
case CollectionType.None:
|
||||
return;
|
||||
case CollectionType.Massive:
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
return;
|
||||
case CollectionType.List:
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
return;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по лайнерам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
return false;
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
using StreamReader sr = new StreamReader(fs);
|
||||
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
get
|
||||
{
|
||||
return false;
|
||||
if (name == null || !_storages.ContainsKey(name))
|
||||
return null;
|
||||
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
|
||||
if (!str.Equals(_collectionKey))
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
|
||||
if (File.Exists(filename))
|
||||
File.Delete(filename);
|
||||
|
||||
|
||||
using (StreamWriter sw = new(filename))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_storages.Clear();
|
||||
|
||||
while (!sr.EndOfStream)
|
||||
{
|
||||
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
sw.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningCommonLiner() is T commonLiner)
|
||||
sw.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
if (collection.Insert(commonLiner) == -1)
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(value.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.GetCollectionType);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.MaxCount);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
/// <summary>
|
||||
/// Загрузка информации по самолетам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
throw new FileFormatException("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!str.Equals(_collectionKey))
|
||||
{
|
||||
throw new FileFormatException("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
|
||||
while (!sr.EndOfStream)
|
||||
{
|
||||
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new InvalidOperationException("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningCommonLiner() is T airplane)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(airplane) == -1)
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new OverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -77,5 +77,4 @@ public class EntityLiner: EntityCommonLiner
|
||||
Color.FromName(strs[3]), Color.FromName(strs[4]),
|
||||
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectLiner.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
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) { }
|
||||
}
|
@ -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 ProjectLiner.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
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) { }
|
||||
}
|
@ -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 ProjectLiner.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) { }
|
||||
}
|
@ -75,7 +75,7 @@
|
||||
// buttonCreateCompany
|
||||
//
|
||||
buttonCreateCompany.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
|
||||
buttonCreateCompany.Location = new Point(8, 520);
|
||||
buttonCreateCompany.Location = new Point(7, 495);
|
||||
buttonCreateCompany.Margin = new Padding(5);
|
||||
buttonCreateCompany.Name = "buttonCreateCompany";
|
||||
buttonCreateCompany.Size = new Size(257, 38);
|
||||
@ -96,13 +96,13 @@
|
||||
panelStorage.Dock = DockStyle.Top;
|
||||
panelStorage.Location = new Point(3, 43);
|
||||
panelStorage.Name = "panelStorage";
|
||||
panelStorage.Size = new Size(266, 405);
|
||||
panelStorage.Size = new Size(266, 370);
|
||||
panelStorage.TabIndex = 7;
|
||||
//
|
||||
// buttonCollectionDel
|
||||
//
|
||||
buttonCollectionDel.Font = new Font("Segoe UI", 9.75F, FontStyle.Regular, GraphicsUnit.Point);
|
||||
buttonCollectionDel.Location = new Point(5, 348);
|
||||
buttonCollectionDel.Location = new Point(3, 314);
|
||||
buttonCollectionDel.Margin = new Padding(5);
|
||||
buttonCollectionDel.Name = "buttonCollectionDel";
|
||||
buttonCollectionDel.Size = new Size(257, 38);
|
||||
@ -180,7 +180,7 @@
|
||||
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxSelectorCompany.FormattingEnabled = true;
|
||||
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
||||
comboBoxSelectorCompany.Location = new Point(20, 458);
|
||||
comboBoxSelectorCompany.Location = new Point(23, 419);
|
||||
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
||||
comboBoxSelectorCompany.Size = new Size(242, 49);
|
||||
comboBoxSelectorCompany.TabIndex = 0;
|
||||
@ -249,7 +249,7 @@
|
||||
button3.TabIndex = 4;
|
||||
button3.Text = "Удаление Лайнера";
|
||||
button3.UseVisualStyleBackColor = true;
|
||||
button3.Click += ButtonRemoveLiner_Click;
|
||||
button3.Click += ButtonRemoveCommonLiner_Click;
|
||||
//
|
||||
// button4
|
||||
//
|
||||
|
@ -1,266 +1,328 @@
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Drawnings;
|
||||
using ProjectLiner.Exceptions;
|
||||
using ProjectLiner.CollectionGenericObjects;
|
||||
using ProjectLiner.Exceptions;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectLiner;
|
||||
/// <summary>
|
||||
/// Форма работы с компанией и ее коллекцией
|
||||
/// </summary>
|
||||
public partial class FormLinerCollection : Form
|
||||
namespace ProjectLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Хранилише коллекций
|
||||
/// Форма работы с компанией и ее коллекцией
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningCommonLiner> _storageCollection;
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormLinerCollection()
|
||||
public partial class FormLinerCollection : Form
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление лайнера
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddCommonLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormLinerConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetLiner);
|
||||
}
|
||||
/// <summary>
|
||||
/// Хранилише коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningCommonLiner> _storageCollection;
|
||||
|
||||
/// <summary>
|
||||
/// Добавление Лайнера в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="airplane"></param>
|
||||
private void SetLiner(DrawningCommonLiner liner)
|
||||
{
|
||||
if (_company == null || liner == null)
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormLinerCollection(ILogger<FormLinerCollection> logger)
|
||||
{
|
||||
return;
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
if (_company + liner != -1)
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление самолета
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddCommonLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormLinerConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetLiner);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление самолета в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="CommonLiner"></param>
|
||||
private void SetLiner(DrawningCommonLiner CommonLiner)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_company == null || CommonLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + CommonLiner != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: {0}", CommonLiner.GetDataForSave());
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveCommonLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox1.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int pos = Convert.ToInt32(maskedTextBox1.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удалён объект по позиции {0}", pos);
|
||||
}
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Передача объекта в другую форму
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DrawningCommonLiner? plane = null;
|
||||
int counter = 100;
|
||||
while (plane == null)
|
||||
{
|
||||
plane = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (plane == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
FormLiner form = new()
|
||||
{
|
||||
SetLiner = plane
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (ObjectNotFoundException)
|
||||
{
|
||||
_logger.LogError("Ошибка при передаче объекта на FormLiner");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBoxPosition?.Text) || _company == null)
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Передача объекта в другую форму
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawningCommonLiner? liner = null;
|
||||
int counter = 100;
|
||||
while (liner == null)
|
||||
{
|
||||
liner = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0) break;
|
||||
}
|
||||
if (liner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormLiner form = new FormLiner();
|
||||
form.SetLiner = liner;
|
||||
form.ShowDialog();
|
||||
}
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
pictureBox.Image = _company.Show();
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
collectionType = CollectionType.Massive;
|
||||
else if (radioButtonList.Checked)
|
||||
collectionType = CollectionType.List;
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Добавлена коллекция: {Collection} типа: {Type}", textBoxCollectionName.Text, collectionType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedItems == null || listBoxCollection.SelectedIndex < 0)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция удалена: {0}", textBoxCollectionName.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RefreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
ICollectionGenericObjects<DrawningCommonLiner>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
/// <summary>
|
||||
/// Создание компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
else
|
||||
|
||||
ICollectionGenericObjects<DrawningCommonLiner>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new LinerSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
_logger.LogInformation("Создна компания типа {Company}, коллекция: {Collection}", comboBoxSelectorCompany.Text, textBoxCollectionName.Text);
|
||||
_logger.LogInformation("Создана компания на коллекции: {Collection}", textBoxCollectionName.Text);
|
||||
break;
|
||||
}
|
||||
|
||||
panelCompanyTools.Enabled = true;
|
||||
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)
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Загрузка"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -126,4 +126,7 @@
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>519, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>25</value>
|
||||
</metadata>
|
||||
</root>
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectLiner
|
||||
{
|
||||
internal static class Program
|
||||
@ -10,8 +15,36 @@ namespace ProjectLiner
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormLinerCollection());
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormLinerCollection>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
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<FormLinerCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,15 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +32,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
19
ProjectLiner/ProjectLiner/serilog.json
Normal file
19
ProjectLiner/ProjectLiner/serilog.json
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [
|
||||
"Serilog.Sinks.File"
|
||||
],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log.log"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Неверный тип ошибки