2 Commits
Lab6 ... Lab8

Author SHA1 Message Date
c7a6718b99 Лабораторная работа № 8 2024-06-05 18:16:12 +04:00
3139efc43b 7 лабораторная работа 2024-06-04 14:18:52 +04:00
20 changed files with 642 additions and 125 deletions

View File

@@ -35,7 +35,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth)*(_pictureHeight / (_placeSizeHeight + 60));
/// <summary>
/// Конструктор
@@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedVehicle excavator)
{
return company._collection.Insert(excavator);
return company._collection.Insert(excavator, new DrawningTrackedVehicleEqutables());
}
/// <summary>
@@ -70,7 +70,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static DrawningTrackedVehicle operator -(AbstractCompany company, int position)
{
return company._collection.Remove(position);
return company._collection?.Remove(position) ?? null;
}
/// <summary>
@@ -103,6 +103,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTrackedVehicle?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@@ -0,0 +1,76 @@
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
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>
private 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)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
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)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -1,4 +1,5 @@
using ProjectExcavator.Drawnings;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
@@ -35,6 +36,7 @@ internal class GarageService : AbstractCompany
g.DrawLine(pen, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2, j * _placeSizeWidth + Indent, i * _placeSizeHeight * 2 + _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
@@ -42,18 +44,20 @@ internal class GarageService : AbstractCompany
int LevelWidth = 0;
int LevelHeight = 0;
for (int i = 0; i < _collection?.Count; i++)
{
if (_collection.Get(i) != null)
for (int i = 0; i < _collection?.Count ; i++)
{
if(_collection?.Get(i)== null )
{
return;
}
try
{
_collection?.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition((_pictureWidth - 190) - _placeSizeWidth * LevelWidth, 20 + (_placeSizeHeight + 60) * LevelHeight);
}
if (LevelHeight + 1 > _pictureHeight / (_placeSizeHeight + 60))
catch (ObjectNotFoundException)
{
return;
break;
}
if (LevelWidth + 1 < _pictureWidth / _placeSizeWidth)
@@ -65,6 +69,11 @@ internal class GarageService : AbstractCompany
LevelWidth = 0;
LevelHeight++;
}
if (LevelHeight >= _pictureHeight / (_placeSizeHeight + 60))
{
return;
}
}
}
}

View File

