5 Commits

25 changed files with 1117 additions and 162 deletions

View File

@@ -27,7 +27,7 @@ public abstract class AbstractCompany
/// </summary> /// </summary>
protected readonly int _pictureHeight; protected readonly int _pictureHeight;
/// <summary> /// <summary>
/// Коллекция автомобилей /// Коллекция автобусов
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningBus>? _collection = null; protected ICollectionGenericObjects<DrawningBus>? _collection = null;
/// <summary> /// <summary>
@@ -47,7 +47,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; ; _collection.MaxCount = GetMaxCount; ;
} }
/// <summary> /// <summary>
@@ -59,7 +59,7 @@ public abstract class AbstractCompany
public static bool operator +(AbstractCompany company, DrawningBus bus) public static bool operator +(AbstractCompany company, DrawningBus bus)
{ {
return company._collection?.Insert(bus) ?? false; return company._collection?.Insert(bus, new DrawiningBusEqutables()) ?? false;
} }
/// <summary> /// <summary>
@@ -104,6 +104,15 @@ public abstract class AbstractCompany
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Добавляемый объект</param>
/// <returns></returns>
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Выход заднего фона /// Выход заднего фона
/// </summary> /// </summary>
@@ -119,4 +128,6 @@ public abstract class AbstractCompany
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
} }

View File

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

View File

@@ -1,4 +1,6 @@
namespace ProjectDoubleDeckerBus.CollectionGenericObjects; using ProjectDoubleDeckerBus.Drawnings;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary> /// <summary>
/// Интерфейс опмсания действия для набора хранимых объектов /// Интерфейс опмсания действия для набора хранимых объектов
@@ -17,7 +19,7 @@ public interface ICollectionGenericObjects<T>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -25,7 +27,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добовляемый объект</param> /// <param name="obj">Добовляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась </returns> /// <returns>true - вставка прошла успешно, false - вставка не удалась </returns>
bool Insert(T obj); bool Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта на конкретную позицию /// Добавление объекта на конкретную позицию
@@ -33,7 +35,7 @@ public interface ICollectionGenericObjects<T>
/// <param name="obj">Добовляемый объект</param> /// <param name="obj">Добовляемый объект</param>
/// <param name="position">Добовляемый объект</param> /// <param name="position">Добовляемый объект</param>
/// <returns>true - вставка прошла успешно, false - вставка не удалась </returns> /// <returns>true - вставка прошла успешно, false - вставка не удалась </returns>
bool Insert(T obj, int position); bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@@ -50,4 +52,24 @@ public interface ICollectionGenericObjects<T>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Позиция</param>
/// <returns>Объект</returns>
void CollectionSort(IComparer<T?>? comparer);
} }

View File

@@ -1,4 +1,8 @@
namespace ProjectDoubleDeckerBus.CollectionGenericObjects; using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System.Linq;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@@ -19,7 +23,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = 14;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -31,44 +49,57 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// Проверка, что указанная позиция находится в пределах допустимого диапазона // Проверяем, что позиция в допустимых границах коллекции
if (!(position >= 0 && position < _collection.Count)) return null; if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
// Возвращаем элемент по указанной позиции // Проверяем, что в данной позиции не хранится null (если допустимы nullable объект
if (_collection[position] == null) throw new ObjectNotFoundException(position);
// Возвращаем объект
return _collection[position]; return _collection[position];
} }
public bool Insert(T obj) public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// Проверка, что количество элементов не превышает максимально допустимое значение if (_collection.Count >= _maxCount) throw new CollectionOverflowException(_maxCount);
if (_collection.Count >= _maxCount) if (comparer != null && _collection.Contains(obj, comparer))
return false; {
throw new CollectionAlreadyExistsException();
// Добавление элемента в конец коллекции }
_collection.Add(obj); _collection.Add(obj);
return true; return true;
} }
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
public bool Insert(T obj, int position)
{ {
// Проверка, что количество элементов не превышает максимально допустимое значение if (comparer != null && _collection.Contains(obj, comparer))
// и позиция находится в допустимом диапазоне {
if ((_collection.Count >= _maxCount) || !(position >= 0 && position < _collection.Count)) throw new CollectionAlreadyExistsException();
return false; }
if (_collection.Count >= _maxCount) throw new CollectionOverflowException(_maxCount);
// Вставка элемента на указанную позицию if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
} }
public bool Remove(int position) public bool Remove(int position)
{ {
// Проверка, что позиция находится в допустимом диапазоне // Проверяем, что позиция находится в пределах коллекции
if (!(position >= 0 && position < _collection.Count)) if (!(position >= 0 && position < _collection.Count)) throw new PositionOutOfCollectionException(position);
return false;
// Удаление элемента по указанной позиции // Удаляем объект по указанной позиции
_collection.RemoveAt(position); _collection.RemoveAt(position);
return true; return true;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?>?comparer)
{
_collection.Sort(comparer);
}
} }

