Compare commits

..

No commits in common. "a60364e2a07fce3a1ccad0805d4cea7645113004" and "2fd3db0774756b8d15c1a2dff92f1bfb04b4d000" have entirely different histories.

31 changed files with 196 additions and 1878 deletions

View File

@ -1,5 +1,4 @@
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -36,7 +35,7 @@ namespace ProjectTrain.CollectionGenericObjects
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -50,18 +49,18 @@ namespace ProjectTrain.CollectionGenericObjects
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.MaxCount = GetMaxCount; _collection.SetMaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
/// Перегрузка оператора сложения для класса /// Перегрузка оператора сложения для класса
/// </summary> /// </summary>
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="train">Добавляемый объект</param> /// <param name="сruiser">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrain train) public static int operator +(AbstractCompany company, DrawningTrain сruiser)
{ {
return company._collection.Insert(train, new DrawiningTrainEqutables()); return company._collection.Insert(сruiser);
} }
/// <summary> /// <summary>
@ -97,26 +96,11 @@ namespace ProjectTrain.CollectionGenericObjects
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
try DrawningTrain? obj = _collection?.Get(i);
{ obj?.DrawTransport(graphics);
DrawningTrain? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
} }
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTrain?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@ -1,75 +0,0 @@
namespace ProjectTrain.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,6 +1,4 @@
using ProjectTrain.Drawnings; namespace ProjectTrain.CollectionGenericObjects
namespace ProjectTrain.CollectionGenericObjects
{ {
/// <summary> /// <summary>
/// Интерфейс описания действий для набора хранимых объектов /// Интерфейс описания действий для набора хранимых объектов
@ -16,23 +14,20 @@ namespace ProjectTrain.CollectionGenericObjects
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int MaxCount { get; set; } int SetMaxCount { set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, IEqualityComparer<DrawningTrain?>? comparer = null); int Insert(T obj);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position, IEqualityComparer<DrawningTrain?>? comparer = null); int Insert(T obj, int position);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
@ -45,23 +40,6 @@ namespace ProjectTrain.CollectionGenericObjects
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
} }
} }

View File

@ -1,8 +1,4 @@
using ProjectTrain.Drawnings; namespace ProjectTrain.CollectionGenericObjects
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects
{ {
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -20,20 +16,7 @@ namespace ProjectTrain.CollectionGenericObjects
/// </summary> /// </summary>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int MaxCount public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -44,43 +27,26 @@ namespace ProjectTrain.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO выброc позиций, если выход за границы массива if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj, IEqualityComparer<DrawningTrain?>? comparer = null) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выбром позиций, если переполнение
// TODO выброc позиций, если такой объект есть в коллекции
// TODO вставка в конец набора // TODO вставка в конец набора
for (int i = 0; i < Count; i++) if (Count == _maxCount) return -1;
{
if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position, IEqualityComparer<DrawningTrain?>? comparer = null) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO проверка, что не превышено максимальное количество элементов
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции // TODO проверка позиции
// TODO вставка по позиции // TODO вставка по позиции
for (int i = 0; i < Count; i++) if (Count == _maxCount) return -1;
{ if (position >= Count || position < 0) return -1;
if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i);
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@ -89,26 +55,11 @@ namespace ProjectTrain.CollectionGenericObjects
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO удаление объекта из списка // TODO удаление объекта из списка
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) return null;
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }
} }

View File

