Готовая лаба 7
This commit is contained in:
commit
919febed18
@ -1,88 +1,114 @@
|
||||
using HoistingCrane.Drawning;
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
namespace HoistingCrane.CollectionGenericObjects;
|
||||
public abstract class AbstractCompany
|
||||
{
|
||||
public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 180;
|
||||
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
|
||||
/// <summary>
|
||||
/// Коллекция военных кораблей
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningTrackedVehicle>? _collection = null;
|
||||
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, которые можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth">Ширина окна</param>
|
||||
/// <param name="picHeight">Высота окна</param>
|
||||
/// <param name="collection">Коллекция военных кораблей</param>
|
||||
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> collection)
|
||||
{
|
||||
/// <summary>
|
||||
/// Ширина ячейки гаража
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 150;
|
||||
/// <summary>
|
||||
/// Высота ячейки гаража
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeHeight = 90;
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
protected readonly int pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int pictureHeight;
|
||||
/// <summary>
|
||||
/// Коллекция автомобилей
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningTrackedVehicle>? arr = null;
|
||||
/// <summary>
|
||||
/// Максимальное количество гаражей
|
||||
/// </summary>
|
||||
private int GetMaxCount
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора сложения для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="warship">Добавляемый объект</param>
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningTrackedVehicle warship)
|
||||
{
|
||||
return company._collection.Insert(warship);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перегрузка оператора удаления для класса
|
||||
/// </summary>
|
||||
/// <param name="company">Компания</param>
|
||||
/// <param name="position">Номер удаляемого объекта</param>
|
||||
/// <returns></returns>
|
||||
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company._collection.Remove(position);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение случайного объекта из коллекции
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public DrawningTrackedVehicle? 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);
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
get
|
||||
try
|
||||
{
|
||||
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth);
|
||||
}
|
||||
}
|
||||
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
|
||||
{
|
||||
pictureWidth = picWidth;
|
||||
pictureHeight = picHeight;
|
||||
arr = array;
|
||||
arr.MaxCount = GetMaxCount;
|
||||
}
|
||||
|
||||
public static int operator +(AbstractCompany company, DrawningTrackedVehicle car)
|
||||
{
|
||||
return company.arr?.Insert(car) ?? -1;
|
||||
}
|
||||
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
|
||||
{
|
||||
return company.arr?.Remove(position);
|
||||
}
|
||||
|
||||
public DrawningTrackedVehicle? GetRandomObject()
|
||||
{
|
||||
Random rnd = new();
|
||||
return arr?.Get(rnd.Next(GetMaxCount));
|
||||
}
|
||||
|
||||
/// <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 < (arr?.Count ?? 0); i++)
|
||||
{
|
||||
DrawningTrackedVehicle? obj = arr?.Get(i);
|
||||
DrawningTrackedVehicle? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
return bitmap;
|
||||
catch (Exception) { }
|
||||
}
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,66 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace HoistingCrane.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>
|
||||
public 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)
|
||||
{
|
||||
this.name = name;
|
||||
this.collectionType = collectionType;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
if (other == null) return false;
|
||||
if (name != other.name) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
return Equals(obj as CollectionInfo);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return name.GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
using System;
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
{
|
||||
public enum CollectionType
|
||||
{
|
||||
|
@ -8,8 +8,8 @@ namespace HoistingCrane.CollectionGenericObjects
|
||||
}
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
int width = pictureWidth / _placeSizeWidth;
|
||||
int height = pictureHeight / _placeSizeHeight;
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
Pen pen = new(Color.Black, 3);
|
||||
for (int i = 0; i < width; i++)
|
||||
{
|
||||
@ -22,18 +22,18 @@ namespace HoistingCrane.CollectionGenericObjects
|
||||
}
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
int countWidth = pictureWidth / _placeSizeWidth;
|
||||
int countHeight = pictureHeight / _placeSizeHeight;
|
||||
int countWidth = _pictureWidth / _placeSizeWidth;
|
||||
int countHeight = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int currentPosWidth = countWidth - 1;
|
||||
int currentPosHeight = countHeight - 1;
|
||||
|
||||
for (int i = 0; i < (arr?.Count ?? 0); i++)
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (arr?.Get(i) != null)
|
||||
if (_collection?.Get(i) != null)
|
||||
{
|
||||
arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight);
|
||||
arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
|
||||
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
|
||||
}
|
||||
|
||||
if (currentPosWidth > 0)
|
||||
@ -47,7 +47,6 @@ namespace HoistingCrane.CollectionGenericObjects
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
using HoistingCrane.Drawning;
|
||||
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
{
|
||||
public interface ICollectionGenericObjects<T>
|
||||
where T: class
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Кол-во объектов в коллекции
|
||||
@ -15,15 +17,17 @@
|
||||
/// Добавление элемента в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// /// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns></returns>
|
||||
int Insert(T obj);
|
||||
int Insert(T obj, IEqualityComparer<T>? comparer = null);
|
||||
/// <summary>
|
||||
/// Добавление элемента в коллекцию на определенную позицию
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <param name="position"></param>
|
||||
/// <param name="comparer">Сравнение двух объектов</param>
|
||||
/// <returns></returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T>? comparer = null);
|
||||
/// <summary>
|
||||
/// Удаление элемента из коллекции по его позиции
|
||||
/// </summary>
|
||||
@ -45,5 +49,10 @@
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
void CollectionSort(IComparer<T> comparer);
|
||||
}
|
||||
}
|
@ -1,89 +1,107 @@
|
||||
using System;
|
||||
using System.CodeDom.Compiler;
|
||||
using System.Windows.Forms.VisualStyles;
|
||||
using HoistingCrane.Drawning;
|
||||
using HoistingCrane.Exceptions;
|
||||
namespace HoistingCrane.CollectionGenericObjects;
|
||||
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
|
||||
{
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : class
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
readonly List<T> list;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
/// <summary>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
readonly List<T> list;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
{
|
||||
list = new List<T>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public int Count
|
||||
{
|
||||
get { return list.Count; }
|
||||
}
|
||||
list = new List<T>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
public int Count
|
||||
{
|
||||
get { return list.Count; }
|
||||
}
|
||||
|
||||
public int MaxCount
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
get
|
||||
{
|
||||
return list.Count;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
return list.Count;
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
public T? Get(int position)
|
||||
set
|
||||
{
|
||||
if (position >= Count || position < 0) return null;
|
||||
return list[position];
|
||||
}
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount)
|
||||
if (value > 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
list.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position >= Count || Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
list.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if(position >= 0 && position < list.Count)
|
||||
{
|
||||
T? temp = list[position];
|
||||
list.RemoveAt(position);
|
||||
return temp;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for(int i = 0; i < list.Count; i++)
|
||||
{
|
||||
yield return list[i];
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return list[position];
|
||||
}
|
||||
public int Insert(T obj, IEqualityComparer<T>? comparer = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (list.Contains(obj, comparer)) throw new ObjectIsPresentInTheCollectionException(Count);
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
list.Add(obj);
|
||||
return Count - 1;
|
||||
}
|
||||
catch (ObjectIsPresentInTheCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
public int Insert(T obj, int position, IEqualityComparer<T>? comparer = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (comparer != null && list.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectIsPresentInTheCollectionException(Count);
|
||||
}
|
||||
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
list.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
catch (ObjectIsPresentInTheCollectionException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
|
||||
T? temp = list[position];
|
||||
list.RemoveAt(position);
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
yield return list[i];
|
||||
}
|
||||
}
|
||||
|
||||
public void CollectionSort(IComparer<T> comparer)
|
||||
{
|
||||
list.Sort(comparer);
|
||||
}
|
||||
}
|
@ -1,105 +1,148 @@
|
||||
using System;
|
||||
using HoistingCrane.Drawning;
|
||||
using HoistingCrane.Exceptions;
|
||||
using System.Linq;
|
||||
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
namespace HoistingCrane.CollectionGenericObjects;
|
||||
|
||||
public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : DrawningTrackedVehicle
|
||||
{
|
||||
public class MassivGenericObjects<T> : ICollectionGenericObjects<T> where T : class
|
||||
private T?[] arr;
|
||||
public MassivGenericObjects()
|
||||
{
|
||||
private T?[] arr;
|
||||
public MassivGenericObjects()
|
||||
arr = Array.Empty<T?>();
|
||||
}
|
||||
public int Count
|
||||
{
|
||||
get { return arr.Length; }
|
||||
}
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
{
|
||||
arr = Array.Empty<T?>();
|
||||
return arr.Length;
|
||||
}
|
||||
public int Count
|
||||
set
|
||||
{
|
||||
get { return arr.Length; }
|
||||
}
|
||||
public int MaxCount
|
||||
{
|
||||
get
|
||||
if (value > 0)
|
||||
{
|
||||
return arr.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
if (arr.Length > 0)
|
||||
{
|
||||
if (arr.Length > 0)
|
||||
{
|
||||
Array.Resize(ref arr, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
arr = new T?[value];
|
||||
}
|
||||
Array.Resize(ref arr, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
arr = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
public T? Get(int position)
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
return arr[position];
|
||||
}
|
||||
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (position >= 0 && position < arr.Length)
|
||||
if (arr.Contains(obj, comparer))
|
||||
{
|
||||
return arr[position];
|
||||
throw new ObjectIsPresentInTheCollectionException();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for(int i = 0; i < arr.Length; i++)
|
||||
for (int i = 0; i < Count; ++i)
|
||||
{
|
||||
yield return arr[i];
|
||||
}
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
return Insert(obj, 0);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
int copyPos = position - 1;
|
||||
|
||||
while (position < Count)
|
||||
{
|
||||
if (arr[position] == null)
|
||||
if (arr[i] == null)
|
||||
{
|
||||
arr[position] = obj;
|
||||
return position;
|
||||
arr[i] = obj;
|
||||
return i;
|
||||
}
|
||||
position++;
|
||||
}
|
||||
while (copyPos > 0)
|
||||
{
|
||||
if (arr[copyPos] == null)
|
||||
{
|
||||
arr[copyPos] = obj;
|
||||
return copyPos;
|
||||
}
|
||||
copyPos--;
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
catch (ObjectIsPresentInTheCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
return -1;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
}
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (comparer != null)
|
||||
{
|
||||
T? temp = arr[position];
|
||||
arr[position] = null;
|
||||
return temp;
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (comparer.Equals(arr[i], obj))
|
||||
{
|
||||
throw new ObjectIsPresentInTheCollectionException();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
if (arr[position] == null)
|
||||
{
|
||||
arr[position] = obj;
|
||||
return position;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 1; i < Count; ++i)
|
||||
{
|
||||
if (arr[position + i] == null)
|
||||
{
|
||||
arr[position + i] = obj;
|
||||
return position + i;
|
||||
}
|
||||
for (i = position - 1; i >= 0; i--)
|
||||
{
|
||||
if (arr[i] == null)
|
||||
{
|
||||
arr[i] = obj;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
return -1;
|
||||
}
|
||||
catch (ObjectIsPresentInTheCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (arr[position] == null) throw new ObjectNotFoundException(position);
|
||||
T? temp = arr[position];
|
||||
arr[position] = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < arr.Length; i++)
|
||||
{
|
||||
yield return arr[i];
|
||||
}
|
||||
}
|
||||
public void CollectionSort(IComparer<T> comparer)
|
||||
{
|
||||
T[] notNullArr = arr.OfType<T>().ToArray();
|
||||
Array.Sort(notNullArr, comparer);
|
||||
Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length);
|
||||
}
|
||||
}
|
||||
|
@ -1,200 +1,199 @@
|
||||
using HoistingCrane.Drawning;
|
||||
using System;
|
||||
using System.Configuration;
|
||||
using HoistingCrane.Exceptions;
|
||||
using System.Text;
|
||||
namespace HoistingCrane.CollectionGenericObjects;
|
||||
|
||||
namespace HoistingCrane.CollectionGenericObjects
|
||||
public class StorageCollection<T> where T : DrawningTrackedVehicle
|
||||
{
|
||||
public class StorageCollection<T> where T : DrawningTrackedVehicle
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> dict;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<CollectionInfo> Keys => dict.Keys.ToList();
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> dict;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => dict.Keys.ToList();
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
dict = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
var collectionInfo = new CollectionInfo(name, collectionType, " ");
|
||||
if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo))
|
||||
{
|
||||
dict = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (dict.ContainsKey(name)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
dict[name] = new MassivGenericObjects<T>();
|
||||
else if (collectionType == CollectionType.List)
|
||||
dict[name] = new ListGenericObjects<T>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
if (Keys.Contains(name))
|
||||
if (collectionType == CollectionType.Massive)
|
||||
{
|
||||
dict.Remove(name);
|
||||
dict.Add(collectionInfo, new MassivGenericObjects<T>());
|
||||
}
|
||||
if (collectionType == CollectionType.List)
|
||||
{
|
||||
dict.Add(collectionInfo, new ListGenericObjects<T>());
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
var key = dict.Keys.FirstOrDefault(k => k.name == name);
|
||||
if (key != null)
|
||||
{
|
||||
get
|
||||
{
|
||||
if (dict.ContainsKey(name))
|
||||
return dict[name];
|
||||
return null;
|
||||
}
|
||||
dict.Remove(key);
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
/// </summary>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
/// <returns></returns>
|
||||
public ICollectionGenericObjects<T>? this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (dict.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var key = dict.Keys.FirstOrDefault(k => k.name == name);
|
||||
if (key == null) { return null; }
|
||||
return dict[key];
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (dict.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in dict)
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in dict)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
writer.Write(sb);
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
writer.Write(sb);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
// /// Загрузка информации по грузовикам в хранилище из файла
|
||||
// /// </summary>
|
||||
// /// <param name="filename">Путь и имя файла</param>
|
||||
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
/// <summary>
|
||||
/// Загрузка информации по грузовикам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("В файле не присутствуют данные");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
throw new FormatException("В файле неверные данные");
|
||||
}
|
||||
dict.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 3)
|
||||
{
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new InvalidOperationException("Не удалось определить информацию о коллекции: " + record[0]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.collectionType) ?? throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
dict.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
if (elem?.CreateDrawningTrackedVehicle() is T crane)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTrackedVehicle() is T truck)
|
||||
try
|
||||
{
|
||||
if (collection.Insert(truck) == -1)
|
||||
if (collection.Insert(crane) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[2]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена");
|
||||
}
|
||||
}
|
||||
dict.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
dict.Add(collectionInfo, collection);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassivGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
CollectionType.Massive => new MassivGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace HoistingCrane.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: count" + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace HoistingCrane.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public class ObjectIsPresentInTheCollectionException : ApplicationException
|
||||
{
|
||||
public ObjectIsPresentInTheCollectionException(int objName) : base("В коллекции уже присустствует объект " + objName) { }
|
||||
public ObjectIsPresentInTheCollectionException() : base() { }
|
||||
protected ObjectIsPresentInTheCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace HoistingCrane.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
public ObjectNotFoundException() : base() { }
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace HoistingCrane.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
public 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 context) : base(info, context) { }
|
||||
}
|
||||
}
|
@ -1,248 +1,241 @@
|
||||
using HoistingCrane.CollectionGenericObjects;
|
||||
using HoistingCrane.Drawning;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using HoistingCrane.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
namespace HoistingCrane;
|
||||
|
||||
namespace HoistingCrane
|
||||
public partial class FormCarCollection : Form
|
||||
{
|
||||
public partial class FormCarCollection : Form
|
||||
private AbstractCompany? _company;
|
||||
|
||||
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
|
||||
/// <summary>
|
||||
/// Логгер
|
||||
/// </summary>
|
||||
private readonly ILogger logger;
|
||||
public FormCarCollection(ILogger<FormCarCollection> logger)
|
||||
{
|
||||
private AbstractCompany? _company;
|
||||
|
||||
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
|
||||
public FormCarCollection()
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
panelCompanyTool.Enabled = false;
|
||||
this.logger = logger;
|
||||
}
|
||||
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
panelCompanyTool.Enabled = false;
|
||||
}
|
||||
private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormCarConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetCrane);
|
||||
}
|
||||
private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle)
|
||||
{
|
||||
if (_company == null || drawningTrackedVehicle == null) return;
|
||||
try
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
panelCompanyTool.Enabled = false;
|
||||
}
|
||||
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
panelCompanyTool.Enabled = false;
|
||||
}
|
||||
private void CreateObject(string type)
|
||||
{
|
||||
DrawningTrackedVehicle drawning;
|
||||
if (_company == null) return;
|
||||
Random rand = new();
|
||||
switch (type)
|
||||
{
|
||||
case nameof(DrawningHoistingCrane):
|
||||
drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand), GetColor(rand), true, true);
|
||||
break;
|
||||
|
||||
case nameof(DrawningTrackedVehicle):
|
||||
drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand));
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
if ((_company + drawning) != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
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 buttonCreateHoistingCrane_Click(object sender, EventArgs e)
|
||||
{
|
||||
FormCarConfig form = new();
|
||||
form.Show();
|
||||
form.AddEvent(SetCar);
|
||||
}
|
||||
private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle)
|
||||
{
|
||||
if (_company == null || drawningTrackedVehicle == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + drawningTrackedVehicle != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
logger.LogInformation("Не удалось добавить кран {crane} в коллекцию", drawningTrackedVehicle.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonDeleteCar_Click(object sender, EventArgs e)
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка переполнения коллекции");
|
||||
logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonDeleteCar_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if ((_company - pos) != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален!");
|
||||
pictureBox.Image = _company.Show();
|
||||
logger.LogInformation("Удаление авто по индексу {pos}", pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos);
|
||||
}
|
||||
}
|
||||
private void buttonRefresh_Click(object sender, EventArgs e)
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
if (_company == null) return;
|
||||
pictureBox.Image = _company.Show();
|
||||
MessageBox.Show("Ошибка: отсутствует объект");
|
||||
logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
private void buttonGoToChek_Click(object sender, EventArgs e)
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
if (_company == null) return;
|
||||
DrawningTrackedVehicle? car = null;
|
||||
int count = 100;
|
||||
while (car == null)
|
||||
{
|
||||
car = _company.GetRandomObject();
|
||||
count--;
|
||||
if (count <= 0) break;
|
||||
}
|
||||
if (car == null) return;
|
||||
FormHoistingCrane form = new()
|
||||
{
|
||||
SetCar = car
|
||||
};
|
||||
form.ShowDialog();
|
||||
MessageBox.Show("Ошибка: неправильная позиция");
|
||||
logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
private void buttonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null) return;
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
private void buttonGoToChek_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null) return;
|
||||
DrawningTrackedVehicle? car = null;
|
||||
int count = 100;
|
||||
while (car == null)
|
||||
{
|
||||
car = _company.GetRandomObject();
|
||||
count--;
|
||||
if (count <= 0) break;
|
||||
}
|
||||
if (car == null) return;
|
||||
FormHoistingCrane form = new()
|
||||
{
|
||||
SetCar = car
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
/// </summary>
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
{
|
||||
listBoxCollection.Items.Clear();
|
||||
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
|
||||
string? colName = _storageCollection.Keys?[i].name;
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
string? colName = _storageCollection.Keys?[i];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
{
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
listBoxCollection.Items.Add(colName);
|
||||
}
|
||||
}
|
||||
private void buttonCollectionAdd_Click(object sender, EventArgs e)
|
||||
}
|
||||
private void buttonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
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;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text,
|
||||
collectionType);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
|
||||
return;
|
||||
}
|
||||
private void buttonDeleteCollection_Click(object sender, EventArgs e)
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
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();
|
||||
collectionType = CollectionType.Massive;
|
||||
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
|
||||
}
|
||||
private void buttonCreateCompany_Click(object sender, EventArgs e)
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
}
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new Garage(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTool.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
collectionType = CollectionType.List;
|
||||
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
private void buttonDeleteCollection_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
return;
|
||||
if (listBoxCollection.SelectedItem != null)
|
||||
{
|
||||
logger.LogInformation("Коллекция '{name}' успешно удалена", listBoxCollection.SelectedItem.ToString());
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
}
|
||||
private void buttonCreateCompany_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
ICollectionGenericObjects<DrawningTrackedVehicle>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
return;
|
||||
};
|
||||
switch (comboBoxSelectorCompany.Text)
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new Garage(pictureBox.Width, pictureBox.Height, collection);
|
||||
break;
|
||||
}
|
||||
panelCompanyTool.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
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
{
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName.ToString());
|
||||
}
|
||||
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)
|
||||
/// <summary>
|
||||
/// Обработка нажатия "Загразка"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if(openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
try
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -31,6 +31,7 @@ namespace HoistingCrane
|
||||
panelColorPurple.MouseDown += panel_MouseDown;
|
||||
buttonCancel.Click += (sender, e) => Close();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Привязка метода к событию
|
||||
/// </summary>
|
||||
|
@ -12,6 +12,18 @@
|
||||
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<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>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,18 +1,40 @@
|
||||
namespace HoistingCrane
|
||||
{
|
||||
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 FormCarCollection());
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
namespace HoistingCrane;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormCarCollection>());
|
||||
}
|
||||
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<FormCarCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
17
HoistingCrane/HoistingCrane/serilog.json
Normal file
17
HoistingCrane/HoistingCrane/serilog.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log.log"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
CollectionsStorage
|
||||
массив|Massive|25|EntityTrackedVehicle:100:100:Green;EntityHoistingCrane:100:100:Yellow:Black:False:False;EntityTrackedVehicle:100:100:Gray;
|
||||
список|List|2|EntityTrackedVehicle:100:100:Blue;EntityHoistingCrane:100:100:Gray:Black:True:True;
|
@ -1,2 +0,0 @@
|
||||
CollectionsStorage
|
||||
массив|Massive|24|EntityTrackedVehicle:100:100:Gray;EntityTrackedVehicle:100:100:Red;EntityTrackedVehicle:100:100:Blue;EntityTrackedVehicle:100:100:Yellow;EntityTrackedVehicle:100:100:Green;EntityTrackedVehicle:100:100:Black;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:Purple;EntityHoistingCrane:100:100:Green:Black:False:False;EntityHoistingCrane:100:100:Yellow:Gray:False:True;EntityHoistingCrane:100:100:Purple:Black:True:True;EntityTrackedVehicle:100:100:White;EntityHoistingCrane:100:100:White:Black:False:True;EntityTrackedVehicle:100:100:Green;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:White;EntityHoistingCrane:100:100:White:Black:False:False;EntityTrackedVehicle:100:100:White;EntityTrackedVehicle:100:100:Yellow;EntityTrackedVehicle:100:100:White;EntityHoistingCrane:100:100:Gray:Black:False:False;EntityTrackedVehicle:100:100:Black;
|
@ -1,3 +0,0 @@
|
||||
CollectionsStorage
|
||||
массив|Massive
|
||||
список|List
|
Loading…
Reference in New Issue
Block a user