@@ -21,16 +21,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</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>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@@ -56,4 +58,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,4 +1,6 @@
namespace ProjectExcavator.CollectionGenericObjects;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -42,41 +44,47 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
else
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj,IEqualityComparer<T?>? comparer = null)
{
//проверка, что не превышено максимальное количество элементов
//вставка в конец набора
if (_collection.Count > _maxCount)
if (Count + 1 > MaxCount)
{
return -1;
throw new CollectionOverflowException();
}
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException();
}
_collection.Add(obj);
return 1;
}
public int Insert(T obj, int position)
{
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка, что не превышено максимальное количество элементов
// проверка позиции
// вставка по позиции
if ((_collection.Count > _maxCount) || (position < 0 || position > Count))
if (_collection.Count + 1 < _maxCount)
{
return -1;
throw new CollectionOverflowException();
}
_collection.Insert(position, obj);
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(position);
}
_collection.Insert(position, obj);
return 1;
}
@@ -85,10 +93,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// проверка позиции
// удаление объекта из списка
if (position < 0 || position > Count)
{
return null;
}
if(position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position];
_collection.RemoveAt(position);
return obj;
@@ -103,4 +108,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectExcavator.CollectionGenericObjects;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -52,7 +54,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position < 0 || position > Count-1)
{
return null;
throw new PositionOutOfCollectionException(position);
}
else
{
@@ -60,21 +62,30 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
//Вставка в свободное место набора
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(index);
}
return Insert(obj, 0);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
//Проверка позиции
//Проверка, что элемент массива по этой позиции пустой, если нет, то
//Ищется свободное место после этой позиции и идет вставка туда
//если нет после, ищем до вставка
if (position >= Count || position < 0) return -1;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(position);
}
if (_collection[position] == null)
{
@@ -105,7 +116,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
behind_position --;
}
return -1;
throw new CollectionOverflowException(Count);
}
}
@@ -115,10 +126,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
// Проверка позиции
// Удаление объекта из массива, присвоив элементу массива значение null
if (position < 0 || _collection[position] == null || position > Count -1)
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
@@ -131,4 +143,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@@ -1,4 +1,5 @@
using ProjectExcavator.Drawnings;
using ProjectExcavator.Exceptions;
using ProjectExcavator.Drawnings;
using System.Text;
namespace ProjectExcavator.CollectionGenericObjects;
@@ -10,16 +11,16 @@ namespace ProjectExcavator.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningTrackedVehicle
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@@ -42,7 +43,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@@ -52,7 +53,8 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
@@ -63,10 +65,10 @@ public class StorageCollection<T>
case CollectionType.None:
return;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { });
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { });
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
}
}
@@ -78,8 +80,12 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
_storages.Remove(collectionInfo);
}
/// <summary>
@@ -92,8 +98,9 @@ public class StorageCollection<T>
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, "");
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
}
}
@@ -103,11 +110,11 @@ public class StorageCollection<T>
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@@ -120,17 +127,16 @@ public class StorageCollection<T>
using (StreamWriter fs = new StreamWriter(filename))
{
fs.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@@ -143,7 +149,6 @@ public class StorageCollection<T>
sb.Clear();
}
}
return true;
}
/// <summary>
@@ -151,50 +156,57 @@ public class StorageCollection<T>
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new ArgumentException("В файле нет данных");
if (str != _collectionKey.ToString())
return false;
throw new InvalidDataException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T boat)
if (elem?.CreateDrawningTrackedVehicle() is T trackedVehicle)
{
if (collection.Insert(boat) == -1)
return false;
try
{
if (collection.Insert(trackedVehicle) == -1)
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
return true;
}
/// <summary>

View File

@@ -0,0 +1,34 @@
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByColor : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityTrackedVehicle == null)
{
return -1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return 1;
}
if(x.EntityTrackedVehicle.BodyColor.Name != y.EntityTrackedVehicle.BodyColor.Name)
{
return x.EntityTrackedVehicle.BodyColor.Name.CompareTo(y.EntityTrackedVehicle.BodyColor.Name);
}
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}

View File

@@ -0,0 +1,37 @@
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByType : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityTrackedVehicle == null)
{
return -1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return 1;
}
if (!x.GetType().Name.Equals(y.GetType().Name))
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}

View File

@@ -0,0 +1,67 @@
using ProjectExcavator.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningTrackedVehicleEqutables : IEqualityComparer<DrawningTrackedVehicle?>
{
public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null)
{
return false;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed)
{
return false;
}
if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight)
{
return false;
}
if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor)
{
return false;
}
if (x is DrawningExcavator && y is DrawningExcavator)
{
EntityExcavator entityX = (EntityExcavator)x.EntityTrackedVehicle;
EntityExcavator entityY = (EntityExcavator)y.EntityTrackedVehicle;
if(entityX.Bucket != entityY.Bucket)
{
return false;
}
if(entityX.Supports != entityY.Supports)
{
return false;
}
if(entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrackedVehicle obj)
{
return obj.GetHashCode();
}
}

View File

