Compare commits
3 Commits
78c85a1e62
...
4a87ab7d00
Author | SHA1 | Date | |
---|---|---|---|
|
4a87ab7d00 | ||
|
e8948059d1 | ||
|
6e6196a623 |
@ -1,4 +1,5 @@
|
||||
using ProjectRoadTrain.Drawnings;
|
||||
using ProjectRoadTrain.Exceptions;
|
||||
|
||||
namespace ProjectRoadTrain.CollectionGenericObjects;
|
||||
|
||||
@ -35,8 +36,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -51,28 +51,27 @@ public abstract class AbstractCompany
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="car">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningTrain bus)
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="сruiser">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningTrain train)
|
||||
{
|
||||
return company._collection?.Insert(bus) ?? -1;
|
||||
return company._collection.Insert(train);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
public static DrawningTrain operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company._collection?.Remove(position) ?? null;
|
||||
return company._collection?.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
@ -83,30 +82,33 @@ public abstract class AbstractCompany
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Bitmap? Show()
|
||||
{
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackgound(graphics);
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningTrain? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningTrain? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{ }
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{ }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
} /// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectRoadTrain.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -17,14 +18,27 @@ where T : class
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
|
||||
public int MaxCount
|
||||
{
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
get
|
||||
{
|
||||
|
||||
return Count;
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
@ -35,49 +49,33 @@ where T : class
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
public T? Get(int position)
|
||||
public T Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
return _collection[position];
|
||||
}
|
||||
return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
if (Count <= _maxCount)
|
||||
{
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (Count < _maxCount && position >= 0 && position < _maxCount)
|
||||
{
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
T temp = _collection[position];
|
||||
if (position >= 0 && position < _maxCount)
|
||||
{
|
||||
_collection.RemoveAt(position);
|
||||
return temp;
|
||||
}
|
||||
return null;
|
||||
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectRoadTrain.Exceptions;
|
||||
|
||||
namespace ProjectRoadTrain.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -6,15 +8,16 @@ namespace ProjectRoadTrain.CollectionGenericObjects;
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
/// <summary>
|
||||
/// Установка максимального кол-ва объектов
|
||||
/// </summary>
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
@ -46,71 +49,86 @@ where T : class
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция (индекс)</param>
|
||||
/// <returns></returns>
|
||||
public T? Get(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// вставка в свободное место набора
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
// вставка в свободное место набора
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return -1; }
|
||||
|
||||
if (_collection[position] == null)
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index;
|
||||
|
||||
for (index = position + 1; index < _collection.Length; ++index)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
bool pushed = false;
|
||||
for (int index = position + 1; index < Count; index++)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
for (index = position - 1; index >= 0; --index)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
// вставка
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
public T Remove(int position)
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return null; }
|
||||
T DrawningAircraft = _collection[position];
|
||||
_collection[position] = null;
|
||||
return DrawningAircraft;
|
||||
}
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectRoadTrain.Drawnings;
|
||||
using ProjectRoadTrain.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -50,22 +51,23 @@ where T : DrawningTrain
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
|
||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
||||
return;
|
||||
switch (collectionType)
|
||||
{
|
||||
if (collectionType == CollectionType.List)
|
||||
{
|
||||
case CollectionType.List:
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
}
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
{
|
||||
break;
|
||||
case CollectionType.Massive:
|
||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
@ -80,15 +82,12 @@ where T : DrawningTrain
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (_storages.ContainsKey(name))
|
||||
{
|
||||
return _storages[name];
|
||||
}
|
||||
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
|
||||
return value;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -97,11 +96,11 @@ where T : DrawningTrain
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
|
||||
@ -110,8 +109,6 @@ where T : DrawningTrain
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter streamWriter = new StreamWriter(fs);
|
||||
streamWriter.Write(_collectionKey);
|
||||
@ -147,43 +144,37 @@ where T : DrawningTrain
|
||||
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по поездам в хранилище из файла
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение
|
||||
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
return false;
|
||||
|
||||
throw new FormatException("В файле неверные данные");
|
||||
_storages.Clear();
|
||||
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
string[] record = str.Split(_separatorForKeyValue);
|
||||
|
||||
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -193,15 +184,22 @@ where T : DrawningTrain
|
||||
{
|
||||
if (elem?.CreateDrawningTrain() is T train)
|
||||
{
|
||||
if (collection.Insert(train) == -1)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
if (collection.Insert(train) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
|
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectRoadTrain.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
|
||||
|
||||
public CollectionOverflowException() : base() { }
|
||||
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
|
||||
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectRoadTrain.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
|
||||
public ObjectNotFoundException() : base() { }
|
||||
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <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) { }
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using ProjectRoadTrain.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectRoadTrain.CollectionGenericObjects;
|
||||
using ProjectRoadTrain.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -10,270 +11,301 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectRoadTrain
|
||||
namespace ProjectRoadTrain;
|
||||
public partial class FormTrainCollection : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningTrain> _storageCollection;
|
||||
|
||||
public partial class FormTrainCollection : Form
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormTrainCollection(ILogger<FormTrainCollection> logger)
|
||||
{
|
||||
/// <summary>
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningTrain> _storageCollection;
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormTrainCollection()
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление автомобиля
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddTrain_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormTrainConfig form = new();
|
||||
//TODO Передать метод
|
||||
form.Show();
|
||||
form.AddEvent(SetTrain);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление автомобиля в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="train"></param>
|
||||
private void SetTrain(DrawningTrain train)
|
||||
{
|
||||
if (_company == null || train == null)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
try
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление поезда
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddTrain_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormTrainConfig form = new();
|
||||
//TODO Передать метод
|
||||
form.Show();
|
||||
form.AddEvent(SetTrain);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление поезда в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="train"></param>
|
||||
private void SetTrain(DrawningTrain train)
|
||||
{
|
||||
if (_company == null || train == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + train != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален!");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DrawningTrain? train = null;
|
||||
int counter = 100;
|
||||
while (train == null)
|
||||
{
|
||||
train = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (train == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormRoadTrain form = new()
|
||||
{
|
||||
SetTrain = train
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var res = _company + train;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
/// <summary>
|
||||
/// Кнопка удаления поезда
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("удалить объект?", "удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DrawningTrain? train = null;
|
||||
int counter = 100;
|
||||
while (train == null)
|
||||
{
|
||||
train = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (train == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormRoadTrain form = new()
|
||||
{
|
||||
SetTrain = train
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавление коллекции");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
catch (Exception ex)
|
||||
{
|
||||
// TODO прописать логику удаления элемента из коллекции
|
||||
// нужно убедиться, что есть выбранная коллекция
|
||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||
// удалить и обновить ListBox
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningTrain>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
}
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранить"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||
DialogResult.Yes)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Загрузка"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание компании
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningTrain>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
|
||||
_logger.LogInformation("Компания создана");
|
||||
break;
|
||||
}
|
||||
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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("Не сохранилось", "Результат", 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -126,4 +126,7 @@
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>43</value>
|
||||
</metadata>
|
||||
</root>
|
@ -1,17 +1,49 @@
|
||||
namespace ProjectRoadTrain
|
||||
{
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
using System;
|
||||
|
||||
namespace ProjectRoadTrain;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormTrainCollection());
|
||||
}
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTrainCollection>());
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
services.AddSingleton<FormTrainCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -8,4 +8,17 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||
<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.11" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties /></VisualStudio></ProjectExtensions>
|
||||
|
||||
</Project>
|
15
ProjectRoadTrain/ProjectRoadTrain/serilog.json
Normal file
15
ProjectRoadTrain/ProjectRoadTrain/serilog.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "C:\\Users\\savel\\source\\repos\\ISEbd-11_Savelyev_P.Y._Simple\\Lab1\\log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user