diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs
index c689725..ba4efdf 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs
@@ -1,88 +1,114 @@
using HoistingCrane.Drawning;
-namespace HoistingCrane.CollectionGenericObjects
+namespace HoistingCrane.CollectionGenericObjects;
+public abstract class AbstractCompany
{
- public abstract class AbstractCompany
+ ///
+ /// Размер места (ширина)
+ ///
+ protected readonly int _placeSizeWidth = 180;
+
+ ///
+ /// Размер места (высота)
+ ///
+ protected readonly int _placeSizeHeight = 100;
+
+ ///
+ /// Ширина окна
+ ///
+ protected readonly int _pictureWidth;
+
+ ///
+ /// Высота окна
+ ///
+ protected readonly int _pictureHeight;
+
+ ///
+ /// Коллекция военных кораблей
+ ///
+ protected ICollectionGenericObjects? _collection = null;
+
+ ///
+ /// Вычисление максимального количества элементов, которые можно разместить в окне
+ ///
+ private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
+
+ ///
+ /// Конструктор
+ ///
+ /// Ширина окна
+ /// Высота окна
+ /// Коллекция военных кораблей
+ public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection)
{
- ///
- /// Ширина ячейки гаража
- ///
- protected readonly int _placeSizeWidth = 150;
- ///
- /// Высота ячейки гаража
- ///
- protected readonly int _placeSizeHeight = 90;
- ///
- /// Ширина окна
- ///
- protected readonly int pictureWidth;
- ///
- /// Высота окна
- ///
- protected readonly int pictureHeight;
- ///
- /// Коллекция автомобилей
- ///
- protected ICollectionGenericObjects? arr = null;
- ///
- /// Максимальное количество гаражей
- ///
- private int GetMaxCount
+ _pictureWidth = picWidth;
+ _pictureHeight = picHeight;
+ _collection = collection;
+ _collection.MaxCount = GetMaxCount;
+ }
+
+ ///
+ /// Перегрузка оператора сложения для класса
+ ///
+ /// Компания
+ /// Добавляемый объект
+ ///
+ public static int operator +(AbstractCompany company, DrawningTrackedVehicle warship)
+ {
+ return company._collection.Insert(warship);
+ }
+
+ ///
+ /// Перегрузка оператора удаления для класса
+ ///
+ /// Компания
+ /// Номер удаляемого объекта
+ ///
+ public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
+ {
+ return company._collection.Remove(position);
+ }
+
+ ///
+ /// Получение случайного объекта из коллекции
+ ///
+ ///
+ public DrawningTrackedVehicle? GetRandomObject()
+ {
+ Random rnd = new();
+ return _collection?.Get(rnd.Next(GetMaxCount));
+ }
+
+ ///
+ /// Вывод всей коллекции
+ ///
+ ///
+ 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 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));
- }
-
- ///
- /// Вывод всей коллекции
- ///
- ///
- 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) { }
}
- ///
- /// Вывод заднего фона
- ///
- ///
- protected abstract void DrawBackgound(Graphics g);
-
- ///
- /// Расстановка объектов
- ///
- protected abstract void SetObjectsPosition();
+ return bitmap;
}
+
+ ///
+ /// Вывод заднего фона
+ ///
+ ///
+ protected abstract void DrawBackgound(Graphics g);
+
+ ///
+ /// Расстановка объектов
+ ///
+ protected abstract void SetObjectsPosition();
}
+
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs
new file mode 100644
index 0000000..fbc1fc7
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionInfo.cs
@@ -0,0 +1,66 @@
+using System.Diagnostics.CodeAnalysis;
+
+namespace HoistingCrane.CollectionGenericObjects
+{
+ public class CollectionInfo : IEquatable
+ {
+ ///
+ /// Название
+ ///
+ public string name { get; private set; }
+ ///
+ /// Тип
+ ///
+ public CollectionType collectionType { get; private set; }
+ ///
+ /// Описание
+ ///
+ public string description { get; private set; }
+ ///
+ /// Разделитель
+ ///
+ public static readonly string _separator = "-";
+
+ ///
+ /// Конструктор
+ ///
+ ///
+ ///
+ ///
+ 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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs
index 22ffa84..93433c2 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs
@@ -1,5 +1,4 @@
-using System;
-namespace HoistingCrane.CollectionGenericObjects
+namespace HoistingCrane.CollectionGenericObjects
{
public enum CollectionType
{
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs
index 6ba0162..9455238 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs
@@ -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;
}
-
}
}
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs
index ae99e89..121887b 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs
@@ -1,7 +1,9 @@
-namespace HoistingCrane.CollectionGenericObjects
+using HoistingCrane.Drawning;
+
+namespace HoistingCrane.CollectionGenericObjects
{
public interface ICollectionGenericObjects
- where T: class
+ where T : class
{
///
/// Кол-во объектов в коллекции
@@ -15,15 +17,17 @@
/// Добавление элемента в коллекцию
///
///
+ /// /// Сравнение двух объектов
///
- int Insert(T obj);
+ int Insert(T obj, IEqualityComparer? comparer = null);
///
/// Добавление элемента в коллекцию на определенную позицию
///
///
///
+ /// Сравнение двух объектов
///
- int Insert(T obj, int position);
+ int Insert(T obj, int position, IEqualityComparer? comparer = null);
///
/// Удаление элемента из коллекции по его позиции
///
@@ -45,5 +49,10 @@
///
///
IEnumerable GetItems();
+ ///
+ /// Сортировка коллекции
+ ///
+ ///
+ void CollectionSort(IComparer comparer);
}
-}
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs
index 6f07ab5..b37f51c 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs
@@ -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 : ICollectionGenericObjects where T : class
{
- public class ListGenericObjects : ICollectionGenericObjects where T : class
+ ///
+ /// Список объектов, которые храним
+ ///
+ readonly List list;
+ ///
+ /// Конструктор
+ ///
+ public ListGenericObjects()
{
- ///
- /// Список объектов, которые храним
- ///
- readonly List list;
- ///
- /// Конструктор
- ///
- public ListGenericObjects()
- {
- list = new List();
- }
- ///
- /// Максимально допустимое число объектов в списке
- ///
- private int _maxCount;
- public int Count
- {
- get { return list.Count; }
- }
+ list = new List();
+ }
+ ///
+ /// Максимально допустимое число объектов в списке
+ ///
+ 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)
- {
- return -1;
- }
- list.Add(obj);
- return Count;
- }
-
- public int Insert(T obj, int position)
- {
- if (position < 0 || position >= Count || Count == _maxCount)
+ if (value > 0)
{
- 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 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? 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? 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 GetItems()
+ {
+ for (int i = 0; i < list.Count; i++)
+ {
+ yield return list[i];
+ }
+ }
+
+ public void CollectionSort(IComparer comparer)
+ {
+ list.Sort(comparer);
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs
index fbd554d..5c95f93 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs
@@ -1,105 +1,148 @@
-using System;
+using HoistingCrane.Drawning;
+using HoistingCrane.Exceptions;
+using System.Linq;
-namespace HoistingCrane.CollectionGenericObjects
+namespace HoistingCrane.CollectionGenericObjects;
+
+public class MassivGenericObjects : ICollectionGenericObjects where T : DrawningTrackedVehicle
{
- public class MassivGenericObjects : ICollectionGenericObjects where T : class
+ private T?[] arr;
+ public MassivGenericObjects()
{
- private T?[] arr;
- public MassivGenericObjects()
+ arr = Array.Empty();
+ }
+ public int Count
+ {
+ get { return arr.Length; }
+ }
+ public int MaxCount
+ {
+ get
{
- arr = Array.Empty();
+ 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? comparer = null)
+ {
+ try
{
- if (position >= 0 && position < arr.Length)
+ if (arr.Contains(obj, comparer))
{
- return arr[position];
+ throw new ObjectIsPresentInTheCollectionException();
}
- return null;
- }
-
- public IEnumerable 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? 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 GetItems()
+ {
+ for (int i = 0; i < arr.Length; i++)
+ {
+ yield return arr[i];
+ }
+ }
+ public void CollectionSort(IComparer comparer)
+ {
+ T[] notNullArr = arr.OfType().ToArray();
+ Array.Sort(notNullArr, comparer);
+ Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length);
+ }
}
diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs
index 0aa587f..4d7f6c8 100644
--- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs
+++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs
@@ -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 where T : DrawningTrackedVehicle
{
- public class StorageCollection where T : DrawningTrackedVehicle
+ ///
+ /// Словарь (хранилище) с коллекциями
+ ///
+ readonly Dictionary> dict;
+ ///
+ /// Возвращение списка названий коллекций
+ ///
+ public List Keys => dict.Keys.ToList();
+ ///
+ /// Ключевое слово, с которого должен начинаться файл
+ ///
+ private readonly string _collectionKey = "CollectionsStorage";
+ ///
+ /// Разделитель для записи ключа и значения элемента словаря
+ ///
+ private readonly string _separatorForKeyValue = "|";
+ ///
+ /// Разделитель для записей коллекции данных в файл
+ ///
+ private readonly string _separatorItems = ";";
+ ///
+ /// Конструктор
+ ///
+ public StorageCollection()
{
- ///
- /// Словарь (хранилище) с коллекциями
- ///
- readonly Dictionary> dict;
- ///
- /// Возвращение списка названий коллекций
- ///
- public List Keys => dict.Keys.ToList();
- ///
- /// Ключевое слово, с которого должен начинаться файл
- ///
- private readonly string _collectionKey = "CollectionsStorage";
- ///
- /// Разделитель для записи ключа и значения элемента словаря
- ///
- private readonly string _separatorForKeyValue = "|";
- ///
- /// Разделитель для записей коллекции данных в файл
- ///
- private readonly string _separatorItems = ";";
- ///
- /// Конструктор
- ///
- public StorageCollection()
+ dict = new Dictionary>();
+ }
+ ///
+ /// Добавление коллекции в хранилище
+ ///
+ /// Название коллекции
+ /// тип коллекции
+ public void AddCollection(string name, CollectionType collectionType)
+ {
+ var collectionInfo = new CollectionInfo(name, collectionType, " ");
+ if (!string.IsNullOrEmpty(name) && !Keys.Contains(collectionInfo))
{
- dict = new Dictionary>();
- }
- ///
- /// Добавление коллекции в хранилище
- ///
- /// Название коллекции
- /// тип коллекции
- 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();
- else if (collectionType == CollectionType.List)
- dict[name] = new ListGenericObjects();
- }
- ///
- /// Удаление коллекции
- ///
- /// Название коллекции
- public void DelCollection(string name)
- {
- if (Keys.Contains(name))
+ if (collectionType == CollectionType.Massive)
{
- dict.Remove(name);
+ dict.Add(collectionInfo, new MassivGenericObjects());
+ }
+ if (collectionType == CollectionType.List)
+ {
+ dict.Add(collectionInfo, new ListGenericObjects());
}
}
- ///
- /// Доступ к коллекции
- ///
- /// Название коллекции
- ///
- public ICollectionGenericObjects? this[string name]
+ }
+ ///
+ /// Удаление коллекции
+ ///
+ /// Название коллекции
+ 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);
}
- ///
- /// Сохранение информации по автомобилям в хранилище в файл
- ///
- /// Путь и имя файла
- /// true - сохранение прошло успешно, false - ошибка при сохранении данных
- public bool SaveData(string filename)
+ }
+ ///
+ /// Доступ к коллекции
+ ///
+ /// Название коллекции
+ ///
+ public ICollectionGenericObjects? 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];
+ }
+ }
+ ///
+ /// Сохранение информации по автомобилям в хранилище в файл
+ ///
+ /// Путь и имя файла
+ /// true - сохранение прошло успешно, false - ошибка при сохранении данных
+ 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> value in dict)
+ foreach (KeyValuePair> 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;
}
+ }
- ///
- // /// Загрузка информации по грузовикам в хранилище из файла
- // ///
- // /// Путь и имя файла
- // /// true - загрузка прошла успешно, false - ошибка при загрузке данных
- public bool LoadData(string filename)
+ ///
+ /// Загрузка информации по грузовикам в хранилище из файла
+ ///
+ ///
+ ///
+ 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? collection = StorageCollection.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? collection = StorageCollection.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);
}
}
- ///
- /// Создание коллекции по типу
- ///
- ///
- ///
- private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
- {
- return collectionType switch
- {
- CollectionType.Massive => new MassivGenericObjects(),
- CollectionType.List => new ListGenericObjects(),
- _ => null,
- };
- }
-
}
-}
+ ///
+ /// Создание коллекции по типу
+ ///
+ ///
+ ///
+ private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType)
+ {
+ return collectionType switch
+ {
+ CollectionType.Massive => new MassivGenericObjects(),
+ CollectionType.List => new ListGenericObjects(),
+ _ => null,
+ };
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/Exception/CollectionOverflowException.cs b/HoistingCrane/HoistingCrane/Exception/CollectionOverflowException.cs
new file mode 100644
index 0000000..f3bd541
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/Exception/CollectionOverflowException.cs
@@ -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) { }
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/Exception/ObjectIsPresentInTheCollectionException.cs b/HoistingCrane/HoistingCrane/Exception/ObjectIsPresentInTheCollectionException.cs
new file mode 100644
index 0000000..074762a
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/Exception/ObjectIsPresentInTheCollectionException.cs
@@ -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) { }
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/Exception/ObjectNotFoundException.cs b/HoistingCrane/HoistingCrane/Exception/ObjectNotFoundException.cs
new file mode 100644
index 0000000..2c0a220
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/Exception/ObjectNotFoundException.cs
@@ -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) { }
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/Exception/PositionOutOfCollectionException.cs b/HoistingCrane/HoistingCrane/Exception/PositionOutOfCollectionException.cs
new file mode 100644
index 0000000..7c50a2d
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/Exception/PositionOutOfCollectionException.cs
@@ -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) { }
+ }
+}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs
index 612b6a7..9f06102 100644
--- a/HoistingCrane/HoistingCrane/FormCarCollection.cs
+++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs
@@ -1,250 +1,243 @@
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 _storageCollection;
+ ///
+ /// Логгер
+ ///
+ private readonly ILogger logger;
+ public FormCarCollection(ILogger logger)
{
- private AbstractCompany? _company;
-
- private readonly StorageCollection _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();
+ }
- ///
- /// Обновление списка в listBoxCollection
- ///
- private void RerfreshListBoxItems()
+ ///
+ /// Обновление списка в listBoxCollection
+ ///
+ 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? 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();
- ///
- /// Обработка нажатия "Сохранение"
- ///
- ///
- ///
- private void saveToolStripMenuItem_Click(object sender, EventArgs e)
- {
- if (saveFileDialog.ShowDialog() == DialogResult.OK)
- {
- if (_storageCollection.SaveData(saveFileDialog.FileName))
- {
- MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- else
- {
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- }
+ }
+ private void buttonCreateCompany_Click(object sender, EventArgs e)
+ {
- ///
- /// Обработка нажатия "Загразка"
- ///
- ///
- ///
- private void loadToolStripMenuItem_Click(object sender, EventArgs e)
+ if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
- if(openFileDialog.ShowDialog() == DialogResult.OK)
+ MessageBox.Show("Коллекция не выбрана");
+ return;
+ }
+ ICollectionGenericObjects? 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();
+ }
+
+ ///
+ /// Обработка нажатия "Сохранение"
+ ///
+ ///
+ ///
+ private void saveToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ try
{
- if (_storageCollection.LoadData(openFileDialog.FileName))
- {
- MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
- RerfreshListBoxItems();
- }
- 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);
}
}
}
-}
\ No newline at end of file
+ ///
+ /// Обработка нажатия "Загразка"
+ ///
+ ///
+ ///
+ private void loadToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ if (openFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ try
+ {
+ _storageCollection.LoadData(openFileDialog.FileName);
+ RerfreshListBoxItems();
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName.ToString());
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ logger.LogError("Ошибка: {Message}", ex.Message);
+ }
+ }
+ }
+
+}
diff --git a/HoistingCrane/HoistingCrane/FormCarConfig.cs b/HoistingCrane/HoistingCrane/FormCarConfig.cs
index 2d0cd40..306b03f 100644
--- a/HoistingCrane/HoistingCrane/FormCarConfig.cs
+++ b/HoistingCrane/HoistingCrane/FormCarConfig.cs
@@ -31,6 +31,7 @@ namespace HoistingCrane
panelColorPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
+
///
/// Привязка метода к событию
///
diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj
index 69ac652..3f2e375 100644
--- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj
+++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj
@@ -12,6 +12,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
True
diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs
index 79d96ff..41f37ff 100644
--- a/HoistingCrane/HoistingCrane/Program.cs
+++ b/HoistingCrane/HoistingCrane/Program.cs
@@ -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
+ [STAThread]
+ static void Main()
{
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
+ ApplicationConfiguration.Initialize();
+ ServiceCollection services = new();
+ ConfigureServices(services);
+ using ServiceProvider serviceProvider = services.BuildServiceProvider();
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ private static void ConfigureServices(ServiceCollection services)
+ {
+
+ string[] path = Directory.GetCurrentDirectory().Split('\\');
+ string pathNeed = "";
+ for (int i = 0; i < path.Length - 3; i++)
{
- // To customize application configuration such as set high DPI settings or default font,
- // see https://aka.ms/applicationconfiguration.
- ApplicationConfiguration.Initialize();
- Application.Run(new FormCarCollection());
-
+ pathNeed += path[i] + "\\";
}
+
+
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(new LoggerConfiguration()
+ .ReadFrom.Configuration(new ConfigurationBuilder()
+ .AddJsonFile($"{pathNeed}serilog.json")
+ .Build())
+ .CreateLogger());
+ });
}
}
\ No newline at end of file
diff --git a/HoistingCrane/HoistingCrane/serilog.json b/HoistingCrane/HoistingCrane/serilog.json
new file mode 100644
index 0000000..6660c8d
--- /dev/null
+++ b/HoistingCrane/HoistingCrane/serilog.json
@@ -0,0 +1,17 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Debug",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "log.log"
+ }
+ }
+ ],
+ "Properties": {
+ "Application": "Sample"
+ }
+ }
+}
\ No newline at end of file
diff --git a/Файл_для_лабораторной_6.txt b/Файл_для_лабораторной_6.txt
deleted file mode 100644
index 9ad6433..0000000
--- a/Файл_для_лабораторной_6.txt
+++ /dev/null
@@ -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;
\ No newline at end of file
diff --git a/Файл_с_машинами.txt b/Файл_с_машинами.txt
deleted file mode 100644
index ec76705..0000000
--- a/Файл_с_машинами.txt
+++ /dev/null
@@ -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;
\ No newline at end of file
diff --git a/допка3.txt b/допка3.txt
deleted file mode 100644
index 24b0dfa..0000000
--- a/допка3.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-CollectionsStorage
-массив|Massive
-список|List
\ No newline at end of file