View File

@@ -1,4 +1,8 @@
namespace ProjectDoubleDeckerBus.CollectionGenericObjects; using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
@@ -12,11 +16,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => 14;
public int Count => _collection.Length; public int MaxCount
public int SetMaxCount
{ {
get => _collection.Length;
set set
{ {
if (value > 0) if (value > 0)
@@ -33,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -40,50 +46,54 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
private bool checkposition(int pos) => pos >= 0 && pos < Count;
// Получение элемента по указанной позиции // Получение элемента по указанной позиции
public T? Get(int position) public T? Get(int position)
{ {
// Проверка, что позиция в допустимом диапазоне // Проходим по всей коллекции
if (position < 0 || position >= _collection.Length)
throw new IndexOutOfRangeException("Некорректная позиция.");
// Возвращает элемент массива (может быть null)
return _collection[position];
}
// Вставка элемента на первое доступное свободное место
public bool Insert(T obj)
{
for (int i = 0; i < _collection.Length; i++) for (int i = 0; i < _collection.Length; i++)
{ {
// Если найдено свободное (null) место — вставляем элемент // Если текущий индекс совпадает с запрошенной позицией
if (_collection[i] == null) if (i == position)
{ {
_collection[i] = obj; // Возвращаем элемент из этой позиции
return true; return _collection[position];
} }
} }
// Если свободных мест нет — возвращаем false // Если позиция не найдена (на практике сюда попасть сложно при корректных входных данных)
return false; return default;
}
// Вставка элемента на первое доступное свободное место
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
return Insert(obj, 0, comparer);
} }
// Вставка элемента в указанную позицию, либо в ближайшую свободную // Вставка элемента в указанную позицию, либо в ближайшую свободную
public bool Insert(T obj, int position) public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// Проверка, что позиция в допустимом диапазоне if (!checkposition(position)) throw new PositionOutOfCollectionException(position);
if (position < 0 || position >= _collection.Length) if (comparer != null)
return false; {
foreach (var item in _collection)
{
if (item != null && comparer.Equals(item, obj))
{
throw new CollectionAlreadyExistsException();
}
}
}
// Если позиция свободна — вставляем туда
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return true; return true;
} }
// Поиск ближайшего свободного места после указанной позиции for (int i = position + 1; i < Count; i++)
for (int i = position + 1; i < _collection.Length; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@@ -91,9 +101,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return true; return true;
} }
} }
for (int i = 0; i < position; i++)
// Поиск ближайшего свободного места до указанной позиции
for (int i = position - 1; i >= 0; i--)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@@ -101,20 +109,35 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return true; return true;
} }
} }
throw new CollectionOverflowException(Count);
// Если свободных мест не найдено — возвращаем false
return false;
} }
// Удаление элемента по указанной позиции // Удаление элемента по указанной позиции
public bool Remove(int position) public bool Remove(int position)
{ {
// Проверка, что позиция в допустимом диапазоне // Проверяем валидность позиции
if (position < 0 || position >= _collection.Length) if (!checkposition(position)) throw new PositionOutOfCollectionException(position);
return false;
// Удаляем элемент (присваиваем null) // Проверяем наличие объекта
if (_collection[position] == null) throw new ObjectNotFoundException(position);
// Удаляем (обнуляем)
_collection[position] = null; _collection[position] = null;
return true; return true;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?>? comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@@ -1,28 +1,47 @@
namespace ProjectDoubleDeckerBus.CollectionGenericObjects; using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System.Text;
namespace ProjectDoubleDeckerBus.CollectionGenericObjects;
/// <summary> /// <summary>
/// Класс-хранилище коллекций /// Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningBus
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@@ -32,28 +51,20 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// Проверка: если имя null или уже существует в словаре — ничего не делаем CollectionInfo info = new CollectionInfo(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(name)) if (name == null || info == null || _storages.ContainsKey(info))
{ return; } {
return;
// В зависимости от типа коллекции, создаётся соответствующий объект и добавляется в словарь }
switch (collectionType) switch (info.CollectionType)
{ {
case CollectionType.None:
// Тип None — ничего не делаем
return;
case CollectionType.Massive: case CollectionType.Massive:
// Добавление массива в качестве коллекции _storages.Add(info, new MassiveGenericObjects<T>());
break;
_storages[name] = new MassiveGenericObjects<T>();
return;
case CollectionType.List: case CollectionType.List:
// Добавление списка в качестве коллекции _storages.Add(info, new ListGenericObjects<T>());
break;
_storages[name] = new ListGenericObjects<T>(); default:
return; return;
} }
} }
@@ -64,9 +75,12 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
// Удаление коллекции, если она существует if (name == null) return;
if (_storages.ContainsKey(name))
_storages.Remove(name); var info = new CollectionInfo(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(info)) return;
_storages.Remove(info);
} }
/// <summary> /// <summary>
@@ -78,13 +92,130 @@ public class StorageCollection<T>
{ {
get get
{ {
//Получения объекта if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)))
if (name == null || !_storages.ContainsKey(name)) {
{ return null; } return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)];
return _storages[name]; }
return null;
} }
} }
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StreamWriter writer = new StreamWriter(filename);
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new StringBuilder();
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.WriteLine(sb.ToString());
}
writer.Close();
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
StreamReader reader = new StreamReader(filename);
if (reader == null)
{
return false;
}
if (!reader.ReadLine()?.Equals(_collectionKey) ?? true) return false;
_storages.Clear();
while (!reader.EndOfStream)
{
string[] record = reader.ReadLine()?.Trim().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries) ?? new string[] { };
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("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingBus() is T gun)
{
try
{
if (!collection.Insert(gun))
{
throw new Exception("Объект не удалось добавить в коллекцию " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@@ -0,0 +1,76 @@
using ProjectDoubleDeckerBus.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDoubleDeckerBus.Drawnings;
public class DrawiningBusEqutables : IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return false;
}
if (y == null || y.EntityBus == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningDoubleDeckerBus && y is DrawningDoubleDeckerBus)
{
EntityDoubleDeckerBus _x = (EntityDoubleDeckerBus)x.EntityBus;
EntityDoubleDeckerBus _y = (EntityDoubleDeckerBus)x.EntityBus;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.SecondFloor != _y.SecondFloor)
{
return false;
}
if (_x.Ladder != _y.Ladder)
{
return false;
}
if (_x.Section != _y.Section)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@@ -1,19 +1,17 @@
using ProjectDoubleDeckerBus.Entities; using ProjectDoubleDeckerBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDoubleDeckerBus.Drawnings; namespace ProjectDoubleDeckerBus.Drawnings;
public class DrawningBus public class DrawningBus
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Класс-сущность
/// </summary> /// </summary>
public EntityBus? EntityBus { get; protected set; } public EntityBus? EntityBus { get; protected set; }
private EntityBus bus;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
@@ -98,6 +96,11 @@ public class DrawningBus
_pictureHeight = drawningBusHeight; _pictureHeight = drawningBusHeight;
} }
public DrawningBus(EntityBus bus)
{
EntityBus = bus;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
@@ -107,11 +110,22 @@ public class DrawningBus
/// <returns>true границы заданы, false проверка не пройдена, нельзя разместить объект в этих размерах</returns> /// <returns>true границы заданы, false проверка не пройдена, нельзя разместить объект в этих размерах</returns>
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена if (_drawningBusWidth < width && _drawningBusHeight < height)
_pictureWidth = width; {
_pictureHeight = height; _pictureWidth = width;
return true; _pictureHeight = height;
if (_startPosX.HasValue && _startPosY.HasValue)
{
SetPosition(_startPosX.Value, _startPosY.Value);
}
return true;
}
else
{
return false;
}
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
@@ -125,10 +139,24 @@ public class DrawningBus
return; return;
} }
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
// то надо изменить координаты, чтобы он оставался в этих границах {
_startPosX = x; return;
_startPosY = y; }
if (x > 0 && y > 0 && x + _drawningBusWidth < _pictureWidth
&& y + _drawningBusHeight < _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
else
{
Random rnd = new();
_startPosX = rnd.Next(0, _pictureWidth.Value -
_drawningBusWidth);
_startPosY = rnd.Next(0, _pictureHeight.Value -
_drawningBusHeight);
}
} }
public bool MoveTransport(DirectionType direction) public bool MoveTransport(DirectionType direction)

