PIBD-14 Boyko_M.S, LabWork07 Simple #9
@ -1,4 +1,5 @@
|
||||
using ProjectElectroTrans.Drawnings;
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
@ -7,59 +8,60 @@ namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
/// </summary>
|
||||
public abstract class AbstractCompany
|
||||
{
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 210;
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 210;
|
||||
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 80;
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 80;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
|
||||
/// <summary>
|
||||
/// Коллекция поездов
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawingTrans>? _collection = null;
|
||||
/// <summary>
|
||||
/// Коллекция поездов
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawingTrans>? _collection = null;
|
||||
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
// private int GetMaxCount => (_pictureWidth * _pictureHeight) / (_placeSizeWidth * _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина окна</param>
|
||||
/// <param name="picHeight">Высота окна</param>
|
||||
/// <param name="collection">Коллекция поездов</param>
|
||||
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection)
|
||||
{
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина окна</param>
|
||||
/// <param name="picHeight">Высота окна</param>
|
||||
/// <param name="collection">Коллекция поездов</param>
|
||||
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection)
|
||||
{
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="car">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingTrans trans)
|
||||
{
|
||||
return company._collection.Insert(trans);
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="car">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawingTrans trans)
|
||||
{
|
||||
return company._collection.Insert(trans);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -69,48 +71,59 @@ public abstract class AbstractCompany
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
public static DrawingTrans? operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company._collection?.Remove(position);
|
||||
}
|
||||
{
|
||||
return company._collection?.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public DrawingTrans? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public DrawingTrans? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
return _collection?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод всей коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Bitmap? Show()
|
||||
{
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackgound(graphics);
|
||||
/// <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)
|
||||
{
|
||||
DrawingTrans? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawingTrans? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{
|
||||
// Relax Man ;)
|
||||
}
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{
|
||||
// Relax Man ;)
|
||||
}
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
}
|
@ -1,4 +1,6 @@
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@ -43,28 +45,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T Get(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count == _maxCount) return -1;
|
||||
if (position >= Count || position < 0) 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)
|
||||
{
|
||||
if (position >= _collection.Count || position < 0) return null;
|
||||
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
|
@ -1,4 +1,5 @@
|
||||
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
@ -6,55 +7,49 @@ namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
public int MaxCount
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
get { return _collection.Length; }
|
||||
set
|
||||
{
|
||||
return _collection[position];
|
||||
if (value > 0)
|
||||
{
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
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)
|
||||
@ -69,16 +64,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
@ -111,7 +103,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
return position;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
}
|
||||
|
||||
@ -123,23 +115,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null) return null;
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,9 @@
|
||||
using ProjectElectroTrans.Drawnings;
|
||||
using System.Text;
|
||||
using ProjectElectroTrans.CollectionGenericObjects;
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
using FileFormatException = ProjectElectroTrans.Exceptions.FileFormatException;
|
||||
using FileNotFoundException = ProjectElectroTrans.Exceptions.FileNotFoundException;
|
||||
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
@ -51,9 +54,9 @@ public class StorageCollection<T>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (_storages.ContainsKey(name)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name);
|
||||
if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции");
|
||||
if (collectionType == CollectionType.Massive)
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
else if (collectionType == CollectionType.List)
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
@ -67,6 +70,7 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -93,7 +97,7 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new EmptyFileExeption();
|
||||
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -154,14 +158,15 @@ public class StorageCollection<T>
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException(filename);
|
||||
|
||||
}
|
||||
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new FileFormatException(filename);
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
@ -178,7 +183,7 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -187,9 +192,70 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (elem?.CreateDrawningTrans() is T ship)
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
collection.Insert(ship);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new FileFormatException(filename, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
}
|
||||
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
throw new EmptyFileExeption(filename);
|
||||
}
|
||||
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTrans() is T ship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
{
|
||||
throw new CollectionTypeException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw ex.InnerException!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
using ProjectElectroTrans.Drawnings;
|
||||
using ProjectElectroTrans.Entities;
|
||||
using System;
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
|
||||
namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
@ -9,47 +10,62 @@ namespace ProjectElectroTrans.CollectionGenericObjects;
|
||||
/// </summary>
|
||||
public class TransDepoService : AbstractCompany
|
||||
{
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth"></param>
|
||||
/// <param name="picHeight"></param>
|
||||
/// <param name="collection"></param>
|
||||
public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth"></param>
|
||||
/// <param name="picHeight"></param>
|
||||
/// <param name="collection"></param>
|
||||
public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(
|
||||
picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
Pen pen = new(Color.Black);
|
||||
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
|
||||
{
|
||||
for(int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
|
||||
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
|
||||
{
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
|
||||
}
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
|
||||
}
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
|
||||
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j),
|
||||
new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
|
||||
}
|
||||
|
||||
|
||||
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)),
|
||||
new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
|
||||
}
|
||||
}
|
||||
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
|
||||
{
|
||||
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
|
||||
{
|
||||
DrawingTrans? drawingTrans = _collection?.Get(n);
|
||||
n++;
|
||||
if (drawingTrans != null)
|
||||
{
|
||||
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
|
||||
{
|
||||
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawingTrans? drawingTrans = _collection?.Get(n);
|
||||
if (drawingTrans != null)
|
||||
{
|
||||
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{
|
||||
// Relax Man ;)
|
||||
}
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{
|
||||
// Relax Man ;)
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class CollectionAlreadyExistsException : Exception
|
||||
{
|
||||
public CollectionAlreadyExistsException() : base() { }
|
||||
public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { }
|
||||
public CollectionAlreadyExistsException(string name, Exception exception) :
|
||||
base($"Коллекция {name} уже существует!", exception) { }
|
||||
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
13
ProjectElectroTrans/Exceptions/CollectionInsertException.cs
Normal file
13
ProjectElectroTrans/Exceptions/CollectionInsertException.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class CollectionInsertException : Exception
|
||||
{
|
||||
public CollectionInsertException() : base() { }
|
||||
public CollectionInsertException(string message) : base(message) { }
|
||||
public CollectionInsertException(string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected CollectionInsertException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count)
|
||||
{
|
||||
}
|
||||
|
||||
public CollectionOverflowException() : base()
|
||||
{
|
||||
}
|
||||
|
||||
public CollectionOverflowException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public CollectionOverflowException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{
|
||||
}
|
||||
|
||||
protected CollectionOverflowException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
14
ProjectElectroTrans/Exceptions/CollectionTypeException.cs
Normal file
14
ProjectElectroTrans/Exceptions/CollectionTypeException.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System.Runtime.Serialization;
|
||||
using ProjectElectroTrans.CollectionGenericObjects;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class CollectionTypeException : Exception
|
||||
{
|
||||
public CollectionTypeException() : base() { }
|
||||
public CollectionTypeException(string message) : base(message) { }
|
||||
public CollectionTypeException(string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected CollectionTypeException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
14
ProjectElectroTrans/Exceptions/EmptyFileExeption.cs
Normal file
14
ProjectElectroTrans/Exceptions/EmptyFileExeption.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class EmptyFileExeption : Exception
|
||||
{
|
||||
public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { }
|
||||
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
|
||||
public EmptyFileExeption(string name, string message) : base(message) { }
|
||||
public EmptyFileExeption(string name, string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected EmptyFileExeption(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
13
ProjectElectroTrans/Exceptions/EmptyStorageException.cs
Normal file
13
ProjectElectroTrans/Exceptions/EmptyStorageException.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class EmptyStorageException : Exception
|
||||
{
|
||||
public EmptyStorageException() : base() { }
|
||||
public EmptyStorageException(string message) : base(message) { }
|
||||
public EmptyStorageException(string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected EmptyStorageException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
13
ProjectElectroTrans/Exceptions/FileFormatException.cs
Normal file
13
ProjectElectroTrans/Exceptions/FileFormatException.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class FileFormatException : Exception
|
||||
{
|
||||
public FileFormatException() : base() { }
|
||||
public FileFormatException(string message) : base(message) { }
|
||||
public FileFormatException(string name, Exception exception) :
|
||||
base($"Файл {name} имеет неверный формат. Ошибка: {exception.Message}", exception) { }
|
||||
protected FileFormatException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
14
ProjectElectroTrans/Exceptions/FileNotFoundException.cs
Normal file
14
ProjectElectroTrans/Exceptions/FileNotFoundException.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
public class FileNotFoundException : Exception
|
||||
{
|
||||
public FileNotFoundException(string name) : base($"Файл {name} не существует ") { }
|
||||
public FileNotFoundException() : base() { }
|
||||
public FileNotFoundException(string name, string message) : base(message) { }
|
||||
public FileNotFoundException(string name, string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected FileNotFoundException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
15
ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs
Normal file
15
ProjectElectroTrans/Exceptions/ObjectNotFoundException.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectElectroTrans.Exceptions;
|
||||
|
||||
[Serializable]
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
public ObjectNotFoundException() : base() { }
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
public ObjectNotFoundException(string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext
|
||||
contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
[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,6 +1,7 @@
|
||||
using ProjectElectroTrans.CollectionGenericObjects;
|
||||
using ProjectElectroTrans.Drawnings;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectElectroTrans.Exceptions;
|
||||
|
||||
namespace ProjectElectroTrans;
|
||||
|
||||
@ -19,13 +20,19 @@ public partial class FormTransCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormTransCollection()
|
||||
public FormTransCollection(ILogger<FormTransCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -62,15 +69,18 @@ public partial class FormTransCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + drawingTrans != -1)
|
||||
try
|
||||
{
|
||||
var res = _company + drawingTrans;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
_ = MessageBox.Show(drawingTrans.ToString());
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -93,14 +103,18 @@ public partial class FormTransCollection : Form
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -179,8 +193,18 @@ public partial class FormTransCollection : Form
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
try
|
||||
{
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавление коллекции");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -203,6 +227,7 @@ public partial class FormTransCollection : Form
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -247,6 +272,7 @@ public partial class FormTransCollection : Form
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new TransDepoService(pictureBox.Width, pictureBox.Height, collection);
|
||||
_logger.LogInformation("Компания создана");
|
||||
break;
|
||||
}
|
||||
|
||||
@ -263,15 +289,19 @@ public partial class FormTransCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}",
|
||||
saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBox.Show(ex.Message, "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -285,16 +315,20 @@ public partial class FormTransCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}");
|
||||
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загружено", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
3
ProjectElectroTrans/FormTransConfig.Designer.cs
generated
3
ProjectElectroTrans/FormTransConfig.Designer.cs
generated
@ -43,7 +43,6 @@
|
||||
panelRed = new Panel();
|
||||
checkBoxBulldozerDump = new CheckBox();
|
||||
checkBoxSupport = new CheckBox();
|
||||
checkBoxBucket = new CheckBox();
|
||||
numericUpDownWeight = new NumericUpDown();
|
||||
numericUpDownSpeed = new NumericUpDown();
|
||||
labelWeight = new Label();
|
||||
@ -73,7 +72,6 @@
|
||||
groupBoxConfig.Controls.Add(groupBoxColors);
|
||||
groupBoxConfig.Controls.Add(checkBoxBulldozerDump);
|
||||
groupBoxConfig.Controls.Add(checkBoxSupport);
|
||||
groupBoxConfig.Controls.Add(checkBoxBucket);
|
||||
groupBoxConfig.Controls.Add(numericUpDownWeight);
|
||||
groupBoxConfig.Controls.Add(numericUpDownSpeed);
|
||||
groupBoxConfig.Controls.Add(labelWeight);
|
||||
@ -377,7 +375,6 @@
|
||||
private Label labelSpeed;
|
||||
private CheckBox checkBoxBulldozerDump;
|
||||
private CheckBox checkBoxSupport;
|
||||
private CheckBox checkBoxBucket;
|
||||
private GroupBox groupBoxColors;
|
||||
private Panel panelPurple;
|
||||
private Panel panelYellow;
|
||||
|
@ -102,7 +102,7 @@ namespace ProjectElectroTrans
|
||||
case "labelModifiedObject":
|
||||
_trans = new DrawingElectroTrans((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value,
|
||||
Color.White,
|
||||
Color.Black, checkBoxBucket.Checked,
|
||||
Color.Black, checkBoxBulldozerDump.Checked,
|
||||
checkBoxSupport.Checked);
|
||||
break;
|
||||
}
|
||||
|
@ -1,20 +1,45 @@
|
||||
using System.Drawing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
|
||||
namespace ProjectElectroTrans
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
/// <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 FormTransCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormTransCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormTransCollection>().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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net7.0-windows</TargetFramework>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
@ -23,4 +23,14 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0-preview.3.24172.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0-preview.3.24172.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0-preview.3.24172.9" />
|
||||
<PackageReference Include="Serilog" Version="4.0.0-dev-02160" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10389" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1-dev-00582" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00972" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
20
ProjectElectroTrans/serilogConfig.json
Normal file
20
ProjectElectroTrans/serilogConfig.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"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}"
|
||||
}
|
||||
}, {"Name": "Console"}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Locomotives"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Не требовалось создавать еще наследников от класса Exception, а нужно было использовать уже имеющиеся, стандартные