Готовая лаба 7

This commit is contained in:
sqdselo 2024-06-05 07:14:35 +04:00
commit 919febed18
20 changed files with 871 additions and 627 deletions

View File

@ -1,59 +1,81 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
namespace HoistingCrane.CollectionGenericObjects namespace HoistingCrane.CollectionGenericObjects;
public abstract class AbstractCompany
{ {
public abstract class AbstractCompany
{
/// <summary> /// <summary>
/// Ширина ячейки гаража /// Размер места (ширина)
/// </summary> /// </summary>
protected readonly int _placeSizeWidth = 150; protected readonly int _placeSizeWidth = 180;
/// <summary> /// <summary>
/// Высота ячейки гаража /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 90; protected readonly int _placeSizeHeight = 100;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
protected readonly int pictureWidth; protected readonly int _pictureWidth;
/// <summary> /// <summary>
/// Высота окна /// Высота окна
/// </summary> /// </summary>
protected readonly int pictureHeight; protected readonly int _pictureHeight;
/// <summary> /// <summary>
/// Коллекция автомобилей /// Коллекция военных кораблей
/// </summary> /// </summary>
protected ICollectionGenericObjects<DrawningTrackedVehicle>? arr = null; protected ICollectionGenericObjects<DrawningTrackedVehicle>? _collection = null;
/// <summary> /// <summary>
/// Максимальное количество гаражей /// Вычисление максимального количества элементов, которые можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount 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)
{ {
get _pictureWidth = picWidth;
{ _pictureHeight = picHeight;
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth); _collection = collection;
} _collection.MaxCount = GetMaxCount;
}
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) /// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="warship">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedVehicle warship)
{ {
return company.arr?.Insert(car) ?? -1; 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) public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
{ {
return company.arr?.Remove(position); return company._collection.Remove(position);
} }
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrackedVehicle? GetRandomObject() public DrawningTrackedVehicle? GetRandomObject()
{ {
Random rnd = new(); Random rnd = new();
return arr?.Get(rnd.Next(GetMaxCount)); return _collection?.Get(rnd.Next(GetMaxCount));
} }
/// <summary> /// <summary>
@ -62,18 +84,22 @@ namespace HoistingCrane.CollectionGenericObjects
/// <returns></returns> /// <returns></returns>
public Bitmap? Show() public Bitmap? Show()
{ {
Bitmap bitmap = new(pictureWidth, pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackgound(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (arr?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningTrackedVehicle? obj = arr?.Get(i); try
{
DrawningTrackedVehicle? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
@ -84,5 +110,5 @@ namespace HoistingCrane.CollectionGenericObjects
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
}
} }

View File

@ -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();
}
}
}

View File

@ -1,5 +1,4 @@
using System; namespace HoistingCrane.CollectionGenericObjects
namespace HoistingCrane.CollectionGenericObjects
{ {
public enum CollectionType public enum CollectionType
{ {

View File

@ -8,8 +8,8 @@ namespace HoistingCrane.CollectionGenericObjects
} }
protected override void DrawBackgound(Graphics g) protected override void DrawBackgound(Graphics g)
{ {
int width = pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
for (int i = 0; i < width; i++) for (int i = 0; i < width; i++)
{ {
@ -22,18 +22,18 @@ namespace HoistingCrane.CollectionGenericObjects
} }
protected override void SetObjectsPosition() protected override void SetObjectsPosition()
{ {
int countWidth = pictureWidth / _placeSizeWidth; int countWidth = _pictureWidth / _placeSizeWidth;
int countHeight = pictureHeight / _placeSizeHeight; int countHeight = _pictureHeight / _placeSizeHeight;
int currentPosWidth = countWidth - 1; int currentPosWidth = countWidth - 1;
int currentPosHeight = countHeight - 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); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); _collection?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15);
} }
if (currentPosWidth > 0) if (currentPosWidth > 0)
@ -47,7 +47,6 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
break; break;
} }
} }
} }

View File