View File

@@ -0,0 +1,36 @@
using ProjectDoubleDeckerBus.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDoubleDeckerBus.Drawnings;
public class DrawningBusCompareByColor : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
var bodyСolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodyСolorCompare != 0)
{
return bodyСolorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDoubleDeckerBus.Drawnings;
internal class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return 1;
}
if (y == null || y.EntityBus == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@@ -7,6 +7,10 @@ namespace ProjectDoubleDeckerBus.Drawnings;
/// </summary> /// </summary>
public class DrawningDoubleDeckerBus : DrawningBus public class DrawningDoubleDeckerBus : DrawningBus
{ {
public DrawningDoubleDeckerBus(EntityBus bus) : base(bus)
{
EntityBus = bus;
}
/// <summary> /// <summary>

View File

@@ -0,0 +1,53 @@

using ProjectDoubleDeckerBus.Entities;
namespace ProjectDoubleDeckerBus.Drawnings;
public static class ExtentionDrawningBus
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawingBus(this string info)
{
string[] str = info.Split(_separatorForObject);
EntityBus? bus = EntityDoubleDeckerBus.CreateEntityDoubleDeckerBus(str);
if (bus != null)
{
return new DrawningDoubleDeckerBus(bus);
}
bus = EntityBus.CreateEntityBus(str);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

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

View File

@@ -1,4 +1,6 @@
namespace ProjectDoubleDeckerBus.Entities; using System.Net.NetworkInformation;
namespace ProjectDoubleDeckerBus.Entities;
/// <summary> /// <summary>
/// Двухэтажный автобус /// Двухэтажный автобус
@@ -54,6 +56,23 @@ public class EntityDoubleDeckerBus : EntityBus
Ladder = ladder; Ladder = ladder;
Section = section; Section = section;
} }
public override string[] GetStringRepresentation()
{
return new string[] { nameof(EntityDoubleDeckerBus), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, SecondFloor.ToString(), Ladder.ToString(), Section.ToString() };
}
public static EntityDoubleDeckerBus? CreateEntityDoubleDeckerBus(string[] str)
{
if (str.Length == 0 || str[0] != nameof(EntityDoubleDeckerBus)) return null;
return new EntityDoubleDeckerBus(
Convert.ToInt32(str[1]),
Convert.ToDouble(str[2]),
Color.FromName(str[3]),
Color.FromName(str[4]),
Convert.ToBoolean(str[5]),
Convert.ToBoolean(str[6]),
Convert.ToBoolean(str[7])
);
}
} }