@ -1,7 +1,5 @@
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using ProjectTrain.Exceptions;
using ProjectTrain.CollectionGenericObjects; using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -17,12 +15,8 @@ namespace ProjectTrain.CollectionGenericObjects
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int MaxCount public int SetMaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -39,8 +33,6 @@ namespace ProjectTrain.CollectionGenericObjects
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -51,115 +43,74 @@ namespace ProjectTrain.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO выбром позиций, если выход за границы массива if (position >= _collection.Length || position < 0)
// TODO выбром позиций, если объект пустой { return null; }
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj, IEqualityComparer<DrawningTrain?>? comparer = null) public int Insert(T obj)
{ {
// TODO вставка в свободное место набора // TODO вставка в свободное место набора
// TODO выброc позиций, если переполнение int index = 0;
// TODO выброc позиций, если такой объект есть в коллекции while (index < _collection.Length)
for (int i = 0; i < Count; i++)
{ {
if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i); if (_collection[index] == null)
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{ {
_collection[i] = obj; _collection[index] = obj;
return i; return index;
} }
}
throw new CollectionOverflowException(Count); index++;
}
return -1;
} }
public int Insert(T obj, int position, IEqualityComparer<DrawningTrain?>? comparer = null) public int Insert(T obj, int position)
{ {
// TODO выброc позиций, если такой объект есть в коллекции
// TODO проверка позиции // TODO проверка позиции
// TODO выбром позиций, если выход за границы массива
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то // TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда // ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до // если нет после, ищем до
// TODO выбром позиций, если переполнение
// TODO вставка // TODO вставка
for (int i = 0; i < Count; i++) if (position >= _collection.Length || position < 0)
{ { return -1; }
if (comparer.Equals((_collection[i] as DrawningTrain), (obj as DrawningTrain))) throw new ObjectAlreadyInCollectionException(i);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
} }
int index;
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); for (index = position + 1; index < _collection.Length; ++index)
if (_collection[position] != null)
{ {
bool pushed = false; if (_collection[index] == null)
for (int index = position + 1; index < Count; index++)
{ {
if (_collection[index] == null) _collection[position] = obj;
{ return position;
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
} }
} }
_collection[position] = obj; for (index = position - 1; index >= 0; --index)
return position; {
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
// TODO выбром позиций, если выход за границы массива if (position >= _collection.Length || position < 0)
// TODO выбром позиций, если объект пустой { return null; }
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); T obj = _collection[position];
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
}
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,48 +1,27 @@
using ProjectTrain.Drawnings; namespace ProjectTrain.CollectionGenericObjects
using ProjectTrain.Exceptions;
using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.Exceptions;
using System.Text;
namespace ProjectTrain.CollectionGenericObjects
{ {
// Класс-хранилище коллекций // Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningTrain where T : class
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@ -50,40 +29,29 @@ namespace ProjectTrain.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(CollectionInfo name) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом // TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
if (name == null || _storages.ContainsKey(name)) if (_storages.ContainsKey(name)) return;
{
return;
}
if (name.CollectionType == CollectionType.Massive) if (collectionType == CollectionType.None) return;
{ else if (collectionType == CollectionType.Massive)
_storages.Add(name, new MassiveGenericObjects<T>()); _storages[name] = new MassiveGenericObjects<T>();
} else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
if (name.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(CollectionInfo name) public void DelCollection(string name)
{ {
// TODO Прописать логику для удаления коллекции // TODO Прописать логику для удаления коллекции
if (name == null || !_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
{ _storages.Remove(name);
return;
}
_storages.Remove(name);
} }
/// <summary> /// <summary>
@ -91,144 +59,15 @@ namespace ProjectTrain.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[CollectionInfo name] public ICollectionGenericObjects<T>? this[string name]
{ {
get get
{ {
// TODO Продумать логику получения объекта // TODO Продумать логику получения объекта
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(name))
{
return _storages[name]; return _storages[name];
}
return null; return null;
} }
} }
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
}
}
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
throw new FormatException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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?.CreateDrawningTrain() is T train)
{
try
{
if (collection.Insert(train, new DrawiningTrainEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }
} }

View File

@ -1,5 +1,4 @@
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using ProjectTrain.Exceptions;
namespace ProjectTrain.CollectionGenericObjects namespace ProjectTrain.CollectionGenericObjects
{ {
@ -42,21 +41,18 @@ namespace ProjectTrain.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null)
try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
} }
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth < width - 1) if (curWidth < width - 1)
curWidth++; curWidth++;
else else
{ {
curWidth = 0; curWidth = 0;
curHeight++; curHeight ++;
} }
if (curHeight >= height) if (curHeight >= height)

View File

@ -1,54 +0,0 @@
using System.Diagnostics.CodeAnalysis;
namespace ProjectTrain.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningTrainEqutables : IEqualityComparer<DrawningTrain?>
{
public bool Equals(DrawningTrain? x, DrawningTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return false;
}
if (y == null || y.EntityTrain == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrain.Speed != y.EntityTrain.Speed)
{
return false;
}
if (x.EntityTrain.Weight != y.EntityTrain.Weight)
{
return false;
}
if (x.EntityTrain.BodyColor != y.EntityTrain.BodyColor)
{
return false;
}
if (x is DrawningElectroTrain && y is DrawningElectroTrain)
{
// TODO доделать логику сравнения дополнительных параметров
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrain obj)
{
return obj.GetHashCode();
}
}

View File

