7 Commits

Author SHA1 Message Date
642e19f10d готовая 8 лаб работа 2024-05-20 13:12:41 +04:00
e8b3ec816b изменения 2024-05-14 14:29:17 +04:00
0e3a9a94a8 Лабораторная работа 8 2024-05-14 14:27:41 +04:00
b63e7a1c12 изменения 2024-05-07 19:28:47 +04:00
65771b774b изменения 2024-05-07 19:27:21 +04:00
c60abd65d7 Лабороторная работа 7 2024-05-06 14:07:43 +04:00
6b8ef29396 лабораторная работа 6 2024-05-05 16:18:45 +04:00
27 changed files with 1162 additions and 117 deletions

View File

@@ -1,4 +1,5 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using ProjectGasMachine.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -53,7 +54,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -64,7 +65,18 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningMachine machine)
{
return company._collection.Insert(machine, 0);
try
{
return company._collection.Insert(machine, 0, new DrawningMachineEqutables());
}
catch (ObjectAlreadyInCollectionException)
{
return -1;
}
catch (CollectionOverflowException)
{
return -1;
}
}
/// <summary>
@@ -87,14 +99,21 @@ public abstract class AbstractCompany
public DrawningMachine? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
try
{
return _collection?.Get(rnd.Next(GetMaxCount));
}
catch (ObjectNotFoundException)
{
return null;
}
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
@@ -103,13 +122,26 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningMachine? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningMachine? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException)
{
continue;
}
}
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningMachine?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@@ -1,4 +1,5 @@
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -41,21 +42,28 @@ public class Autopark : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
if (_collection?.Get(i) != null)
try
{
int x = 5 + _placeSizeWidth * n;
int y = (-3 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
if (_collection?.Get(i) != null)
{
int x = 5 + _placeSizeWidth * n;
int y = (-3 + _placeSizeHeight * (_pictureHeight / _placeSizeHeight - 1)) - _placeSizeHeight * m;
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(x, y);
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
{
n = 0;
m++;
}
}
if (n < _pictureWidth / _placeSizeWidth)
n++;
else
catch (ObjectNotFoundException)
{
n = 0;
m++;
break;
}
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.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,10 +1,11 @@
using System;
using ProjectGasMachine.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@@ -21,22 +22,24 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </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>
/// Удаление объекта из коллекции с конкретной позиции
@@ -51,4 +54,21 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,4 +1,9 @@
namespace ProjectGasMachine.CollectionGenericObjects;

using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System.Linq;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -19,7 +24,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@@ -31,30 +39,52 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount || position < 0 || position > Count)
// TODO выброс ошибки, если выход за границы списка
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
return -1;
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyInCollectionException();
}
}
if (position < 0 || position > Count)
{
throw new PositionOutOfCollectionException(position);
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj);
@@ -63,9 +93,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Remove(int position)
{
// TODO выброс ошибки, если выход за границы списка
if (position < 0 || position > Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
@@ -73,4 +104,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -1,4 +1,8 @@
namespace ProjectGasMachine.CollectionGenericObjects;
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using System.Linq;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -15,8 +19,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -33,6 +42,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// конструктор
/// </summary>
@@ -43,17 +54,36 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position > Count)
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO вставка в свободное место набора
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningMachine>).Equals(obj as DrawningMachine, item as DrawningMachine))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@@ -62,13 +92,28 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position > Count)
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если переполнение
if (comparer != null)
{
return -1;
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningMachine>).Equals(obj as DrawningMachine, item as DrawningMachine))
{
throw new ObjectAlreadyInCollectionException();
}
}
}
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
@@ -82,7 +127,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[i] == null)
{
_collection[i] = obj;
return position;
return i;
}
}
@@ -91,23 +136,42 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[i] == null)
{
_collection[i] = obj;
return position;
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position < 0 || position > Count || _collection[position] == null)
// TODO выброс ошибки, если выход за границы массива
// TODO выброс ошибки, если объект пустой
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;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -1,28 +1,44 @@
namespace ProjectGasMachine.CollectionGenericObjects;
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// класс-хранилище
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningMachine
{
/// <summary>
/// словарь (хранилище) с коллекциями
/// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
private Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@@ -30,21 +46,21 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
public void AddCollection(CollectionInfo info)
{
if (name == null || _storages.ContainsKey(name))
if (info == null || _storages.ContainsKey(info))
{
return;
}
if (collectionType == CollectionType.Massive)
if (info.CollectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(info, new MassiveGenericObjects<T>());
}
if (collectionType == CollectionType.List)
if (info.CollectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(info, new ListGenericObjects<T>());
}
}
@@ -52,14 +68,14 @@ public class StorageCollection<T>
/// Удаление коллекции
/// </summary>
/// <param name="name"></param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo info)
{
if (name == null || !_storages.ContainsKey(name))
if (info == null || !_storages.ContainsKey(info))
{
return;
}
_storages.Remove(name);
_storages.Remove(info);
}
/// <summary>
@@ -67,17 +83,150 @@ public class StorageCollection<T>
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo info]
{
get
{
if (_storages.ContainsKey(name))
if (_storages.ContainsKey(info))
{
return _storages[name];
return _storages[info];
}
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new NullReferenceException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new StreamWriter(filename))
{
sw.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader sr = new(filename))
{
string line = sr.ReadLine();
if (line == null || line.Length == 0)
{
throw new FileFormatException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
throw new FileFormatException("В файле неверные данные");
}
_storages.Clear();
while ((line = sr.ReadLine()) != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningMachine() is T machine)
{
try
{
if (collection.Insert(machine, new DrawningMachineEqutables()) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new OverflowException("Коллекция переполнена", ex);
}
catch (ObjectAlreadyInCollectionException ex)
{
throw new InvalidOperationException("Объект уже присутствует в коллекции", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -23,6 +23,15 @@ public class DrawningGasMachine : DrawningMachine
EntityGas = new EntityMachine(speed, weight, bodyColor, additionalColor, gas, beacon);
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="gasmachine"></param>
public DrawningGasMachine(EntityGas? gasmachine) : base(gasmachine)
{
EntityGas = gasmachine;
}
public override void DrawTransport(Graphics g)
{

View File

@@ -97,6 +97,18 @@ public class DrawningMachine
_drawningMachineWidth = drawningMachineWidth;
_pictureHeight = drawningMachineHeight;
}
/// <summary>
/// Конструктор для класса Extention
/// </summary>
/// <param name="machine"></param>
public DrawningMachine(EntityGas? machine) : this()
{
EntityGas = machine;
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@@ -0,0 +1,48 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningMachineCompareByColor : IComparer<DrawningMachine?>
{
public int Compare(DrawningMachine? x, DrawningMachine? y)
{
if (x == null || x.EntityGas == null)
{
return 1;
}
if (y == null || y.EntityGas == null)
{
return -1;
}
var bodyColorCompare = y.EntityGas.BodyColor.Name.CompareTo(x.EntityGas.BodyColor.Name);
if (bodyColorCompare != 0)
{
return bodyColorCompare;
}
if (x is DrawningGasMachine && y is DrawningGasMachine)
{
var additionalColorCompare = (y.EntityGas as EntityMachine).AdditionalColor.Name.CompareTo(
(x.EntityGas as EntityMachine).AdditionalColor.Name);
if (additionalColorCompare != 0)
{
return additionalColorCompare;
}
}
var speedCompare = y.EntityGas.Speed.CompareTo(x.EntityGas.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityGas.Weight.CompareTo(x.EntityGas.Weight);
}
}

View File

@@ -0,0 +1,36 @@
using ProjectGasMachine.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.CollectionGenericObjects;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningMachineCompareByType : IComparer<DrawningMachine?>
{
public int Compare(DrawningMachine? x, DrawningMachine? y)
{
if (x == null || x.EntityGas == null)
{
return 1;
}
if (y == null || y.EntityGas == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return y.GetType().Name.CompareTo(x.GetType().Name);
}
var speedCompare = y.EntityGas.Speed.CompareTo(x.EntityGas.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityGas.Weight.CompareTo(x.EntityGas.Weight);
}
}

View File

@@ -0,0 +1,68 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningMachineEqutables : IEqualityComparer<DrawningMachine?>
{
public bool Equals(DrawningMachine? x, DrawningMachine? y)
{
if (x == null || x.EntityGas == null)
{
return false;
}
if (y == null || y.EntityGas == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityGas.Speed != y.EntityGas.Speed)
{
return false;
}
if (x.EntityGas.Weight != y.EntityGas.Weight)
{
return false;
}
if (x.EntityGas.BodyColor != y.EntityGas.BodyColor)
{
return false;
}
if (x is DrawningGasMachine && y is DrawningGasMachine)
{
// TODO доделать логику сравнения дополнительных параметров
if ((x.EntityGas as EntityMachine)?.AdditionalColor !=
(y.EntityGas as EntityMachine)?.AdditionalColor)
{
return false;
}
if ((x.EntityGas as EntityMachine)?.Gas !=
(y.EntityGas as EntityMachine)?.Gas)
{
return false;
}
if ((x.EntityGas as EntityMachine)?.Beacon !=
(y.EntityGas as EntityMachine)?.Beacon)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningMachine? obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,56 @@
using ProjectGasMachine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGasMachine.Drawnings;
public static class ExtentionDrawningGas
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningMachine? CreateDrawningMachine(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityGas? machine = EntityMachine.CreateEntityMachine(strs);
if (machine != null)
{
return new DrawningGasMachine(machine);
}
machine = EntityGas.CreateEntityGas(strs);
if (machine != null)
{
return new DrawningMachine(machine);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningMachine">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningMachine drawningMachine)
{
string[]? array = drawningMachine?.EntityGas?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -51,4 +51,29 @@ public class EntityGas
{
BodyColor = newColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityGas), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityGas? CreateEntityGas(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityGas))
{
return null;
}
return new EntityGas(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@@ -36,4 +36,34 @@ public class EntityMachine : EntityGas
{
AdditionalColor = newColor;
}
public override string[] GetStringRepresentation()
{
return new[]
{
nameof(EntityMachine),
Speed.ToString(),
Weight.ToString(),
BodyColor.Name,
AdditionalColor.Name,
Gas.ToString(),
Beacon.ToString(),
};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityMachine? CreateEntityMachine(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityMachine))
{
return null;
}
return new EntityMachine(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]),
Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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 ProjectGasMachine.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class ObjectAlreadyInCollectionException : ApplicationException
{
public ObjectAlreadyInCollectionException(int count) : base("Такой объект уже присутствует в коллекции. Позиция " + count) { }
public ObjectAlreadyInCollectionException() : base() { }
public ObjectAlreadyInCollectionException(string message) : base(message) { }
public ObjectAlreadyInCollectionException(string message, Exception exception) : base(message, exception) { }
protected ObjectAlreadyInCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.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,22 @@
using System.Runtime.Serialization;
namespace ProjectGasMachine.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

@@ -16,13 +16,13 @@ public partial class FormGasConfig : Form
/// <summary>
/// событие для передачи объекта
/// </summary>
private event MachineDelegate? MachineDelegate;
private event Action<DrawningMachine>? MachineDelegate;
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="warshipDelegate"></param>
public void AddEvent(MachineDelegate machineDelegate)
/// <param name="machineDelegate"></param>
public void AddEvent(Action<DrawningMachine>? machineDelegate)
{
MachineDelegate += machineDelegate;
}

View File

@@ -46,10 +46,19 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
FileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,15 +68,17 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(727, 0);
groupBoxTools.Location = new Point(780, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(196, 543);
groupBoxTools.Size = new Size(196, 557);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(ButtonSortByColor);
panelCompanyTools.Controls.Add(ButtonSortByType);
panelCompanyTools.Controls.Add(buttonAddMachine);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@@ -75,15 +86,15 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 323);
panelCompanyTools.Location = new Point(3, 292);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(190, 217);
panelCompanyTools.Size = new Size(190, 262);
panelCompanyTools.TabIndex = 9;
//
// buttonAddMachine
//
buttonAddMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddMachine.Location = new Point(10, 14);
buttonAddMachine.Location = new Point(10, 3);
buttonAddMachine.Name = "buttonAddMachine";
buttonAddMachine.Size = new Size(174, 33);
buttonAddMachine.TabIndex = 2;
@@ -93,7 +104,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 83);
maskedTextBoxPosition.Location = new Point(3, 42);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(184, 23);
@@ -103,7 +114,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(10, 185);
buttonRefresh.Location = new Point(10, 144);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(174, 32);
buttonRefresh.TabIndex = 7;
@@ -114,7 +125,7 @@
// buttonRemoveMachine
//
buttonRemoveMachine.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveMachine.Location = new Point(10, 112);
buttonRemoveMachine.Location = new Point(10, 71);
buttonRemoveMachine.Name = "buttonRemoveMachine";
buttonRemoveMachine.Size = new Size(174, 32);
buttonRemoveMachine.TabIndex = 5;
@@ -125,7 +136,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(10, 150);
buttonGoToCheck.Location = new Point(10, 109);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(174, 29);
buttonGoToCheck.TabIndex = 6;
@@ -135,7 +146,7 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(6, 294);
buttonCreateCompany.Location = new Point(6, 263);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(184, 23);
buttonCreateCompany.TabIndex = 7;
@@ -155,12 +166,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(190, 239);
panelStorage.Size = new Size(190, 209);
panelStorage.TabIndex = 8;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 206);
buttonCollectionDel.Location = new Point(3, 176);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(184, 23);
buttonCollectionDel.TabIndex = 6;
@@ -174,7 +185,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 106);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(184, 94);
listBoxCollection.Size = new Size(184, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
@@ -231,7 +242,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 265);
comboBoxSelectorCompany.Location = new Point(6, 234);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(184, 23);
comboBoxSelectorCompany.TabIndex = 0;
@@ -240,19 +251,83 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(727, 543);
pictureBox.Size = new Size(780, 557);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(976, 24);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
FileToolStripMenuItem.Size = new Size(48, 20);
FileToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByColor
//
ButtonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByColor.Location = new Point(10, 217);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(174, 32);
ButtonSortByColor.TabIndex = 9;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ButtonSortByType.Location = new Point(10, 182);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(174, 29);
ButtonSortByType.TabIndex = 8;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// FormGasMachineCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 543);
ClientSize = new Size(976, 581);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormGasMachineCollection";
Text = "Коллекция газовозов";
groupBoxTools.ResumeLayout(false);
@@ -261,7 +336,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -284,5 +362,13 @@
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@@ -1,5 +1,7 @@
using ProjectGasMachine.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectGasMachine.CollectionGenericObjects;
using ProjectGasMachine.Drawnings;
using ProjectGasMachine.Exceptions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectGasMachine
@@ -19,13 +21,19 @@ namespace ProjectGasMachine
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// конструктор
/// </summary>
public FormGasMachineCollection()
public FormGasMachineCollection(ILogger<FormGasMachineCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@@ -47,15 +55,29 @@ namespace ProjectGasMachine
{
return;
}
if (_company + machine != -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + machine != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {machine.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
@@ -67,7 +89,7 @@ namespace ProjectGasMachine
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMachine_Click(object sender, EventArgs e)
private void ButtonAddMachine_Click(object sender, EventArgs e)
{
FormGasConfig form = new();
// TODO передать метод +
@@ -93,15 +115,25 @@ namespace ProjectGasMachine
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show();
}
}
else
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
catch (PositionOutOfCollectionException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError($"Ошибка: {ex.Message}");
}
}
@@ -167,6 +199,7 @@ namespace ProjectGasMachine
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: Заполнены не все данные для добавления коллекции");
return;
}
@@ -179,8 +212,10 @@ namespace ProjectGasMachine
{
collectionType = CollectionType.List;
}
CollectionInfo collectionInfo = new CollectionInfo(textBoxCollectionName.Text, collectionType, string.Empty);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_storageCollection.AddCollection(collectionInfo);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text} типа: {collectionType}");
RerfreshListBoxItems();
}
@@ -201,7 +236,10 @@ namespace ProjectGasMachine
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
_storageCollection.DelCollection(collectionInfo);
_logger.LogInformation($"Удалена коллекция: {listBoxCollection.SelectedItem.ToString()}");
RerfreshListBoxItems();
}
@@ -213,7 +251,7 @@ namespace ProjectGasMachine
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);
@@ -234,7 +272,8 @@ namespace ProjectGasMachine
return;
}
ICollectionGenericObjects<DrawningMachine>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
CollectionInfo collectionInfo = new CollectionInfo(listBoxCollection.SelectedItem.ToString(), CollectionType.None, string.Empty);
ICollectionGenericObjects<DrawningMachine>? collection = _storageCollection[collectionInfo];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
@@ -250,5 +289,86 @@ namespace ProjectGasMachine
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из фала: {filename}", openFileDialog.FileName);
}
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 ButtonSortByType_Click(object sender, EventArgs e)
{
CompareMachines(new DrawningMachineCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareMachines(new DrawningMachineCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareMachines(IComparer<DrawningMachine?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}

View File

@@ -117,4 +117,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@@ -1,8 +0,0 @@
using ProjectGasMachine.Drawnings;
namespace ProjectGasMachine;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="warship"></param>
public delegate void MachineDelegate(DrawningMachine machine);

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectGasMachine
{
internal static class Program
@@ -11,7 +16,26 @@ namespace ProjectGasMachine
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormGasMachineCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormGasMachineCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services
.AddSingleton<FormGasMachineCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}
}

View File

@@ -13,6 +13,18 @@
<None Include="ProjectGasMachine.csproj.user" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -28,4 +40,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
{
"AllowedHosts": "*",
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "C:\\Пользователи\\artem\\OneDrive\\Рабочий стол\\уник\\ООП\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} | {Level:u} | {SourceContext} | {Message:1j}{NewLine}{Exception}"
}
}
]
}
}