Готовая лаба 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;
namespace HoistingCrane.CollectionGenericObjects
namespace HoistingCrane.CollectionGenericObjects;
public abstract class AbstractCompany
{
public abstract class AbstractCompany
{
/// <summary>
/// Ширина ячейки гаража
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 150;
protected readonly int _placeSizeWidth = 180;
/// <summary>
/// Высота ячейки гаража
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 90;
protected readonly int _placeSizeHeight = 100;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int pictureWidth;
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int pictureHeight;
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция автомобилей
/// Коллекция военных кораблей
/// </summary>
protected ICollectionGenericObjects<DrawningTrackedVehicle>? arr = null;
protected ICollectionGenericObjects<DrawningTrackedVehicle>? _collection = null;
/// <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
{
return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth);
}
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedVehicle> array)
{
pictureWidth = picWidth;
pictureHeight = picHeight;
arr = array;
arr.MaxCount = GetMaxCount;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.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)
{
return company.arr?.Remove(position);
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrackedVehicle? GetRandomObject()
{
Random rnd = new();
return arr?.Get(rnd.Next(GetMaxCount));
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
@ -62,18 +84,22 @@ namespace HoistingCrane.CollectionGenericObjects
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(pictureWidth, pictureHeight);
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
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);
}
catch (Exception) { }
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
@ -84,5 +110,5 @@ namespace HoistingCrane.CollectionGenericObjects
/// Расстановка объектов
/// </summary>
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
{

View File

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

View File

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

View File

@ -1,11 +1,9 @@
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>
@ -45,45 +43,65 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(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;
}
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 (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
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)
{
if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position);
T? temp = list[position];
list.RemoveAt(position);
return temp;
}
return null;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < list.Count; i++)
for (int i = 0; i < list.Count; 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;
public MassivGenericObjects()
{
@ -39,67 +41,108 @@ namespace HoistingCrane.CollectionGenericObjects
public T? Get(int position)
{
if (position >= 0 && position < arr.Length)
{
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
return arr[position];
}
return null;
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
try
{
if (arr.Contains(obj, comparer))
{
throw new ObjectIsPresentInTheCollectionException();
}
public IEnumerable<T?> GetItems()
for (int i = 0; i < Count; ++i)
{
for(int i = 0; i < arr.Length; i++)
if (arr[i] == null)
{
yield return arr[i];
arr[i] = obj;
return i;
}
}
public int Insert(T obj)
{
return Insert(obj, 0);
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
int copyPos = position - 1;
while (position < Count)
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
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)
{
arr[position] = obj;
return position;
}
position++;
}
while (copyPos > 0)
else
{
if (arr[copyPos] == null)
for (int i = 1; i < Count; ++i)
{
arr[copyPos] = obj;
return copyPos;
if (arr[position + i] == null)
{
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;
}
catch (ObjectIsPresentInTheCollectionException ex)
{
MessageBox.Show(ex.Message);
return -1;
}
}
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];
arr[position] = null;
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 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<string, ICollectionGenericObjects<T>> dict;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> dict;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => dict.Keys.ToList();
public List<CollectionInfo> Keys => dict.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
@ -32,7 +30,7 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary>
public StorageCollection()
{
dict = new Dictionary<string, ICollectionGenericObjects<T>>();
dict = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -41,12 +39,18 @@ namespace HoistingCrane.CollectionGenericObjects
/// <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>();
var collectionInfo = new CollectionInfo(name, collectionType, " ");
if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo))
{
if (collectionType == CollectionType.Massive)
{
dict.Add(collectionInfo, new MassivGenericObjects<T>());
}
if (collectionType == CollectionType.List)
{
dict.Add(collectionInfo, new ListGenericObjects<T>());
}
}
}
/// <summary>
/// Удаление коллекции
@ -54,9 +58,10 @@ namespace HoistingCrane.CollectionGenericObjects
/// <param name="name">Название коллекции</param>
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>
@ -68,9 +73,9 @@ namespace HoistingCrane.CollectionGenericObjects
{
get
{
if (dict.ContainsKey(name))
return dict[name];
return null;
var key = dict.Keys.FirstOrDefault(k => k.name == name);
if (key == null) { return null; }
return dict[key];
}
}
/// <summary>
@ -78,11 +83,11 @@ namespace HoistingCrane.CollectionGenericObjects
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (dict.Count == 0)
{
return false;
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -94,21 +99,16 @@ namespace HoistingCrane.CollectionGenericObjects
{
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)
{
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())
@ -124,61 +124,62 @@ namespace HoistingCrane.CollectionGenericObjects
writer.Write(sb);
}
}
return true;
}
/// <summary>
// /// Загрузка информации по грузовикам в хранилище из файла
// /// </summary>
// /// <param name="filename">Путь и имя файла</param>
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
/// Загрузка информации по грузовикам в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <exception cref="Exception"></exception>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new InvalidOperationException("В файле не присутствуют данные");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new FormatException("В файле неверные данные");
}
dict.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
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);
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)
{
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>
@ -195,6 +196,4 @@ namespace HoistingCrane.CollectionGenericObjects
_ => 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.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;
public FormCarCollection()
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger logger;
public FormCarCollection(ILogger<FormCarCollection> logger)
{
InitializeComponent();
_storageCollection = new();
panelCompanyTool.Enabled = false;
this.logger = logger;
}
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);
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)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
logger.LogInformation("Добавлен объект {nameObject}", drawningTrackedVehicle.GetType().Name);
}
else
{
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)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
@ -99,15 +65,30 @@ namespace HoistingCrane
{
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);
}
}
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)
@ -142,7 +123,7 @@ namespace HoistingCrane
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -153,21 +134,22 @@ namespace HoistingCrane
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.LogInformation("Не удалось добавить коллекцию: не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
logger.LogInformation("Создана коллекция {nameCol} , название: {name}", collectionType, textBoxCollectionName.Text);
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void buttonDeleteCollection_Click(object sender, EventArgs e)
@ -179,11 +161,17 @@ namespace HoistingCrane
}
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();
}
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
@ -194,7 +182,7 @@ namespace HoistingCrane
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
};
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
@ -214,13 +202,16 @@ namespace HoistingCrane
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName.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>
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();
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;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка метода к событию
/// </summary>

View File

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

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]
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());
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