View File

@@ -0,0 +1,15 @@
using ProjectDoubleDeckerBus.CollectionGenericObjects;
using System.Runtime.Serialization;
namespace ProjectDoubleDeckerBus.Exceptions;
[Serializable]
internal class CollectionAlreadyExistsException : ApplicationException
{
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base("В коллекции уже есть такой элемент: " + collectionInfo) { }
public CollectionAlreadyExistsException() : base("В коллекции уже есть такой элемент") { }
public CollectionAlreadyExistsException(string message) : base(message) { }
public CollectionAlreadyExistsException(string message, Exception exception) : base(message, exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@@ -0,0 +1,21 @@

using System.Runtime.Serialization;
namespace ProjectDoubleDeckerBus.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,19 @@

using System.Runtime.Serialization;
namespace ProjectDoubleDeckerBus.Exceptions;
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,19 @@

using System.Runtime.Serialization;
namespace ProjectDoubleDeckerBus.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -46,10 +46,19 @@ partial class FormBusCollection
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -59,31 +68,33 @@ partial class FormBusCollection
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(727, 0); groupBoxTools.Location = new Point(608, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(173, 608); groupBoxTools.Size = new Size(173, 651);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddBus); panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveBus); panelCompanyTools.Controls.Add(buttonRemoveBus);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 314); panelCompanyTools.Location = new Point(3, 313);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(167, 291); panelCompanyTools.Size = new Size(167, 335);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
// //
// buttonAddBus // buttonAddBus
// //
buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddBus.Location = new Point(3, 10); buttonAddBus.Location = new Point(3, 3);
buttonAddBus.Name = "buttonAddBus"; buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(161, 44); buttonAddBus.Size = new Size(161, 44);
buttonAddBus.TabIndex = 1; buttonAddBus.TabIndex = 1;
@@ -94,7 +105,7 @@ partial class FormBusCollection
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 239); buttonRefresh.Location = new Point(3, 182);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(161, 44); buttonRefresh.Size = new Size(161, 44);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@@ -104,7 +115,7 @@ partial class FormBusCollection
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(5, 110); maskedTextBoxPosition.Location = new Point(8, 53);
maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(153, 23); maskedTextBoxPosition.Size = new Size(153, 23);
@@ -114,7 +125,7 @@ partial class FormBusCollection
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 189); buttonGoToCheck.Location = new Point(3, 132);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(161, 44); buttonGoToCheck.Size = new Size(161, 44);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@@ -125,7 +136,7 @@ partial class FormBusCollection
// buttonRemoveBus // buttonRemoveBus
// //
buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveBus.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBus.Location = new Point(3, 139); buttonRemoveBus.Location = new Point(3, 82);
buttonRemoveBus.Name = "buttonRemoveBus"; buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(161, 44); buttonRemoveBus.Size = new Size(161, 44);
buttonRemoveBus.TabIndex = 4; buttonRemoveBus.TabIndex = 4;
@@ -240,19 +251,83 @@ partial class FormBusCollection
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(727, 608); pictureBox.Size = new Size(608, 651);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(781, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(173, 22);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(173, 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(3, 282);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(161, 44);
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(3, 232);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(161, 44);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormBusCollection // FormBusCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(900, 608); ClientSize = new Size(781, 675);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormBusCollection"; Name = "FormBusCollection";
Text = "Коллекция"; Text = "Коллекция";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -261,7 +336,10 @@ partial class FormBusCollection
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -284,4 +362,12 @@ partial class FormBusCollection
private TextBox textBoxCollectionName; private TextBox textBoxCollectionName;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }

View File

@@ -1,5 +1,8 @@
using ProjectDoubleDeckerBus.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectDoubleDeckerBus.CollectionGenericObjects;
using ProjectDoubleDeckerBus.Drawnings; using ProjectDoubleDeckerBus.Drawnings;
using ProjectDoubleDeckerBus.Exceptions;
using System.Windows.Forms;
namespace ProjectDoubleDeckerBus; namespace ProjectDoubleDeckerBus;
@@ -18,13 +21,17 @@ public partial class FormBusCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Логгер
/// </summary> /// </summary>
public FormBusCollection() public FormBusCollection(ILogger<FormBusCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
panelCompanyTools.Enabled = false;
_logger = logger;
} }
/// <summary> /// <summary>
@@ -54,21 +61,36 @@ public partial class FormBusCollection : Form
/// Добавление автобуса в коллекцию /// Добавление автобуса в коллекцию
/// </summary> /// </summary>
/// <param name="bus"></param> /// <param name="bus"></param>
private void SetBus(DrawningBus bus) private void SetBus(DrawningBus bus)
{ {
if (_company == null || bus == null) if (_company == null)
{ {
MessageBox.Show("_company == null");
return; return;
} }
if (_company + bus)
if (bus == null)
{ {
MessageBox.Show("bus == null");
return;
}
try
{
bool addingObject = (_company + bus);
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (CollectionAlreadyExistsException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
@@ -79,7 +101,6 @@ public partial class FormBusCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e) private void ButtonRemoveBus_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{ {
return; return;
@@ -91,14 +112,17 @@ public partial class FormBusCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos) try
{ {
Object decrementObject = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален по позиции {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); _logger.LogError($"Удаление объекта в позиции {pos} ");
MessageBox.Show(ex.Message);
} }
} }
@@ -109,17 +133,16 @@ public partial class FormBusCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e) private void ButtonGoToCheck_Click(object sender, EventArgs e)
{ {
if (_company == null) if (_company == null)
{ {
return; return;
} }
DrawningBus? car = null; DrawningBus? bus = null;
int counter = 100; int counter = 100;
while (car == null) while (bus == null)
{ {
car = _company.GetRandomObject(); bus = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@@ -127,18 +150,19 @@ public partial class FormBusCollection : Form
} }
} }
if (car == null) if (bus == null)
{ {
return; return;
} }
FormDoubleDeckerBus form = new() FormDoubleDeckerBus form = new()
{ {
SetBus = car SetBus = bus
}; };
form.ShowDialog(); form.ShowDialog();
} }
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
/// </summary> /// </summary>
@@ -164,6 +188,7 @@ public partial class FormBusCollection : Form
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return; return;
} }
@@ -178,9 +203,11 @@ public partial class FormBusCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RefreshListBoxItems(); RefreshListBoxItems();
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
@@ -188,16 +215,19 @@ public partial class FormBusCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e) private void ButtonCollectionDel_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) if (listBoxCollection.SelectedItems.Count == 0)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Нет выбранных элементов");
_logger.LogWarning("Удаление невыбранной коллекции");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Подтвердите удаление коллекции" + listBoxCollection.SelectedItem?.ToString(), "", MessageBoxButtons.YesNo) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty); _storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString());
_logger.LogInformation($"Удалена коллекция: {name}");
RefreshListBoxItems(); RefreshListBoxItems();
} }
@@ -212,7 +242,7 @@ public partial class FormBusCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@@ -227,15 +257,18 @@ public partial class FormBusCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e) private void ButtonCreateCompany_Click(object sender, EventArgs e)
{ {
if(listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании c невыбранной коллекции");
return; return;
} }
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
ICollectionGenericObjects<DrawningBus>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningBus>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return; return;
} }
@@ -249,7 +282,78 @@ public partial class FormBusCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RefreshListBoxItems(); RefreshListBoxItems();
} }
/// <summary>
/// Обрвботка нажатие "Cохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатие "Загрузить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
RefreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if(_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }

View File

@@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 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>
</root> </root>

View File

@@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectDoubleDeckerBus namespace ProjectDoubleDeckerBus
{ {
internal static class Program internal static class Program
@@ -8,10 +16,51 @@ namespace ProjectDoubleDeckerBus
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, try
// see https://aka.ms/applicationconfiguration. {
ApplicationConfiguration.Initialize(); ConfigureLogging();
Application.Run(new FormBusCollection());
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using var serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
}
catch (Exception ex)
{
// <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
MessageBox.Show($"<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: {ex.Message}", "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Fatal(ex, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureLogging()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("serilog.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormBusCollection>();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders(); // <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
loggingBuilder.SetMinimumLevel(LogLevel.Information);
loggingBuilder.AddSerilog();
});
} }
} }
} }

View File

@@ -8,6 +8,19 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.6" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.5.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="System.IO" Version="4.3.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +36,13 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Lokolog-.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithThreadId" ],
"Properties": {
"Application": "PrLaba1"
}
}
}