@@ -1,5 +1,5 @@
using ProjectExcavator.Drawnings;
using ProjectExcavator.Entities;
using ProjectExcavator.Entities;
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Расширение для класса TrackedVehicle

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectExistsException : ApplicationException
{
public ObjectExistsException(int count) : base("Вставка существуюзего объекта") { }
public ObjectExistsException() : base() { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTrackedVehicle);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@@ -100,9 +104,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top;
buttonRefresh.Location = new Point(3, 240);
buttonRefresh.Location = new Point(1, 174);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(215, 40);
buttonRefresh.Size = new Size(215, 30);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -111,7 +115,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top;
maskedTextBoxPosition.Location = new Point(3, 115);
maskedTextBoxPosition.Location = new Point(4, 59);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(215, 27);
@@ -121,9 +125,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top;
buttonGoToCheck.Location = new Point(3, 194);
buttonGoToCheck.Location = new Point(4, 138);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(215, 40);
buttonGoToCheck.Size = new Size(214, 30);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -132,7 +136,7 @@
// ButtonRemoveExcavator
//
ButtonRemoveExcavator.Anchor = AnchorStyles.Top;
ButtonRemoveExcavator.Location = new Point(3, 148);
ButtonRemoveExcavator.Location = new Point(3, 92);
ButtonRemoveExcavator.Name = "ButtonRemoveExcavator";
ButtonRemoveExcavator.Size = new Size(215, 40);
ButtonRemoveExcavator.TabIndex = 4;
@@ -306,6 +310,26 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(1, 210);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(215, 27);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 243);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(213, 27);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormExcavatorCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@@ -355,5 +379,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,6 +1,7 @@
using ProjectExcavator.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectExcavator.CollectionGenericObjects;
using ProjectExcavator.Drawnings;
using System.Windows.Forms;
using ProjectExcavator.Exceptions;
namespace ProjectExcavator;
/// <summary>
@@ -13,6 +14,11 @@ public partial class FormExcavatorCollection : Form
/// </summary>
private readonly StorageCollection<DrawningTrackedVehicle> _storageCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Компания
/// </summary>
@@ -21,10 +27,12 @@ public partial class FormExcavatorCollection : Form
/// <summary>
/// Конструктор
/// </summary>
public FormExcavatorCollection()
public FormExcavatorCollection(ILogger<FormExcavatorCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@@ -60,19 +68,29 @@ public partial class FormExcavatorCollection : Form
/// <param name="trackedVehicle"></param>
private void SetTrackedVehicle(DrawningTrackedVehicle? trackedVehicle)
{
if (_company == null || trackedVehicle == null)
try
{
return;
}
if (_company == null || trackedVehicle == null)
{
return;
}
if (_company + trackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + trackedVehicle != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + trackedVehicle.GetDataForSave());
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("В коллекции превышено допустимое количество элементов:");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
}
@@ -85,21 +103,41 @@ public partial class FormExcavatorCollection : Form
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
_logger.LogWarning("Удаление объекта из несуществующей коллекции");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if ((_company - pos) != null)
try
{
MessageBox.Show("Объект удален!");
pictureBox.Image = _company.Show();
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null)
{
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
}
}
else
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Удаление вне рамках коллекции");
_logger.LogWarning($"Удаление объекта за пределами коллекции {pos} ");
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Объект по позиции " + pos + " не существует ");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@@ -162,13 +200,12 @@ public partial class FormExcavatorCollection : Form
/// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
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)
{
@@ -180,9 +217,8 @@ public partial class FormExcavatorCollection : Form
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена коллекция типа {type} с названием {name}", collectionType, textBoxCollectionName.Text);
RefreshListBoxItems();
}
/// <summary>
@@ -197,12 +233,22 @@ public partial class FormExcavatorCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString());
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@@ -214,7 +260,7 @@ public partial class FormExcavatorCollection : Form
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);
@@ -263,13 +309,16 @@ public partial class FormExcavatorCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@@ -283,15 +332,53 @@ public partial class FormExcavatorCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
RefreshListBoxItems();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawningTrackedVehicleCompareByColor());
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawningTrackedVehicleCompareByType());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawningTrackedVehicle?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectExcavator
{
internal static class Program
@@ -11,7 +16,28 @@ namespace ProjectExcavator
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormExcavatorCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormExcavatorCollection>());
}
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<FormExcavatorCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}appSetting.json").Build()).CreateLogger());
});
}
}
}

View File

@@ -8,6 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +31,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appSetting.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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