@ -22,13 +22,6 @@ namespace ProjectTrain.Drawnings
{ {
EntityTrain = new EntityElectroTrain(speed, weight, bodyColor, additionalColor, horns, electro, headlight); EntityTrain = new EntityElectroTrain(speed, weight, bodyColor, additionalColor, horns, electro, headlight);
} }
public DrawningElectroTrain(EntityTrain entityTrain)
{
if (entityTrain != null)
{
EntityTrain = entityTrain;
}
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
@ -53,14 +46,13 @@ namespace ProjectTrain.Drawnings
base.DrawTransport(g); base.DrawTransport(g);
if (entityElectroTrain.Horns) g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value, _startPosX.Value + 47, _startPosY.Value - 5);
{ g.DrawLine(pen, _startPosX.Value + 47, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value - 10);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value, _startPosX.Value + 47, _startPosY.Value - 5); g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value - 10, _startPosX.Value + 87, _startPosY.Value - 5);
g.DrawLine(pen, _startPosX.Value + 47, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value - 10); g.DrawLine(pen, _startPosX.Value + 87, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value);
g.DrawLine(pen, _startPosX.Value + 67, _startPosY.Value - 10, _startPosX.Value + 87, _startPosY.Value - 5);
g.DrawLine(pen, _startPosX.Value + 87, _startPosY.Value - 5, _startPosX.Value + 67, _startPosY.Value);
}
if (entityElectroTrain.Electro) if (entityElectroTrain.Electro)
{ {

View File

@ -58,7 +58,7 @@ public class DrawningTrain
/// <summary> /// <summary>
/// Пустой онструктор /// Пустой онструктор
/// </summary> /// </summary>
public DrawningTrain() private DrawningTrain()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
@ -87,15 +87,6 @@ public class DrawningTrain
_pictureHeight = drawningCarHeight; _pictureHeight = drawningCarHeight;
} }
/// <summary>
/// конструктор
/// </summary>
/// <param name="entityTrain"></param>
public DrawningTrain(EntityTrain entityTrain)
{
EntityTrain = entityTrain;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </summary>
@ -215,7 +206,7 @@ public class DrawningTrain
//Brush additionalBrush = new SolidBrush(entityElectroTrain.AdditionalColor); //Brush additionalBrush = new SolidBrush(entityElectroTrain.AdditionalColor);
Brush bodyBrush = new SolidBrush(EntityTrain.BodyColor); Brush bodyBrush = new SolidBrush(EntityTrain.BodyColor);
//границы поезда //границы круисера
Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) }; Point[] points = { new Point(_startPosX.Value + 5, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value), new Point(_startPosX.Value + 140, _startPosY.Value + 20), new Point(_startPosX.Value, _startPosY.Value + 20) };
//g.FillPolygon(additionalBrush, points); //g.FillPolygon(additionalBrush, points);

View File