@ -1,7 +1,9 @@
namespace HoistingCrane.CollectionGenericObjects using HoistingCrane.Drawning;
namespace HoistingCrane.CollectionGenericObjects
{ {
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T: class where T : class
{ {
/// <summary> /// <summary>
/// Кол-во объектов в коллекции /// Кол-во объектов в коллекции
@ -15,15 +17,17 @@
/// Добавление элемента в коллекцию /// Добавление элемента в коллекцию
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// /// <param name="comparer">Сравнение двух объектов</param>
/// <returns></returns> /// <returns></returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T>? comparer = null);
/// <summary> /// <summary>
/// Добавление элемента в коллекцию на определенную позицию /// Добавление элемента в коллекцию на определенную позицию
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <param name="position"></param> /// <param name="position"></param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns></returns> /// <returns></returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T>? comparer = null);
/// <summary> /// <summary>
/// Удаление элемента из коллекции по его позиции /// Удаление элемента из коллекции по его позиции
/// </summary> /// </summary>
@ -45,5 +49,10 @@
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer"></param>
void CollectionSort(IComparer<T> comparer);
} }
} }

View File

@ -1,11 +1,9 @@
using System; using HoistingCrane.Drawning;
using System.CodeDom.Compiler; using HoistingCrane.Exceptions;
using System.Windows.Forms.VisualStyles; 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>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
@ -45,45 +43,65 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return list[position]; return list[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T>? comparer = null)
{ {
if (Count == _maxCount) 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; return -1;
} }
list.Add(obj); }
return Count; public int Insert(T obj, int position, IEqualityComparer<T>? comparer = null)
{
try
{
if (comparer != null && list.Contains(obj, comparer))
{
throw new ObjectIsPresentInTheCollectionException(Count);
} }
public int Insert(T obj, int position) if (Count == _maxCount) throw new CollectionOverflowException(Count);
{
if (position < 0 || position >= Count || Count == _maxCount) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{
return -1;
}
list.Insert(position, obj); list.Insert(position, obj);
return position; return position;
} }
catch (ObjectIsPresentInTheCollectionException ex)
{
Console.WriteLine(ex.Message);
return -1;
}
}
public T? Remove(int position) public T? Remove(int position)
{ {
if(position >= 0 && position < list.Count) if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
{
T? temp = list[position]; T? temp = list[position];
list.RemoveAt(position); list.RemoveAt(position);
return temp; return temp;
} }
return null;
}
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for(int i = 0; i < list.Count; i++) for (int i = 0; i < list.Count; i++)
{ {
yield return list[i]; yield return list[i];
} }
} }
public void CollectionSort(IComparer<T> comparer)
{
list.Sort(comparer);
} }
} }

View File

@ -1,9 +1,11 @@
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; private T?[] arr;
public MassivGenericObjects() public MassivGenericObjects()
{ {
@ -39,67 +41,108 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < arr.Length) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{
return arr[position]; return arr[position];
} }
return null; public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
try
{
if (arr.Contains(obj, comparer))
{
throw new ObjectIsPresentInTheCollectionException();
} }
for (int i = 0; i < Count; ++i)
public IEnumerable<T?> GetItems()
{ {
for(int i = 0; i < arr.Length; i++) if (arr[i] == null)
{ {
yield return arr[i]; arr[i] = obj;
return i;
} }
} }
throw new CollectionOverflowException(Count);
public int Insert(T obj)
{
return Insert(obj, 0);
} }
catch (ObjectIsPresentInTheCollectionException ex)
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{ {
MessageBox.Show(ex.Message);
return -1; return -1;
} }
int copyPos = position - 1; }
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
while (position < Count)
{ {
try
{
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(arr[i], obj))
{
throw new ObjectIsPresentInTheCollectionException();
}
}
}
if (arr[position] == null) if (arr[position] == null)
{ {
arr[position] = obj; arr[position] = obj;
return position; return position;
} }
position++; else
}
while (copyPos > 0)
{ {
if (arr[copyPos] == null) for (int i = 1; i < Count; ++i)
{ {
arr[copyPos] = obj; if (arr[position + i] == null)
return copyPos; {
arr[position + i] = obj;
return position + i;
} }
copyPos--; 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; return -1;
} }
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
}
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= 0 && position < Count) if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
{ if (arr[position] == null) throw new ObjectNotFoundException(position);
T? temp = arr[position]; T? temp = arr[position];
arr[position] = null; arr[position] = null;
return temp; return temp;
} }
return null;
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);
}
} }

