Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 35fa426532 | |||
| 2db4595ab4 | |||
| 265eb071be |
@@ -59,7 +59,7 @@ public abstract class AbstractCompany
|
||||
/// <returns></returns>
|
||||
public static int operator +(AbstractCompany company, DrawningPropelledArtillery propelledartillery)
|
||||
{
|
||||
return company._collection.Insert(propelledartillery);
|
||||
return company._collection.Insert(propelledartillery, new DrawiningPropelledArtilleryEqutables());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -114,4 +114,11 @@ public abstract class AbstractCompany
|
||||
/// Расстановка объектов
|
||||
/// </summary>
|
||||
protected abstract void SetObjectsPosition();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
public void Sort(IComparer<DrawningPropelledArtillery?> comparer) => _collection?.CollectionSort(comparer);
|
||||
}
|
||||
|
||||
@@ -41,11 +41,12 @@ public class ArtilleryBase : AbstractCompany
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
try
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4);
|
||||
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4);
|
||||
}
|
||||
catch (Exception) { };
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@@ -14,20 +15,22 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <summary>
|
||||
/// Установка максимального количества элементов
|
||||
/// </summary>
|
||||
int MaxCount { get; set; }
|
||||
int MaxCount { set; get; }
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="obj">Добавляемый объект</param>
|
||||
/// /// <param name="comparer">Cравнение двух объектов</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">Cравнение двух объектов</param>
|
||||
/// <returns>true - вставка прошла удачно, false - вставка неудалась</returns>
|
||||
int Insert(T obj, int position);
|
||||
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
|
||||
/// <summary>
|
||||
/// Удаление объекта из коллекции с конкретной позиции
|
||||
/// </summary>
|
||||
@@ -49,4 +52,9 @@ public interface ICollectionGenericObjects<T>
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
/// <summary>
|
||||
/// Сортировка коллекции
|
||||
/// </summary>
|
||||
/// <param name="comparer">Сравнитель объектов</param>
|
||||
void CollectionSort(IComparer<T?> comparer);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
using SelfPropelledArtilleryUnit.Drawnings;
|
||||
using SelfPropelledArtilleryUnit.Exceptions;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects
|
||||
{
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
@@ -7,11 +12,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
public int MaxCount
|
||||
{
|
||||
@@ -27,8 +32,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -38,33 +41,39 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0) 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)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
if (Count == _maxCount) return -1;
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectIsEqualException();
|
||||
}
|
||||
}
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (Count == _maxCount) return -1;
|
||||
if (position >= Count || position < 0) return -1;
|
||||
if (comparer != null)
|
||||
{
|
||||
if (_collection.Contains(obj, comparer))
|
||||
{
|
||||
throw new ObjectIsEqualException();
|
||||
}
|
||||
}
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
@@ -76,4 +85,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
_collection.Sort(comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
using SelfPropelledArtilleryUnit.Drawnings;
|
||||
using SelfPropelledArtilleryUnit.Exceptions;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
@@ -34,19 +37,29 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
public T? Get(int position)
|
||||
public T Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= _collection.Length || position < 0) return null;
|
||||
if (position >= _collection.Length || position < 0) 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 вставка в свободное место набора
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? item in _collection)
|
||||
{
|
||||
if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
|
||||
throw new ObjectIsEqualException();
|
||||
}
|
||||
}
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
@@ -57,17 +70,19 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
++index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return -1;
|
||||
if (comparer != null)
|
||||
{
|
||||
foreach (T? item in _collection)
|
||||
{
|
||||
if ((comparer as IEqualityComparer<DrawningPropelledArtillery>).Equals(obj as DrawningPropelledArtillery, item as DrawningPropelledArtillery))
|
||||
throw new ObjectIsEqualException();
|
||||
}
|
||||
}
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
@@ -93,14 +108,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
--index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return null;
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
@@ -112,4 +125,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
|
||||
{
|
||||
Array.Sort(_collection, comparer);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using SelfPropelledArtilleryUnit.Drawnings;
|
||||
using SelfPropelledArtilleryUnit.Exceptions;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
@@ -8,33 +10,18 @@ public class StorageCollection<T>
|
||||
/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
public List<CollectionInfo> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление коллекции в хранилище
|
||||
@@ -43,14 +30,13 @@ public class StorageCollection<T>
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (_storages.ContainsKey(name)) return;
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo)) return;
|
||||
if (collectionType == CollectionType.None) return;
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
_storages[name] = new MassiveGenericObjects<T>();
|
||||
_storages[collectionInfo] = new MassiveGenericObjects<T>();
|
||||
else if (collectionType == CollectionType.List)
|
||||
_storages[name] = new ListGenericObjects<T>();
|
||||
_storages[collectionInfo] = new ListGenericObjects<T>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
@@ -58,10 +44,9 @@ public class StorageCollection<T>
|
||||
/// <param name="name">Название коллекции</param>
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
_storages.Remove(collectionInfo);
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к коллекции
|
||||
@@ -72,22 +57,33 @@ public class StorageCollection<T>
|
||||
{
|
||||
get
|
||||
{
|
||||
// TODO Продумать логику получения объекта
|
||||
if (_storages.ContainsKey(name))
|
||||
return _storages[name];
|
||||
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
|
||||
if (_storages.ContainsKey(collectionInfo))
|
||||
return _storages[collectionInfo];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </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 Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@@ -96,21 +92,18 @@ public class StorageCollection<T>
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.Append(Environment.NewLine);
|
||||
writer.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
writer.Write(value.Key);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
writer.Write(value.Value.MaxCount);
|
||||
writer.Write(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
@@ -118,73 +111,73 @@ public class StorageCollection<T>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
writer.Write(data);
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
writer.Write(sb);
|
||||
}
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </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 Exception("Файл не существует");
|
||||
}
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
//по идее этого произойти не должно
|
||||
//if (strs == null)
|
||||
//{
|
||||
// return false;
|
||||
//}
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
if (record.Length != 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
|
||||
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
collection.MaxCount = Convert.ToInt32(record[1]);
|
||||
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningPropelledArtillery() is T ship)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(ship) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
_storages.Add(collectionInfo, collection);
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
using SelfPropelledArtilleryUnit.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.Drawnings;
|
||||
|
||||
public class DrawiningPropelledArtilleryEqutables : IEqualityComparer<DrawningPropelledArtillery?>
|
||||
{
|
||||
public bool Equals(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
|
||||
{
|
||||
if (x == null || x.EntityPropelledArtillery == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (y == null || y.EntityPropelledArtillery == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityPropelledArtillery.Speed != y.EntityPropelledArtillery.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityPropelledArtillery.Weight != y.EntityPropelledArtillery.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityPropelledArtillery.BodyColor != y.EntityPropelledArtillery.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawningSelfPropelledArtilleryUnit && y is DrawningSelfPropelledArtilleryUnit)
|
||||
{
|
||||
EntitySelfPropelledArtilleryUnit _x = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
|
||||
EntitySelfPropelledArtilleryUnit _y = (EntitySelfPropelledArtilleryUnit)x.EntityPropelledArtillery;
|
||||
if (_x.AdditionalColor != _y.AdditionalColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_x.TurretCannon != _y.TurretCannon)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_x.LaunchBattery != _y.LaunchBattery)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public int GetHashCode([DisallowNull] DrawningPropelledArtillery obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
@@ -96,8 +96,8 @@ public class DrawningPropelledArtillery
|
||||
|
||||
protected DrawningPropelledArtillery(int drawningPropelledArtilleryWidth, int drawningPropelledArtilleryHeight):this()
|
||||
{
|
||||
_drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth;
|
||||
_drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight;
|
||||
this._drawningPropelledArtilleryWidth = drawningPropelledArtilleryWidth;
|
||||
this._drawningPropelledArtilleryHeight = drawningPropelledArtilleryHeight;
|
||||
}
|
||||
public DrawningPropelledArtillery(EntityPropelledArtillery propelledArtillery) : this()
|
||||
{
|
||||
@@ -273,8 +273,5 @@ public class DrawningPropelledArtillery
|
||||
g.DrawEllipse(pen, _startPosX.Value + 93, _startPosY.Value + 78, 24, 24);
|
||||
|
||||
g.FillRectangle(brush, _startPosX.Value + 0, _startPosY.Value + 65, 120, 13);//
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.Drawnings;
|
||||
/// <summary>
|
||||
/// Сравнение по цвету, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningPropelledArtilleryCompareByColor : IComparer<DrawningPropelledArtillery?>
|
||||
{
|
||||
public int Compare(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
|
||||
{
|
||||
if (x == null || x.EntityPropelledArtillery == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityPropelledArtillery == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
var bodycolorCompare = x.EntityPropelledArtillery.BodyColor.Name.CompareTo(y.EntityPropelledArtillery.BodyColor.Name);
|
||||
if (bodycolorCompare != 0)
|
||||
{
|
||||
return bodycolorCompare;
|
||||
}
|
||||
var speedCompare = x.EntityPropelledArtillery.Speed.CompareTo(y.EntityPropelledArtillery.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityPropelledArtillery.Weight.CompareTo(y.EntityPropelledArtillery.Weight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using SelfPropelledArtilleryUnit.Drawnings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
/// <summary>
|
||||
/// Сравнение по типу, скорости, весу
|
||||
/// </summary>
|
||||
public class DrawningPropelledArtilleryCompareByType : IComparer<DrawningPropelledArtillery?>
|
||||
{
|
||||
public int Compare(DrawningPropelledArtillery? x, DrawningPropelledArtillery? y)
|
||||
{
|
||||
if (x == null || x.EntityPropelledArtillery == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (y == null || y.EntityPropelledArtillery == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
|
||||
var speedCompare = x.EntityPropelledArtillery.Speed.CompareTo(y.EntityPropelledArtillery.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityPropelledArtillery.Weight.CompareTo(y.EntityPropelledArtillery.Weight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.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) { }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ObjectIsEqualException : ApplicationException
|
||||
{
|
||||
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
|
||||
public ObjectIsEqualException() : base() { }
|
||||
public ObjectIsEqualException(string message) : base(message) { }
|
||||
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.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) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace SelfPropelledArtilleryUnit.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) { }
|
||||
}
|
||||
@@ -30,6 +30,8 @@
|
||||
{
|
||||
groupBoxTools = new GroupBox();
|
||||
panelCompanyTools = new Panel();
|
||||
buttonSortByColor = new Button();
|
||||
buttonSortByType = new Button();
|
||||
maskedTextBox = new MaskedTextBox();
|
||||
buttonAddPropelledArtillery = new Button();
|
||||
buttonRefresh = new Button();
|
||||
@@ -75,6 +77,8 @@
|
||||
//
|
||||
// panelCompanyTools
|
||||
//
|
||||
panelCompanyTools.Controls.Add(buttonSortByColor);
|
||||
panelCompanyTools.Controls.Add(buttonSortByType);
|
||||
panelCompanyTools.Controls.Add(maskedTextBox);
|
||||
panelCompanyTools.Controls.Add(buttonAddPropelledArtillery);
|
||||
panelCompanyTools.Controls.Add(buttonRefresh);
|
||||
@@ -83,19 +87,33 @@
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Location = new Point(6, 343);
|
||||
panelCompanyTools.Name = "panelCompanyTools";
|
||||
panelCompanyTools.Size = new Size(200, 213);
|
||||
panelCompanyTools.Size = new Size(188, 236);
|
||||
panelCompanyTools.TabIndex = 9;
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Location = new Point(0, 194);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(188, 23);
|
||||
buttonSortByColor.TabIndex = 0;
|
||||
buttonSortByColor.Text = "Сортировка по цвету";
|
||||
buttonSortByColor.Click += buttonSortByColor_Click;
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Location = new Point(0, 168);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(188, 23);
|
||||
buttonSortByType.TabIndex = 1;
|
||||
buttonSortByType.Text = "Сортировка по типу";
|
||||
buttonSortByType.Click += buttonSortByType_Click;
|
||||
//
|
||||
// maskedTextBox
|
||||
//
|
||||
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
maskedTextBox.Location = new Point(0, 95);
|
||||
maskedTextBox.Mask = "00";
|
||||
maskedTextBox.Location = new Point(0, 49);
|
||||
maskedTextBox.Name = "maskedTextBox";
|
||||
maskedTextBox.Size = new Size(188, 23);
|
||||
maskedTextBox.TabIndex = 3;
|
||||
maskedTextBox.ValidatingType = typeof(int);
|
||||
maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected;
|
||||
maskedTextBox.TabIndex = 0;
|
||||
//
|
||||
// buttonAddPropelledArtillery
|
||||
//
|
||||
@@ -111,7 +129,7 @@
|
||||
// buttonRefresh
|
||||
//
|
||||
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRefresh.Location = new Point(0, 185);
|
||||
buttonRefresh.Location = new Point(0, 140);
|
||||
buttonRefresh.Name = "buttonRefresh";
|
||||
buttonRefresh.Size = new Size(188, 22);
|
||||
buttonRefresh.TabIndex = 6;
|
||||
@@ -122,7 +140,7 @@
|
||||
// buttonRemovePropelledArtillery
|
||||
//
|
||||
buttonRemovePropelledArtillery.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonRemovePropelledArtillery.Location = new Point(0, 123);
|
||||
buttonRemovePropelledArtillery.Location = new Point(0, 78);
|
||||
buttonRemovePropelledArtillery.Name = "buttonRemovePropelledArtillery";
|
||||
buttonRemovePropelledArtillery.Size = new Size(188, 24);
|
||||
buttonRemovePropelledArtillery.TabIndex = 4;
|
||||
@@ -133,7 +151,7 @@
|
||||
// buttonGoToCheck
|
||||
//
|
||||
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
|
||||
buttonGoToCheck.Location = new Point(0, 153);
|
||||
buttonGoToCheck.Location = new Point(0, 108);
|
||||
buttonGoToCheck.Name = "buttonGoToCheck";
|
||||
buttonGoToCheck.Size = new Size(188, 26);
|
||||
buttonGoToCheck.TabIndex = 5;
|
||||
@@ -344,5 +362,7 @@
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonSortByColor;
|
||||
private Button buttonSortByType;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,8 @@
|
||||
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
|
||||
using SelfPropelledArtilleryUnit.Drawnings;
|
||||
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 SelfPropelledArtilleryUnit.Exceptions;
|
||||
|
||||
|
||||
namespace SelfPropelledArtilleryUnit;
|
||||
|
||||
@@ -24,13 +18,20 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormPropelledArtilleryCollection()
|
||||
public FormPropelledArtilleryCollection(ILogger<FormPropelledArtilleryCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,51 +47,42 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
|
||||
private void buttonAddPropelledArtillery_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormPropelledArtilleryConfig form = new();
|
||||
form.PropelledArtilleryDelegate += SetCar;
|
||||
// TODO передать метод
|
||||
form.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавление
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddSelfPropelledArtilleryUnit_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
form.AddEvent(SetPropelledArtillery);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта класса-перемещения
|
||||
/// </summary>
|
||||
/// <param name="type">Тип создаваемого объекта</param>
|
||||
private void SetCar(DrawningPropelledArtillery propelledArtilleryk)
|
||||
private void SetPropelledArtillery(DrawningPropelledArtillery propelledArtillery)
|
||||
{
|
||||
|
||||
if (_company == null || propelledArtilleryk == null)
|
||||
try
|
||||
{
|
||||
if (_company == null || propelledArtillery == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (_company + propelledArtilleryk != -1)
|
||||
if (_company + propelledArtillery != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект: " + propelledArtillery.GetDataForSave());
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
|
||||
catch (ObjectIsEqualException ex)
|
||||
{
|
||||
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -109,14 +101,19 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
try
|
||||
{
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции " + pos);
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +131,8 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
|
||||
DrawningPropelledArtillery? propelledartillery = null;
|
||||
int counter = 100;
|
||||
try
|
||||
{
|
||||
while (propelledartillery == null)
|
||||
{
|
||||
propelledartillery = _company.GetRandomObject();
|
||||
@@ -143,18 +142,17 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (propelledartillery == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SelfPropelledArtilleryUnit form = new()
|
||||
{
|
||||
SetPropelledArtillery = propelledartillery
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
@@ -178,6 +176,8 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@@ -189,13 +189,19 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
private void RerfreshListBoxItems()
|
||||
{
|
||||
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);
|
||||
@@ -213,12 +219,20 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonCreateCompany_Click(object sender, EventArgs e)
|
||||
@@ -249,13 +263,16 @@ public partial class FormPropelledArtilleryCollection : 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,19 +281,41 @@ public partial class FormPropelledArtilleryCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonSortByType_Click(object sender, EventArgs e)
|
||||
{
|
||||
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByType());
|
||||
|
||||
}
|
||||
|
||||
private void ComparePropelledArtillery(IComparer<DrawningPropelledArtillery?> comparer)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_company.Sort(comparer);
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
|
||||
private void buttonSortByColor_Click(object sender, EventArgs e)
|
||||
{
|
||||
ComparePropelledArtillery(new DrawningPropelledArtilleryCompareByColor());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -174,8 +174,6 @@ public partial class FormPropelledArtilleryConfig : Form
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void groupBoxColors_Enter(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
namespace SelfPropelledArtilleryUnit
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using SelfPropelledArtilleryUnit;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace ProjectWarmlyShip
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
@@ -11,7 +17,31 @@ namespace SelfPropelledArtilleryUnit
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormPropelledArtilleryCollection());
|
||||
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormPropelledArtilleryCollection>());
|
||||
|
||||
}
|
||||
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<FormPropelledArtilleryCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.AddJsonFile($"{pathNeed}serilog.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,45 +57,6 @@ namespace SelfPropelledArtilleryUnit
|
||||
_drawningPropelledArtillery.DrawTransport(gr);
|
||||
pictureBoxSelfPropelledArtilleryUnit.Image = bmp;
|
||||
}
|
||||
//private void CreateObject(string type)
|
||||
//{
|
||||
// Random random = new();
|
||||
// switch (type)
|
||||
// {
|
||||
// case nameof(DrawningPropelledArtillery):
|
||||
// _drawningPropelledArtillery = new DrawningPropelledArtillery(random.Next(100, 300), random.Next(1000, 3000),
|
||||
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
|
||||
// break;
|
||||
// case nameof(DrawningSelfPropelledArtilleryUnit):
|
||||
// _drawningPropelledArtillery = new DrawningSelfPropelledArtilleryUnit(random.Next(100, 300), random.Next(1000, 3000),
|
||||
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
|
||||
// Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
|
||||
// Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
|
||||
// break;
|
||||
// default:
|
||||
// return;
|
||||
// }
|
||||
|
||||
// _drawningPropelledArtillery.SetPictureSize(pictureBoxSelfPropelledArtilleryUnit.Width, pictureBoxSelfPropelledArtilleryUnit.Height);
|
||||
// _drawningPropelledArtillery.SetPosition(random.Next(10, 100), random.Next(10, 100));
|
||||
// _strategy = null;
|
||||
// comboBoxStrategy.Enabled = true;
|
||||
// Draw();
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// Обработка нажатия кнопки "Создать самоходную арт.установку"
|
||||
///// </summary>
|
||||
///// <param name="sender"></param>
|
||||
///// <param name="e"></param>
|
||||
//private void buttonCreateSelfPropelledArtilleryUnit_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningSelfPropelledArtilleryUnit));
|
||||
|
||||
///// <summary>
|
||||
///// Обработка нажатия кнопки "Создать бронированную машину"
|
||||
///// </summary>
|
||||
///// <param name="sender"></param>
|
||||
///// <param name="e"></param>
|
||||
//private void buttonCreatePropelledArtillery_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningPropelledArtillery));
|
||||
|
||||
private void ButtonMove_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
@@ -8,6 +8,17 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -23,4 +34,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": { "path": "log.log" }
|
||||
}
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "Sample"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user