@ -1,34 +0,0 @@
using ProjectTrain.Entities;
namespace ProjectTrain.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTrainCompareByColor : IComparer<DrawningTrain?>
{
public int Compare(DrawningTrain? x, DrawningTrain? y)
{
// TODO прописать логику сравения по цветам, скорости, весу
if (x == null || x.EntityTrain == null)
{
return 1;
}
if (y == null || y.EntityTrain == null)
{
return -1;
}
var bodycolorCompare = x.EntityTrain.BodyColor.Name.CompareTo(y.EntityTrain.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
}

View File

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

View File

@ -1,50 +0,0 @@
using ProjectTrain.Entities;
namespace ProjectTrain.Drawnings
{
public static class ExtentionDrawningTrain
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrain? CreateDrawningTrain(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrain? train = EntityElectroTrain.CreateEntityElectroTrain(strs);
if (train != null)
{
return new DrawningElectroTrain(train);
}
train = EntityTrain.CreateEntityTrain(strs);
if (train != null)
{
return new DrawningTrain(train);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTrain">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrain drawningTrain)
{
string[]? array = drawningTrain?.EntityTrain?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
}

View File

@ -5,27 +5,19 @@
/// <summary> /// <summary>
/// Признак (опция) наличие рогов /// Признак (опция) наличие рогов
/// </summary> /// </summary>
public bool Horns { get; private set; } public bool Horns { get; private set; }
/// <summary> /// <summary>
/// Признак (опция) наличие электробатареи /// Признак (опция) наличие электробатареи
/// </summary> /// </summary>
public bool Electro { get; private set; } public bool Electro { get; private set; }
/// <summary> /// <summary>
/// Признак (опция) наличие фары /// Признак (опция) наличие фары
/// </summary> /// </summary>
public bool Headlight { get; private set; } public bool Headlight { get; private set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
public EntityElectroTrain(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight) : base(speed, weight, bodyColor) public EntityElectroTrain(int speed, double weight, Color bodyColor, Color additionalColor, bool horns, bool electro, bool headlight) : base(speed, weight, bodyColor)
{ {
@ -34,30 +26,5 @@
Electro = electro; Electro = electro;
Headlight = headlight; Headlight = headlight;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Horns.ToString(), Electro.ToString(), Headlight.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrain? CreateEntityElectroTrain(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityTrain))
{
return null;
}
return new EntityElectroTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
}
} }
} }

View File

@ -18,10 +18,7 @@ public class EntityTrain
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public void setBodyColor(Color color)
{
BodyColor = color;
}
/// <summary> /// <summary>
/// Шаг перемещения автомобиля /// Шаг перемещения автомобиля
/// </summary> /// </summary>
@ -38,28 +35,4 @@ public class EntityTrain
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrain? CreateEntityTrain(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrain))
{
return null;
}
return new EntityTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.Exceptions;
[Serializable]
internal class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int index) : base("Такой объект уже присутствует в коллекции. Позиция " + index) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTrain.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,394 +0,0 @@
namespace ProjectTrain
{
partial class FormTrainConfing
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBoxConfing = new GroupBox();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxHeadlight = new CheckBox();
checkBoxElectro = new CheckBox();
checkBoxHorns = new CheckBox();
numericUpDownWeight = new NumericUpDown();
labelWeight = new Label();
numericUpDownSpeed = new NumericUpDown();
labelSpeed = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
panelObject = new Panel();
labelAdditionalColor = new Label();
labelBodyColor = new Label();
groupBoxConfing.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelObject.SuspendLayout();
SuspendLayout();
//
// groupBoxConfing
//
groupBoxConfing.Controls.Add(groupBoxColors);
groupBoxConfing.Controls.Add(checkBoxHeadlight);
groupBoxConfing.Controls.Add(checkBoxElectro);
groupBoxConfing.Controls.Add(checkBoxHorns);
groupBoxConfing.Controls.Add(numericUpDownWeight);
groupBoxConfing.Controls.Add(labelWeight);
groupBoxConfing.Controls.Add(numericUpDownSpeed);
groupBoxConfing.Controls.Add(labelSpeed);
groupBoxConfing.Controls.Add(labelModifiedObject);
groupBoxConfing.Controls.Add(labelSimpleObject);
groupBoxConfing.Dock = DockStyle.Left;
groupBoxConfing.Location = new Point(0, 0);
groupBoxConfing.Margin = new Padding(3, 2, 3, 2);
groupBoxConfing.Name = "groupBoxConfing";
groupBoxConfing.Padding = new Padding(3, 2, 3, 2);
groupBoxConfing.Size = new Size(548, 196);
groupBoxConfing.TabIndex = 0;
groupBoxConfing.TabStop = false;
groupBoxConfing.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(286, 20);
groupBoxColors.Margin = new Padding(3, 2, 3, 2);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Padding = new Padding(3, 2, 3, 2);
groupBoxColors.Size = new Size(245, 116);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(190, 72);
panelPurple.Margin = new Padding(3, 2, 3, 2);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(42, 35);
panelPurple.TabIndex = 1;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(130, 72);
panelBlack.Margin = new Padding(3, 2, 3, 2);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(42, 35);
panelBlack.TabIndex = 1;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(72, 72);
panelGray.Margin = new Padding(3, 2, 3, 2);
panelGray.Name = "panelGray";
panelGray.Size = new Size(42, 35);
panelGray.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(15, 72);
panelWhite.Margin = new Padding(3, 2, 3, 2);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(42, 35);
panelWhite.TabIndex = 1;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(190, 23);
panelYellow.Margin = new Padding(3, 2, 3, 2);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(42, 35);
panelYellow.TabIndex = 1;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(130, 23);
panelBlue.Margin = new Padding(3, 2, 3, 2);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(42, 35);
panelBlue.TabIndex = 1;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(72, 23);
panelGreen.Margin = new Padding(3, 2, 3, 2);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(42, 35);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(15, 23);
panelRed.Margin = new Padding(3, 2, 3, 2);
panelRed.Name = "panelRed";
panelRed.Size = new Size(42, 35);
panelRed.TabIndex = 0;
//
// checkBoxHeadlight
//
checkBoxHeadlight.AutoSize = true;
checkBoxHeadlight.Location = new Point(5, 163);
checkBoxHeadlight.Margin = new Padding(3, 2, 3, 2);
checkBoxHeadlight.Name = "checkBoxHeadlight";
checkBoxHeadlight.Size = new Size(168, 19);
checkBoxHeadlight.TabIndex = 8;
checkBoxHeadlight.Text = "Признак наличие фонаря";
checkBoxHeadlight.UseVisualStyleBackColor = true;
checkBoxHeadlight.CheckedChanged += checkBoxHeadlight_CheckedChanged;
//
// checkBoxElectro
//
checkBoxElectro.AutoSize = true;
checkBoxElectro.Location = new Point(5, 127);
checkBoxElectro.Margin = new Padding(3, 2, 3, 2);
checkBoxElectro.Name = "checkBoxElectro";
checkBoxElectro.Size = new Size(170, 19);
checkBoxElectro.TabIndex = 7;
checkBoxElectro.Text = "Признак наличие батареи";
checkBoxElectro.UseVisualStyleBackColor = true;
//
// checkBoxHorns
//
checkBoxHorns.AutoSize = true;
checkBoxHorns.Location = new Point(5, 92);
checkBoxHorns.Margin = new Padding(3, 2, 3, 2);
checkBoxHorns.Name = "checkBoxHorns";
checkBoxHorns.Size = new Size(158, 19);
checkBoxHorns.TabIndex = 6;
checkBoxHorns.Text = "Признак наличие рогов";
checkBoxHorns.UseVisualStyleBackColor = true;
checkBoxHorns.CheckedChanged += checkBoxHorns_CheckedChanged;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(82, 51);
numericUpDownWeight.Margin = new Padding(3, 2, 3, 2);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(100, 23);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(24, 52);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 4;
labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(82, 24);
numericUpDownSpeed.Margin = new Padding(3, 2, 3, 2);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(100, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(10, 24);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 2;
labelSpeed.Text = "Скорость:";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(416, 152);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(115, 34);
labelModifiedObject.TabIndex = 1;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += labelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(286, 152);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(114, 34);
labelSimpleObject.TabIndex = 0;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelObject_MouseDown;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(10, 42);
pictureBoxObject.Margin = new Padding(3, 2, 3, 2);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(160, 94);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(553, 159);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(82, 22);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(648, 159);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelAdditionalColor);
panelObject.Controls.Add(labelBodyColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(553, 9);
panelObject.Margin = new Padding(3, 2, 3, 2);
panelObject.Name = "panelObject";
panelObject.Size = new Size(179, 146);
panelObject.TabIndex = 4;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(94, 8);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(73, 28);
labelAdditionalColor.TabIndex = 3;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(10, 8);
labelBodyColor.Name = "labelBodyColor";
labelBodyColor.Size = new Size(73, 28);
labelBodyColor.TabIndex = 2;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += labelBodyColor_DragEnter;
//
// FormTrainConfing
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(733, 196);
Controls.Add(panelObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxConfing);
Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainConfing";
Text = "Создание объекта";
groupBoxConfing.ResumeLayout(false);
groupBoxConfing.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelObject.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfing;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxHorns;
private CheckBox checkBoxElectro;
private CheckBox checkBoxHeadlight;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
private Label labelBodyColor;
private Label labelAdditionalColor;
}
}