View File

@ -1,20 +1,18 @@
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using HoistingCrane.Exceptions;
using System.Configuration;
using System.Text; 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>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> dict; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> dict;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => dict.Keys.ToList(); public List<CollectionInfo> Keys => dict.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
/// </summary> /// </summary>
@ -32,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
dict = new Dictionary<string, ICollectionGenericObjects<T>>(); dict = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -41,12 +39,18 @@ namespace HoistingCrane.CollectionGenericObjects
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
if (dict.ContainsKey(name)) return; var collectionInfo = new CollectionInfo(name, collectionType, " ");
if (collectionType == CollectionType.None) return; if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo))
else if (collectionType == CollectionType.Massive) {
dict[name] = new MassivGenericObjects<T>(); if (collectionType == CollectionType.Massive)
else if (collectionType == CollectionType.List) {
dict[name] = new ListGenericObjects<T>(); dict.Add(collectionInfo, new MassivGenericObjects<T>());
}
if (collectionType == CollectionType.List)
{
dict.Add(collectionInfo, new ListGenericObjects<T>());
}
}
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -54,9 +58,10 @@ namespace HoistingCrane.CollectionGenericObjects
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
if (Keys.Contains(name)) var key = dict.Keys.FirstOrDefault(k => k.name == name);
if (key != null)
{ {
dict.Remove(name); dict.Remove(key);
} }
} }
/// <summary> /// <summary>
@ -68,9 +73,9 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
get get
{ {
if (dict.ContainsKey(name)) var key = dict.Keys.FirstOrDefault(k => k.name == name);
return dict[name]; if (key == null) { return null; }
return null; return dict[key];
} }
} }
/// <summary> /// <summary>
@ -78,11 +83,11 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (dict.Count == 0) if (dict.Count == 0)
{ {
return false; throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -94,21 +99,16 @@ namespace HoistingCrane.CollectionGenericObjects
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in dict) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in dict)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
@ -124,61 +124,62 @@ namespace HoistingCrane.CollectionGenericObjects
writer.Write(sb); writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
// /// Загрузка информации по грузовикам в хранилище из файла /// Загрузка информации по грузовикам в хранилище из файла
// /// </summary> /// </summary>
// /// <param name="filename">Путь и имя файла</param> /// <param name="filename"></param>
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <exception cref="Exception"></exception>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new InvalidOperationException("В файле не присутствуют данные");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new FormatException("В файле неверные данные");
} }
dict.Clear(); dict.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new InvalidOperationException("Не удалось определить информацию о коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.collectionType) ?? throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
if (collection == null) collection.MaxCount = Convert.ToInt32(record[1]);
{ string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningTrackedVehicle() is T truck) if (elem?.CreateDrawningTrackedVehicle() is T crane)
{ {
if (collection.Insert(truck) == -1) try
{ {
return false; if (collection.Insert(crane) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[2]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена");
} }
} }
} }
dict.Add(record[0], collection); dict.Add(collectionInfo, collection);
} }
return true;
} }
} }
/// <summary> /// <summary>
@ -195,6 +196,4 @@ namespace HoistingCrane.CollectionGenericObjects
_ => null, _ => null,
}; };
} }
}
} }

View File

@ -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) { }
}
}

View File

@ -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) { }
}
}

View File

@ -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) { }
}
}

View File

@ -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) { }
}
}

View File

