Compare commits
6 Commits
LabWork05
...
LabWork_08
| Author | SHA1 | Date | |
|---|---|---|---|
| 55d4fe2ed9 | |||
| a4c7b2d9a3 | |||
| 587bc65760 | |||
| 329ebf6e8a | |||
| 128ee83824 | |||
| 5f6dec67ad |
@@ -35,7 +35,7 @@ namespace MotorBoat.CollectionGenericObjects
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight * 73/50);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -48,7 +48,7 @@ namespace MotorBoat.CollectionGenericObjects
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.SetMaxCount = GetMaxCount;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -59,7 +59,7 @@ namespace MotorBoat.CollectionGenericObjects
|
||||
/// <returns></returns>
|
||||
public static bool operator +(AbstractCompany company, DrawningBoat boat)
|
||||
{
|
||||
return company._collection?.Insert(boat) ?? false;
|
||||
return company._collection?.Insert(boat, new DrawningBoatEqutables()) ?? false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -103,6 +103,12 @@ namespace MotorBoat.CollectionGenericObjects
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawningBoat?> comparer) => _collection?.CollectionSort(comparer);
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace MotorBoat.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,22 +15,24 @@
|
||||
/// <summary>
|
||||
/// Установка максимального количества элементов
|
||||
/// </summary>
|
||||
int SetMaxCount { set; }
|
||||
int MaxCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="comparer">Cравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
bool Insert(T obj);
|
||||
bool Insert(T obj, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <param name="comparer">Cравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
|
||||
bool Insert(T obj, int position);
|
||||
bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
@@ -45,5 +47,22 @@
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
CollectionType GetCollectionType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции по одному
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
using MotorBoat.Exceptions;
|
||||
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@@ -19,7 +21,19 @@
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
||||
public int MaxCount
|
||||
{
|
||||
get => _maxCount;
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@@ -29,63 +43,83 @@
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
//---------------TODO ПРОВЕРКА ПО ПОЗИЦИИ----------------------------//
|
||||
//---------------TODO НЕ ВЫХОДИТ ЛИ ЗА ГРАНИЦЫ СПИСКА---------------//
|
||||
/// /////////////////////////////////////////////////////////////////
|
||||
/// <param name="position"></param>
|
||||
/// <returns></returns>
|
||||
public T? Get(int position)
|
||||
{
|
||||
|
||||
if (position < 0 || position >= _maxCount)
|
||||
{
|
||||
return null;
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////
|
||||
//---------------TODO ПРОВЕРКА ВСТАВКИ----------------------//
|
||||
//---------------TODO ВСТАВКА В КОНЕЦ НАБОРА---------------//
|
||||
////////////////////////////////////////////////////////////
|
||||
public bool Insert(T obj)
|
||||
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - выборс ошибки, если такой объект есть в коллекции---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
return false;
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
}
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new AlreadyExistException();
|
||||
}
|
||||
_collection.Add(obj);
|
||||
return true;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------TODO ПРОВЕРКА ВСТАВКИ--------------------------------------------------------//
|
||||
//---------------TODO ОТСУТСТВИЕ ПРЕВЫШЕНИЯ МАКСИМАЛЬНОГО КОЛИЧЕСТВА ЭЛЕМЕНТОВ---------------//
|
||||
//---------------TODO ПРОВЕРКА ПОЗИЦИИ------------------------------------------------------//
|
||||
//---------------TODO ВСТАВКА ПО ПОЗИЦИИ---------------------------------------------------//
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
public bool Insert(T obj, int position)
|
||||
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount || Count == _maxCount)
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - выборс ошибки, если такой объект есть в коллекции---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
if (position < 0 || position >= _maxCount)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
}
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new AlreadyExistException();
|
||||
}
|
||||
_collection.Insert(position, obj);
|
||||
return true;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
//---------------TODO ПРОВЕРКА ПОЗИЦИИ--------------------------//
|
||||
//---------------TODO УДАЛЕНИЕ ОБЪЕКТА ИЗ СПИСКА---------------//
|
||||
////////////////////////////////////////////////////////////////
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (_collection.Count == 0 || position < 0 || position >= _collection.Count)
|
||||
if (/*_collection.Count == 0 || position < 0 || */position > _collection.Count)
|
||||
{
|
||||
return false;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
_collection.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
//---------------Lab08 - добавить код---------------//
|
||||
/////////////////////////////////////////////////////
|
||||
///как и проверка на равенство идентично, у листа встроенный метод сорт точка, у массива класс аррэй точка
|
||||
///туда передаем компэир который говорит как мы хотим сравнивать и внутри будет вызываться метод компэир
|
||||
public void CollectionSort(IComparer<T?> comparer) => _collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
|
||||
using MotorBoat.Exceptions;
|
||||
using System.Text;
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@@ -14,8 +17,12 @@
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int SetMaxCount
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
@@ -32,6 +39,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -42,23 +51,36 @@
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < _collection.Length)
|
||||
{
|
||||
return _collection[position];
|
||||
if (position < 0 || position >= _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
return null;
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public bool Insert(T obj)
|
||||
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if(obj == null)
|
||||
if (obj == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
int result = _collection.Count(s => s == null);
|
||||
if (result == 0)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - выборс ошибки, если такой объект есть в коллекции---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new AlreadyExistException();
|
||||
}
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return true;
|
||||
@@ -67,38 +89,84 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Insert(T obj, int position)
|
||||
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
if (position >= 0 && position < _collection.Length)
|
||||
if (obj == null)
|
||||
{
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return true;
|
||||
}
|
||||
|
||||
for (int i = position + 1; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (position < 0 || position >= _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - выборс ошибки, если такой объект есть в коллекции---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new AlreadyExistException();
|
||||
}
|
||||
|
||||
int result = _collection.Count(s => s == null);
|
||||
if (result == 0)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return true;
|
||||
}
|
||||
for (int i = ++position; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (int i = --position; i >= 0; i--)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position >= 0 && position < _collection.Length)
|
||||
if (position < 0 || position >= _collection.Length)
|
||||
{
|
||||
_collection[position] = null;
|
||||
return true;
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
_collection[position] = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
if (_collection != null && _collection.Length > 0)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +1,51 @@
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
using MotorBoat.Drawnings;
|
||||
using MotorBoat.Exceptions;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MotorBoat.CollectionGenericObjects
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс-хранилище коллекций
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class StorageCollection<T>
|
||||
where T : class
|
||||
where T : DrawningBoat
|
||||
{
|
||||
/// <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>>();
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------TODO ПРОВЕРКА ЧТО NAME НЕ ПУСТОЙ - ОТСУТСТВУЕТ ЗАПИСЬ В СЛОВАРЕ С ТАКИМ КЛЮЧОМ---------------//
|
||||
//---------------TODO ЛОГИКА ДЛЯ ДОБАВЛЕНИЯ ЗАВИСИМОСТИ ОТ collectionType СОЗДАЕМ ОБЪЕКТ ЛИБО----------------//
|
||||
//---------------TODO В MassiveGenericObjects ЛИБО в ListGenericObjects-------------------------------------//
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
@@ -37,42 +53,40 @@
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (name == null || Keys.Contains(name))
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
|
||||
|
||||
if (name == null || Keys.Contains(collectionInfo))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (collectionType)
|
||||
{
|
||||
case CollectionType.Massive:
|
||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
|
||||
break;
|
||||
case CollectionType.List:
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
break;
|
||||
case CollectionType.None:
|
||||
_storages.Add(collectionInfo, new ListGenericObjects<T>());
|
||||
break;
|
||||
default:
|
||||
return; // Обработка других типов, если необходимо
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------TODO УДАЛЕНИЕ КОЛЛЕКЦИИ С ПРОВЕРКОЙ НАЛИЧИЯ КЛЮЧА---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (name == null || !Keys.Contains(name))
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
if (name == null || !Keys.Contains(collectionInfo))
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storages.Remove(name);
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
//---------------TODO ЛОГИКА ПОЛУЧЕНИЯ ОБЪЕКТА---------------//
|
||||
//////////////////////////////////////////////////////////////
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
@@ -82,9 +96,147 @@
|
||||
{
|
||||
get
|
||||
{
|
||||
return _storages.GetValueOrDefault(name, null);
|
||||
return _storages.GetValueOrDefault(new CollectionInfo(name, CollectionType.Massive, string.Empty), null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
StringBuilder sb = new();
|
||||
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
}
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
|
||||
fs.Write(info, 0, info.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
}
|
||||
|
||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!strs[0].Equals(_collectionKey))
|
||||
{
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
|
||||
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningBoat() is T boat)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!collection.Insert(boat))
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,14 @@ namespace MotorBoat.Drawnings
|
||||
_drawningMotorBoatHeight = drawningMotorBoatHeight;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//---------------Lab06 - Конструктор---------------//
|
||||
////////////////////////////////////////////////////
|
||||
public DrawningBoat(EntityBoat? entityBoat)
|
||||
{
|
||||
EntityBoat = entityBoat;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Установка границ поля
|
||||
/// </summary>
|
||||
|
||||
34
MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs
Normal file
34
MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByColor.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
namespace MotorBoat.Drawnings
|
||||
{
|
||||
/// <summary>
|
||||
/// Сравнение по цвету, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningBoatCompareByColor : IComparer<DrawningBoat?>
|
||||
{
|
||||
public int Compare(DrawningBoat? x, DrawningBoat? y)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - прописать логику сравения по цветам, скорости, весу---------------//
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
if (x == null || x.EntityBoat == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (y == null || y.EntityBoat == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (x.EntityBoat.BodyColor.Name != y.EntityBoat.BodyColor.Name)
|
||||
{
|
||||
return x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
|
||||
}
|
||||
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs
Normal file
34
MotorBoat/MotorBoat/Drawnings/DrawningBoatCompareByType.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
namespace MotorBoat.Drawnings
|
||||
{
|
||||
/// <summary>
|
||||
/// Сравнение по типу, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningBoatCompareByType : IComparer<DrawningBoat?>
|
||||
{
|
||||
public int Compare(DrawningBoat? x, DrawningBoat? y)
|
||||
{
|
||||
if (x == null || x.EntityBoat == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityBoat == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
|
||||
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
78
MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs
Normal file
78
MotorBoat/MotorBoat/Drawnings/DrawningBoatEqutables.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using MotorBoat.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace MotorBoat.Drawnings
|
||||
{
|
||||
/// <summary>
|
||||
/// Реализация сравнения двух объектов класса-прорисовки
|
||||
/// </summary>
|
||||
public class DrawningBoatEqutables : IEqualityComparer<DrawningBoat?>
|
||||
{
|
||||
public bool Equals(DrawningBoat? x, DrawningBoat? y)
|
||||
{
|
||||
if (x == null || x.EntityBoat == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityBoat == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (x is DrawningMotorBoat && y is DrawningMotorBoat)
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab08 - доделать логику сравнения дополнительных параметров---------------//
|
||||
////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
EntityMotorBoat entityMotorBoatX = (EntityMotorBoat)x.EntityBoat;
|
||||
EntityMotorBoat entityMotorBoatY = (EntityMotorBoat)y.EntityBoat;
|
||||
if (entityMotorBoatX.AdditionalColor != entityMotorBoatY.AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (entityMotorBoatX.AddTwoMotors != entityMotorBoatY.AddTwoMotors)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (entityMotorBoatX.Sofa != entityMotorBoatY.Sofa)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (entityMotorBoatX.SportLines != entityMotorBoatY.SportLines)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int GetHashCode([DisallowNull] DrawningBoat obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -19,6 +19,13 @@ namespace MotorBoat.Drawnings
|
||||
EntityBoat = new EntityMotorBoat(speed, weight, bodyColor, additionalColor, addTwoMotors, sofa, sportLines);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//---------------Lab06 - Конструктор---------------//
|
||||
////////////////////////////////////////////////////
|
||||
public DrawningMotorBoat(EntityMotorBoat? entityMotorBoat) : base(entityMotorBoat)
|
||||
{
|
||||
}
|
||||
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityBoat == null || EntityBoat is not EntityMotorBoat motorBoat || !_startPosX.HasValue || !_startPosY.HasValue)
|
||||
@@ -43,7 +50,6 @@ namespace MotorBoat.Drawnings
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 10, 5, 10);
|
||||
g.FillEllipse(additionalBrush, _startPosX.Value + 10, _startPosY.Value + 40, 10, 10);
|
||||
g.FillRectangle(additionalBrush, _startPosX.Value + 20, _startPosY.Value + 40, 5, 10);
|
||||
|
||||
}
|
||||
|
||||
// добавляем две полоски
|
||||
|
||||
79
MotorBoat/MotorBoat/Drawnings/ExtentionDrawningBoat.cs
Normal file
79
MotorBoat/MotorBoat/Drawnings/ExtentionDrawningBoat.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using MotorBoat.Entities;
|
||||
|
||||
namespace MotorBoat.Drawnings
|
||||
{
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityCar
|
||||
/// </summary>
|
||||
public static class ExtentionDrawningCar
|
||||
{
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separatorForObject = ":";
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <returns>Объект</returns>
|
||||
//public static DrawningBoat? CreateDrawningBoat(this string info)
|
||||
//{
|
||||
// string[] strs = info.Split(_separatorForObject);
|
||||
// EntityBoat? boat = EntityMotorBoat.CreateEntityMotorBoat(strs);
|
||||
// if (boat != null)
|
||||
// {
|
||||
// return new DrawningMotorBoat(boat);
|
||||
// }
|
||||
|
||||
// boat = EntityBoat.CreateEntityBoat(strs);
|
||||
// if (boat != null)
|
||||
// {
|
||||
// return new DrawningBoat(boat);
|
||||
// }
|
||||
|
||||
// return null;
|
||||
//}
|
||||
|
||||
public static DrawningBoat? CreateDrawningBoat(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
EntityBoat? boat = EntityMotorBoat.CreateEntityMotorBoat(strs);
|
||||
|
||||
DrawningBoat? drawnBoat = null;
|
||||
|
||||
if (boat != null)
|
||||
{
|
||||
EntityMotorBoat? motorBoat = (EntityMotorBoat?)boat;
|
||||
drawnBoat = new DrawningMotorBoat(motorBoat);
|
||||
}
|
||||
else
|
||||
{
|
||||
boat = EntityBoat.CreateEntityBoat(strs);
|
||||
if (boat != null)
|
||||
{
|
||||
drawnBoat = new DrawningBoat(boat);
|
||||
}
|
||||
}
|
||||
|
||||
return drawnBoat;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawningBoat">Сохраняемый объект</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawningBoat drawningBoat)
|
||||
{
|
||||
string[]? array = drawningBoat?.EntityBoat?.GetStringRepresentation();
|
||||
|
||||
if (array == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(_separatorForObject, array);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,6 @@
|
||||
BodyColor = bodyColor;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//---------------Новый основной цвет---------------//
|
||||
////////////////////////////////////////////////////
|
||||
|
||||
/// <summary>
|
||||
/// Новый основной цвет
|
||||
/// </summary>
|
||||
@@ -53,6 +49,30 @@
|
||||
//{
|
||||
// BodyColor = color != null ? color : Color.White;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityBoat? CreateEntityBoat(string[] strs)
|
||||
{
|
||||
if (strs.Length != 4 || strs[0] != nameof(EntityBoat))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EntityBoat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,10 +48,6 @@
|
||||
SportLines = sportLines;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
//---------------Новый дополнительныйй цвет---------------//
|
||||
///////////////////////////////////////////////////////////
|
||||
|
||||
/// <summary>
|
||||
/// Новый дополнительный цвет
|
||||
/// </summary>
|
||||
@@ -63,5 +59,38 @@
|
||||
//{
|
||||
// AdditionalColor = color != null ? color : Color.White;
|
||||
//}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab06 - Получение строк со значениями свойств объекта класса-сущности---------------//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string[] GetStringRepresentation()
|
||||
{
|
||||
//return new[] { nameof(EntityBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name };
|
||||
|
||||
return new[] { nameof(EntityMotorBoat), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
|
||||
AddTwoMotors.ToString(), Sofa.ToString(), SportLines.ToString() };
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//---------------Lab06 - Создание объекта из массива строк---------------//
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityMotorBoat? CreateEntityMotorBoat(string[] strs)
|
||||
{
|
||||
if (strs.Length != 8 || strs[0] != nameof(EntityMotorBoat))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityMotorBoat(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
|
||||
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
16
MotorBoat/MotorBoat/Exceptions/AlreadyExistException.cs
Normal file
16
MotorBoat/MotorBoat/Exceptions/AlreadyExistException.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace MotorBoat.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Объект уже есть в коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class AlreadyExistException: ApplicationException
|
||||
{
|
||||
public AlreadyExistException() : base("Объект уже есть в коллекции") { }
|
||||
public AlreadyExistException(string message) : base(message) { }
|
||||
public AlreadyExistException(string message, Exception exception) : base(message, exception) { }
|
||||
protected AlreadyExistException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace MotorBoat.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) { }
|
||||
}
|
||||
}
|
||||
21
MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs
Normal file
21
MotorBoat/MotorBoat/Exceptions/ObjectNotFoundException.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace MotorBoat.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) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace MotorBoat.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) { }
|
||||
}
|
||||
}
|
||||
120
MotorBoat/MotorBoat/FormBoatCollection.Designer.cs
generated
120
MotorBoat/MotorBoat/FormBoatCollection.Designer.cs
generated
@@ -46,10 +46,19 @@
|
||||
labelCollectionName = new Label();
|
||||
comboBoxSelectorCompany = new ComboBox();
|
||||
pictureBox = new PictureBox();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxTools
|
||||
@@ -59,24 +68,26 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(884, 0);
|
||||
groupBoxTools.Location = new Point(834, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(200, 561);
|
||||
groupBoxTools.Size = new Size(200, 508);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(buttonAddBoat);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
|
||||
panelCompanyTools.Controls.Add(buttonGoToCheck);
|
||||
panelCompanyTools.Controls.Add(buttonRemoveBoat);
|
||||
panelCompanyTools.Dock = DockStyle.Bottom;
|
||||
panelCompanyTools.Location = new Point(3, 384);
|
||||
panelCompanyTools.Location = new Point(3, 301);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(194, 174);
|
||||
panelCompanyTools.Size = new Size(194, 204);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonAddBoat
|
||||
@@ -93,7 +104,7 @@
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(14, 147);
|
||||
buttonRefresh.Location = new Point(14, 118);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(167, 21);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@@ -104,7 +115,7 @@
|
||||
// maskedTextBoxPosition
|
||||
//
|
||||
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
maskedTextBoxPosition.Location = new Point(14, 62);
|
||||
maskedTextBoxPosition.Location = new Point(14, 33);
|
||||
maskedTextBoxPosition.Mask = "00";
|
||||
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
|
||||
maskedTextBoxPosition.Size = new Size(167, 23);
|
||||
@@ -114,7 +125,7 @@
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(14, 118);
|
||||
buttonGoToCheck.Location = new Point(14, 89);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(167, 23);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
@@ -125,7 +136,7 @@
|
||||
// buttonRemoveBoat
|
||||
//
|
||||
buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRemoveBoat.Location = new Point(14, 91);
|
||||
buttonRemoveBoat.Location = new Point(14, 62);
|
||||
buttonRemoveBoat.Name = "buttonRemoveBoat";
|
||||
buttonRemoveBoat.Size = new Size(167, 21);
|
||||
buttonRemoveBoat.TabIndex = 4;
|
||||
@@ -135,7 +146,7 @@
|
||||
//
|
||||
// buttonCreateCompany
|
||||
//
|
||||
buttonCreateCompany.Location = new Point(15, 303);
|
||||
buttonCreateCompany.Location = new Point(15, 272);
|
||||
buttonCreateCompany.Name = "buttonCreateCompany";
|
||||
buttonCreateCompany.Size = new Size(173, 23);
|
||||
buttonCreateCompany.TabIndex = 8;
|
||||
@@ -155,12 +166,12 @@
|
||||
panelStorage.Dock = DockStyle.Top;
|
||||
panelStorage.Location = new Point(3, 19);
|
||||
panelStorage.Name = "panelStorage";
|
||||
panelStorage.Size = new Size(194, 249);
|
||||
panelStorage.Size = new Size(194, 218);
|
||||
panelStorage.TabIndex = 7;
|
||||
//
|
||||
// buttonCollectionDel
|
||||
//
|
||||
buttonCollectionDel.Location = new Point(12, 219);
|
||||
buttonCollectionDel.Location = new Point(12, 189);
|
||||
buttonCollectionDel.Name = "buttonCollectionDel";
|
||||
buttonCollectionDel.Size = new Size(173, 23);
|
||||
buttonCollectionDel.TabIndex = 6;
|
||||
@@ -174,7 +185,7 @@
|
||||
listBoxCollection.ItemHeight = 15;
|
||||
listBoxCollection.Location = new Point(12, 119);
|
||||
listBoxCollection.Name = "listBoxCollection";
|
||||
listBoxCollection.Size = new Size(173, 94);
|
||||
listBoxCollection.Size = new Size(173, 64);
|
||||
listBoxCollection.TabIndex = 5;
|
||||
//
|
||||
// buttonCollectionAdd
|
||||
@@ -231,7 +242,7 @@
|
||||
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxSelectorCompany.FormattingEnabled = true;
|
||||
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
|
||||
comboBoxSelectorCompany.Location = new Point(15, 274);
|
||||
comboBoxSelectorCompany.Location = new Point(15, 243);
|
||||
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
|
||||
comboBoxSelectorCompany.Size = new Size(173, 23);
|
||||
comboBoxSelectorCompany.TabIndex = 0;
|
||||
@@ -239,21 +250,85 @@
|
||||
//
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Dock = DockStyle.Left;
|
||||
pictureBox.Enabled = false;
|
||||
pictureBox.Location = new Point(0, 0);
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(884, 561);
|
||||
pictureBox.Size = new Size(830, 508);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(1034, 24);
|
||||
menuStrip.TabIndex = 0;
|
||||
menuStrip.Text = "menuStrip1";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(48, 20);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
//
|
||||
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
saveToolStripMenuItem.Size = new Size(181, 22);
|
||||
saveToolStripMenuItem.Text = "Сохранение";
|
||||
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// loadToolStripMenuItem
|
||||
//
|
||||
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(181, 22);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByColor.Location = new Point(14, 174);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(167, 21);
|
||||
buttonSortByColor.TabIndex = 8;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonSortByType.Location = new Point(14, 145);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(167, 23);
|
||||
buttonSortByType.TabIndex = 7;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += ButtonSortByType_Click;
|
||||
//
|
||||
// FormBoatCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1084, 561);
|
||||
ClientSize = new Size(1034, 532);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
MainMenuStrip = menuStrip;
|
||||
Name = "FormBoatCollection";
|
||||
Text = "Коллекция лодок";
|
||||
groupBoxTools.ResumeLayout(false);
|
||||
@@ -262,7 +337,10 @@
|
||||
panelStorage.ResumeLayout(false);
|
||||
panelStorage.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -285,5 +363,13 @@
|
||||
private ListBox listBoxCollection;
|
||||
private Button buttonCollectionAdd;
|
||||
private Panel panelCompanyTools;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem saveToolStripMenuItem;
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,6 @@
|
||||
using MotorBoat.CollectionGenericObjects;
|
||||
using MotorBoat.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MotorBoat
|
||||
{
|
||||
@@ -27,13 +19,19 @@ namespace MotorBoat
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormBoatCollection()
|
||||
public FormBoatCollection(ILogger<FormBoatCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -54,36 +52,31 @@ namespace MotorBoat
|
||||
private void ButtonAddBoat_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormBoatConfig form = new();
|
||||
|
||||
//33 минута
|
||||
//////////////////////////////////////////////////////////////////
|
||||
//---------------передать метод в FormBoatConfig---------------//
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
form.AddEvent(SetBoat);
|
||||
|
||||
form.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление автомобиля в коллекцию
|
||||
/// Добавление лодки в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="boat"></param>
|
||||
private void SetBoat(DrawningBoat? boat)
|
||||
private void SetBoat(DrawningBoat boat)
|
||||
{
|
||||
if (_company == null || boat == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + boat)
|
||||
try
|
||||
{
|
||||
bool isSet = _company + boat;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: {boat}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,24 +91,30 @@ namespace MotorBoat
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos)
|
||||
try
|
||||
{
|
||||
bool isRemove = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект с индексом: {pos}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
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)
|
||||
@@ -147,6 +146,11 @@ namespace MotorBoat
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
@@ -167,6 +171,7 @@ namespace MotorBoat
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: Не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -182,6 +187,7 @@ namespace MotorBoat
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Добавлена коллекция: {textBoxCollectionName.Text}", saveFileDialog.FileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -212,13 +218,12 @@ namespace MotorBoat
|
||||
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>
|
||||
@@ -251,5 +256,78 @@ namespace MotorBoat
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по типу
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
CompareBoats(new DrawningBoatCompareByType());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
CompareBoats(new DrawningBoatCompareByColor());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
private void CompareBoats(IComparer<DrawningBoat?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,4 +117,16 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>127, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>62</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -8,6 +8,11 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -23,4 +28,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,3 +1,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
|
||||
namespace MotorBoat
|
||||
{
|
||||
internal static class Program
|
||||
@@ -11,8 +15,25 @@ namespace MotorBoat
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
//Application.Run(new FormMotorBoat());
|
||||
Application.Run(new FormBoatCollection());
|
||||
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBoatCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
15
MotorBoat/MotorBoat/nlog.config
Normal file
15
MotorBoat/MotorBoat/nlog.config
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true" internalLogLevel="Info">
|
||||
|
||||
<targets>
|
||||
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user