View File

@ -1,186 +0,0 @@
using ProjectTrain.Drawnings;
using ProjectTrain.Entities;
namespace ProjectTrain
{
/// <summary>
/// Форма конфигурации объекта
/// </summary>
public partial class FormTrainConfing : Form
{
/// <summary>
/// Объект - прорисовка артиллерийской установки
/// </summary>
private DrawningTrain _train;
/// <summary>
/// Событие для передачи объекта
/// </summary>
private event Action<DrawningTrain>? TrainDelegate;
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="carDelegate"></param>
public void AddEvent(Action<DrawningTrain> trainDelegate)
{
TrainDelegate += trainDelegate;
}
/// <summary>
/// Конструктор
/// </summary>
public FormTrainConfing()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
panelYellow.MouseDown += Panel_MouseDown;
panelWhite.MouseDown += Panel_MouseDown;
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
//TODO buttonCancel.Click with lambda с закрытием формы
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Прорисовка объекта
/// </summary>
private void DrawObject()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_train?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_train?.SetPosition(15, 15);
_train?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>labelSimpleObject
/// <param name="e"></param>labelSimpleObject
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data?.GetDataPresent(DataFormats.Text) ?? false ? DragDropEffects.Copy : DragDropEffects.None;
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
_train = new DrawningTrain((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_train = new
DrawningElectroTrain((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White,
Color.Black, checkBoxHorns.Checked, checkBoxElectro.Checked, checkBoxHeadlight.Checked);
break;
}
DrawObject();
}
/// <summary>
/// Передаем информацию при нажатии на Panel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object sender, MouseEventArgs e)
{
//TODO отправка цвета в Drag&Drop
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void labelBodyColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_train != null)
{
_train.EntityTrain.setBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_train is DrawningTrain)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_train.EntityTrain is EntityElectroTrain electroTrain)
{
electroTrain.setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_train != null)
{
TrainDelegate?.Invoke(_train);
Close();
}
}
private void checkBoxHorns_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBoxHeadlight_CheckedChanged(object sender, EventArgs e)
{
}
}
}

View File