@ -1,96 +1,62 @@
using HoistingCrane.CollectionGenericObjects; using HoistingCrane.CollectionGenericObjects;
using HoistingCrane.Drawning; using HoistingCrane.Drawning;
using System; using HoistingCrane.Exceptions;
using System.Collections.Generic; using Microsoft.Extensions.Logging;
using System.ComponentModel; namespace HoistingCrane;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HoistingCrane public partial class FormCarCollection : Form
{ {
public partial class FormCarCollection : Form
{
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection; private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
public FormCarCollection() /// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection(ILogger<FormCarCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
panelCompanyTool.Enabled = false; panelCompanyTool.Enabled = false;
this.logger = logger;
} }
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{ {
panelCompanyTool.Enabled = false; 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) private void buttonCreateHoistingCrane_Click(object sender, EventArgs e)
{ {
FormCarConfig form = new(); FormCarConfig form = new();
form.Show(); form.Show();
form.AddEvent(SetCar); form.AddEvent(SetCrane);
} }
private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle)
{ {
if (_company == null || drawningTrackedVehicle == null) if (_company == null || drawningTrackedVehicle == null) return;
try
{ {
return;
}
if (_company + drawningTrackedVehicle != -1) if (_company + drawningTrackedVehicle != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
logger.LogInformation("Не удалось добавить кран {crane} в коллекцию", drawningTrackedVehicle.GetType().Name);
} }
} }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Ошибка переполнения коллекции");
logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonDeleteCar_Click(object sender, EventArgs e) private void buttonDeleteCar_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
return; return;
@ -99,15 +65,30 @@ namespace HoistingCrane
{ {
return; return;
} }
try
{
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if ((_company - pos) != null) if ((_company - pos) != null)
{ {
MessageBox.Show("Объект удален!"); MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
logger.LogInformation("Удаление авто по индексу {pos}", pos);
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
logger.LogInformation("Не удалось удалить авто из коллекции по индексу {pos}", pos);
}
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Ошибка: отсутствует объект");
logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Ошибка: неправильная позиция");
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
private void buttonRefresh_Click(object sender, EventArgs e) private void buttonRefresh_Click(object sender, EventArgs e)
@ -142,7 +123,7 @@ namespace HoistingCrane
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -153,21 +134,22 @@ namespace HoistingCrane
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
collectionType = CollectionType.Massive; collectionType = CollectionType.Massive;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
} }
else if (radioButtonList.Checked) else if (radioButtonList.Checked)
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void buttonDeleteCollection_Click(object sender, EventArgs e) private void buttonDeleteCollection_Click(object sender, EventArgs e)
@ -179,11 +161,17 @@ namespace HoistingCrane
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
return; return;
if (listBoxCollection.SelectedItem != null)
{
logger.LogInformation("Коллекция '{name}' успешно удалена", listBoxCollection.SelectedItem.ToString());
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
@ -194,7 +182,7 @@ namespace HoistingCrane
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} };
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Хранилище":
@ -214,13 +202,16 @@ namespace HoistingCrane
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName.ToString());
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -232,17 +223,19 @@ namespace HoistingCrane
/// <param name="e"></param> /// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e) private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems(); RerfreshListBoxItems();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName.ToString());
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -31,6 +31,7 @@ namespace HoistingCrane
panelColorPurple.MouseDown += panel_MouseDown; panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
/// <summary> /// <summary>
/// Привязка метода к событию /// Привязка метода к событию
/// </summary> /// </summary>

View File

@ -12,6 +12,18 @@
<None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" /> <None Remove="CollectionGenericObjects\MassivGenericObjects.cs~RF2955bcc.TMP" />
</ItemGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,18 +1,40 @@
namespace HoistingCrane using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace HoistingCrane;
internal static class Program
{ {
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormCarCollection()); 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());
});
} }
} }

View File

@ -0,0 +1,17 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log"
}
}
],
"Properties": {
"Application": "Sample"
}
}
}

View File

@ -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;

View File

@ -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;

View File

@ -1,3 +0,0 @@
CollectionsStorage
массив|Massive
список|List