@ -1,120 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -40,25 +40,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
panelCompanyTools = new Panel(); panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
ButtonAddTrain = new Button(); ButtonAddTrain = new Button();
ButtonAddElectroTrain = new Button();
buttonRefresh = new Button(); buttonRefresh = new Button();
ButtonRemoveTrain = new Button(); ButtonRemoveTrain = new Button();
maskedTextBoxPosision = new MaskedTextBox(); maskedTextBoxPosision = new MaskedTextBox();
buttonGetToTest = new Button(); buttonGetToTest = new Button();
pictureBoxTrain = new PictureBox(); pictureBoxTrain = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrain).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -68,11 +60,11 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(552, 24); groupBoxTools.Location = new Point(558, 0);
groupBoxTools.Margin = new Padding(3, 2, 3, 2); groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2); groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(194, 492); groupBoxTools.Size = new Size(194, 490);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "инструменты"; groupBoxTools.Text = "инструменты";
@ -191,9 +183,8 @@
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(ButtonAddTrain); panelCompanyTools.Controls.Add(ButtonAddTrain);
panelCompanyTools.Controls.Add(ButtonAddElectroTrain);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ButtonRemoveTrain); panelCompanyTools.Controls.Add(ButtonRemoveTrain);
panelCompanyTools.Controls.Add(maskedTextBoxPosision); panelCompanyTools.Controls.Add(maskedTextBoxPosision);
@ -205,30 +196,6 @@
panelCompanyTools.Size = new Size(189, 206); panelCompanyTools.Size = new Size(189, 206);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSortByColor.Location = new Point(17, 181);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(163, 23);
buttonSortByColor.TabIndex = 7;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Right;
buttonSortByType.Location = new Point(17, 149);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(163, 28);
buttonSortByType.TabIndex = 6;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// ButtonAddTrain // ButtonAddTrain
// //
ButtonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; ButtonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -236,19 +203,31 @@
ButtonAddTrain.Location = new Point(16, 2); ButtonAddTrain.Location = new Point(16, 2);
ButtonAddTrain.Margin = new Padding(3, 2, 3, 2); ButtonAddTrain.Margin = new Padding(3, 2, 3, 2);
ButtonAddTrain.Name = "ButtonAddTrain"; ButtonAddTrain.Name = "ButtonAddTrain";
ButtonAddTrain.Size = new Size(163, 39); ButtonAddTrain.Size = new Size(163, 30);
ButtonAddTrain.TabIndex = 1; ButtonAddTrain.TabIndex = 1;
ButtonAddTrain.Text = "добваление поезда"; ButtonAddTrain.Text = "добваление поезда";
ButtonAddTrain.UseVisualStyleBackColor = true; ButtonAddTrain.UseVisualStyleBackColor = true;
ButtonAddTrain.Click += ButtonAddTrain_Click; ButtonAddTrain.Click += ButtonAddTrain_Click;
// //
// ButtonAddElectroTrain
//
ButtonAddElectroTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonAddElectroTrain.Location = new Point(16, 37);
ButtonAddElectroTrain.Margin = new Padding(3, 2, 3, 2);
ButtonAddElectroTrain.Name = "ButtonAddElectroTrain";
ButtonAddElectroTrain.Size = new Size(163, 38);
ButtonAddElectroTrain.TabIndex = 2;
ButtonAddElectroTrain.Text = "добваление электро-поеда";
ButtonAddElectroTrain.UseVisualStyleBackColor = true;
ButtonAddElectroTrain.Click += ButtonAddElectroTrain_Click;
//
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRefresh.Location = new Point(17, 123); buttonRefresh.Location = new Point(16, 170);
buttonRefresh.Margin = new Padding(3, 2, 3, 2); buttonRefresh.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(163, 22); buttonRefresh.Size = new Size(163, 31);
buttonRefresh.TabIndex = 5; buttonRefresh.TabIndex = 5;
buttonRefresh.Text = "обновить"; buttonRefresh.Text = "обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -257,10 +236,10 @@
// ButtonRemoveTrain // ButtonRemoveTrain
// //
ButtonRemoveTrain.Anchor = AnchorStyles.Right; ButtonRemoveTrain.Anchor = AnchorStyles.Right;
ButtonRemoveTrain.Location = new Point(17, 74); ButtonRemoveTrain.Location = new Point(16, 104);
ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2); ButtonRemoveTrain.Margin = new Padding(3, 2, 3, 2);
ButtonRemoveTrain.Name = "ButtonRemoveTrain"; ButtonRemoveTrain.Name = "ButtonRemoveTrain";
ButtonRemoveTrain.Size = new Size(163, 21); ButtonRemoveTrain.Size = new Size(163, 30);
ButtonRemoveTrain.TabIndex = 3; ButtonRemoveTrain.TabIndex = 3;
ButtonRemoveTrain.Text = "удалить поезд"; ButtonRemoveTrain.Text = "удалить поезд";
ButtonRemoveTrain.UseVisualStyleBackColor = true; ButtonRemoveTrain.UseVisualStyleBackColor = true;
@ -268,7 +247,7 @@
// //
// maskedTextBoxPosision // maskedTextBoxPosision
// //
maskedTextBoxPosision.Location = new Point(16, 45); maskedTextBoxPosision.Location = new Point(15, 79);
maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2); maskedTextBoxPosision.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxPosision.Mask = "00"; maskedTextBoxPosision.Mask = "00";
maskedTextBoxPosision.Name = "maskedTextBoxPosision"; maskedTextBoxPosision.Name = "maskedTextBoxPosision";
@ -279,10 +258,10 @@
// buttonGetToTest // buttonGetToTest
// //
buttonGetToTest.Anchor = AnchorStyles.Right; buttonGetToTest.Anchor = AnchorStyles.Right;
buttonGetToTest.Location = new Point(16, 99); buttonGetToTest.Location = new Point(16, 138);
buttonGetToTest.Margin = new Padding(3, 2, 3, 2); buttonGetToTest.Margin = new Padding(3, 2, 3, 2);
buttonGetToTest.Name = "buttonGetToTest"; buttonGetToTest.Name = "buttonGetToTest";
buttonGetToTest.Size = new Size(163, 20); buttonGetToTest.Size = new Size(163, 30);
buttonGetToTest.TabIndex = 4; buttonGetToTest.TabIndex = 4;
buttonGetToTest.Text = "передать на тесты"; buttonGetToTest.Text = "передать на тесты";
buttonGetToTest.UseVisualStyleBackColor = true; buttonGetToTest.UseVisualStyleBackColor = true;
@ -291,84 +270,37 @@
// pictureBoxTrain // pictureBoxTrain
// //
pictureBoxTrain.Dock = DockStyle.Fill; pictureBoxTrain.Dock = DockStyle.Fill;
pictureBoxTrain.Location = new Point(0, 24); pictureBoxTrain.Location = new Point(0, 0);
pictureBoxTrain.Margin = new Padding(3, 2, 3, 2); pictureBoxTrain.Margin = new Padding(3, 2, 3, 2);
pictureBoxTrain.Name = "pictureBoxTrain"; pictureBoxTrain.Name = "pictureBoxTrain";
pictureBoxTrain.Size = new Size(552, 492); pictureBoxTrain.Size = new Size(558, 490);
pictureBoxTrain.TabIndex = 1; pictureBoxTrain.TabIndex = 1;
pictureBoxTrain.TabStop = false; pictureBoxTrain.TabStop = false;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(5, 2, 0, 2);
menuStrip.Size = new Size(746, 24);
menuStrip.TabIndex = 2;
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";
//
// FormTrainsCollection // FormTrainsCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(746, 516); ClientSize = new Size(752, 490);
Controls.Add(pictureBoxTrain); Controls.Add(pictureBoxTrain);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
Name = "FormTrainsCollection"; Name = "FormTrainsCollection";
Text = "FormTrainsCollection"; Text = "FormTrainsCollection";
Load += FormTrainsCollection_Load;
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
panelCompanyTools.ResumeLayout(false); panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout(); panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTrain).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany; private ComboBox comboBoxSelectorCompany;
private Button ButtonAddElectroTrain;
private Button ButtonAddTrain; private Button ButtonAddTrain;
private Button ButtonRemoveTrain; private Button ButtonRemoveTrain;
private Button buttonRefresh; private Button buttonRefresh;
@ -385,13 +317,5 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -1,7 +1,5 @@
using Microsoft.Extensions.Logging; using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.CollectionGenericObjects;
using ProjectTrain.Drawnings; using ProjectTrain.Drawnings;
using System.Windows.Forms;
namespace ProjectTrain namespace ProjectTrain
{ {
@ -17,19 +15,13 @@ namespace ProjectTrain
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormTrainsCollection(ILogger<FormTrainsCollection> logger) public FormTrainsCollection()
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
/// <summary> /// <summary>
@ -43,49 +35,72 @@ namespace ProjectTrain
} }
/// <summary> /// <summary>
/// добавление артиллерийской установки /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="type">Тип создаваемого объекта</param>
/// <param name="e"></param> private void CreateObject(string type)
private void ButtonAddTrain_Click(object sender, EventArgs e)
{ {
FormTrainConfing form = new(); if (_company == null)
// TODO передать метод
form.Show();
form.AddEvent(SetTrain);
}
/// <summary>
/// Добавление артиллерийской установки в коллекцию
/// </summary>
/// <param name="train"></param>
private void SetTrain(DrawningTrain? train)
{
if (_company == null || train == null)
{ {
return; return;
} }
try Random random = new();
DrawningTrain drawningTrain;
switch (type)
{
case nameof(DrawningTrain):
drawningTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningElectroTrain):
// TODO вызов диалогового окна для выбора цвета
drawningTrain = new DrawningElectroTrain(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTrain != -1)
{ {
var res = _company + train;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBoxTrain.Image = _company.Show(); pictureBoxTrain.Image = _company.Show();
} }
catch (Exception ex) else
{ {
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBox.Show("Не удалось добавить объект");
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
/// Удаление объекта /// Получение цвета
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="random">Генератор случайных чисел</param>
/// <param name="e"></param> /// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0,
256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
//private void ButtonAddTrain_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrain));
//private void ButtonAddElectroTrain_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningElectroTrain));
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningTrain));
}
private void ButtonAddElectroTrain_Click(object sender, EventArgs e)
{
CreateObject(nameof(DrawningElectroTrain));
}
private void ButtonRemoveTrain_Click(object sender, EventArgs e) private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBoxPosision.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBoxPosision.Text) || _company == null)
@ -98,18 +113,14 @@ namespace ProjectTrain
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosision.Text); int pos = Convert.ToInt32(maskedTextBoxPosision.Text);
try if (_company - pos != null)
{ {
var res = _company - pos; MessageBox.Show("объект удален");
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBoxTrain.Image = _company.Show(); pictureBoxTrain.Image = _company.Show();
} }
catch (Exception ex) else
{ {
MessageBox.Show(ex.Message, "Не удалось удалить объект", MessageBox.Show("не удалось удалить объект");
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -120,24 +131,24 @@ namespace ProjectTrain
return; return;
} }
DrawningTrain? train = null; DrawningTrain? cruiser = null;
int counter = 100; int counter = 100;
while (train == null) while (cruiser == null)
{ {
train = _company.GetRandomObject(); cruiser = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
break; break;
} }
} }
if (train == null) if (cruiser == null)
{ {
return; return;
} }
FormTrain form = new() FormTrain form = new()
{ {
SetTrain = train SetTrain = cruiser
}; };
form.ShowDialog(); form.ShowDialog();
@ -162,7 +173,8 @@ namespace ProjectTrain
{ {
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);
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
@ -174,11 +186,7 @@ namespace ProjectTrain
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -198,11 +206,7 @@ namespace ProjectTrain
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
@ -214,7 +218,7 @@ namespace ProjectTrain
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].Name; string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -223,7 +227,7 @@ namespace ProjectTrain
} }
/// <summary> /// <summary>
/// Создание компании ///
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
@ -234,111 +238,23 @@ namespace ProjectTrain
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningTrain>? collection =
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty); _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
ICollectionGenericObjects<DrawningTrain>? collection = _storageCollection[collectionInfo];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
_company = new TrainDockingService(pictureBoxTrain.Width, pictureBoxTrain.Height, collection); _company = new TrainDockingService(pictureBoxTrain.Width, pictureBoxTrain.Height, collection);
_logger.LogInformation("Компания создана");
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
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);
RerfreshListBoxItems();
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);
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareTrains(new DrawningTrainCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareTrains(new DrawningTrainCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTrains(IComparer<DrawningTrain?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBoxTrain.Image = _company.Show();
}
private void FormTrainsCollection_Load(object sender, EventArgs e)
{
}
} }
} }

View File

@ -117,16 +117,4 @@
<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, 1</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>145, 1</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 1</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>

View File

@ -10,36 +10,36 @@ namespace ProjectTrain.MovementStrategy
/// <summary> /// <summary>
/// Поле-объект класса DrawningTrain или его наследника /// Поле-объект класса DrawningTrain или его наследника
/// </summary> /// </summary>
private readonly DrawningTrain? _train = null; private readonly DrawningTrain? _cruiser = null;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="train">Объект класса DrawningTrain</param> /// <param name="cruiser">Объект класса DrawningTrain</param>
public MoveableTrain(DrawningTrain train) public MoveableTrain(DrawningTrain cruiser)
{ {
_train = train; _cruiser = cruiser;
} }
public ObjectParameters? GetObjectPosition public ObjectParameters? GetObjectPosition
{ {
get get
{ {
if (_train == null || _train.EntityTrain == null || if (_cruiser == null || _cruiser.EntityTrain == null ||
!_train.GetPosX.HasValue || !_train.GetPosY.HasValue) !_cruiser.GetPosX.HasValue || !_cruiser.GetPosY.HasValue)
{ {
return null; return null;
} }
return new ObjectParameters(_train.GetPosX.Value, return new ObjectParameters(_cruiser.GetPosX.Value,
_train.GetPosY.Value, _train.GetWidth, _train.GetHeight); _cruiser.GetPosY.Value, _cruiser.GetWidth, _cruiser.GetHeight);
} }
} }
public int GetStep => (int)(_train?.EntityTrain?.Step ?? 0); public int GetStep => (int)(_cruiser?.EntityTrain?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction) public bool TryMoveObject(MovementDirection direction)
{ {
if (_train == null || _train.EntityTrain == null) if (_cruiser == null || _cruiser.EntityTrain == null)
{ {
return false; return false;
} }
return _train.MoveTransport(GetDirectionType(direction)); return _cruiser.MoveTransport(GetDirectionType(direction));
} }
/// <summary> /// <summary>
/// Конвертация из MovementDirection в DirectionType /// Конвертация из MovementDirection в DirectionType

View File

@ -1,8 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectTrain namespace ProjectTrain
{ {
internal static class Program internal static class Program
@ -15,31 +10,7 @@ namespace ProjectTrain
{ {
// To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration. // To customize application configuration such as set high DPI settings or default font, see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
ServiceCollection services = new(); Application.Run(new FormTrainsCollection());
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormTrainsCollection>());
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTrainsCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
} }
} }

View File

@ -8,15 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.12" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -1,10 +0,0 @@
using ProjectTrain.Drawnings;
namespace ProjectTrain;
/// <summary>
/// Делегат передачи объекта класса-прорисвоки
/// </summary>
/// <param name="train"></param>
public delegate void TrainDelegate(DrawningTrain train);

View File

@ -1,14 +0,0 @@
<?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="trainlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@ -1,20 +0,0 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "train"
}
}
}