7 Commits

20 changed files with 740 additions and 187 deletions

View File

@@ -1,4 +1,5 @@
using ProjectContainerShip.Drawings; using ProjectContainerShip.Drawings;
using System.Linq.Expressions;
namespace ProjectContainerShip.CollectionGenericObjects; namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary> /// <summary>
@@ -14,7 +15,7 @@ namespace ProjectContainerShip.CollectionGenericObjects;
/// <summary> /// <summary>
/// Размер места (высота) /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 80; protected readonly int _placeSizeHeight = 82;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
@@ -58,7 +59,7 @@ namespace ProjectContainerShip.CollectionGenericObjects;
/// <returns></returns> /// <returns></returns>
public static int operator +(AbstractCompany company, DrawningShip ship) public static int operator +(AbstractCompany company, DrawningShip ship)
{ {
return company._collection?.Insert(ship) ?? -1; return company._collection?.Insert(ship, new DrawiningShipEqutables()) ?? -1;
} }
/// <summary> /// <summary>
@@ -93,13 +94,23 @@ namespace ProjectContainerShip.CollectionGenericObjects;
DrawBackgound(graphics); DrawBackgound(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningShip? obj = _collection?.Get(i); DrawningShip? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>

View File

@@ -0,0 +1,74 @@
namespace ProjectContainerShip.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></returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@@ -1,4 +1,6 @@
namespace ProjectContainerShip.CollectionGenericObjects using ProjectContainerShip.Drawings;
namespace ProjectContainerShip.CollectionGenericObjects
{ {
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T : class where T : class
@@ -17,16 +19,18 @@
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// /// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Добавление объекта в коллекцию на конкретную позицию /// Добавление объекта в коллекцию на конкретную позицию
/// </summary> /// </summary>
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
@@ -52,5 +56,11 @@
/// </summary> /// </summary>
/// <returns>Поэлементный вывод элементов коллекции</returns> /// <returns>Поэлементный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer"></param>
void CollectionSort(IComparer<T?> comparer);
} }
} }

View File

@@ -1,4 +1,7 @@
using ProjectContainerShip.CollectionGenericObjects; using ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
using System.Linq;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@@ -28,7 +31,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetColectionType => CollectionType.Massive; public CollectionType GetColectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -40,24 +43,33 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (comparer != null)
// TODO вставка в конец набора {
if (Count == _maxCount) return -1; if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (comparer != null)
// TODO проверка позиции {
// TODO вставка по позиции if (_collection.Contains(obj, comparer))
if (Count == _maxCount) return -1; {
if (position >= Count || position < 0) return -1; throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
@@ -65,7 +77,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из списка // TODO удаление объекта из списка
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
@@ -78,4 +90,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@@ -1,4 +1,7 @@
 
using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
namespace ProjectContainerShip.CollectionGenericObjects namespace ProjectContainerShip.CollectionGenericObjects
{ {
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
@@ -45,12 +48,20 @@ namespace ProjectContainerShip.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции // 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]; 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<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
throw new ObjectIsEqualException();
}
}
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@@ -61,17 +72,20 @@ namespace ProjectContainerShip.CollectionGenericObjects
} }
++index; ++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 проверка позиции if (comparer != null)
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то {
// ищется свободное место после этой позиции и идет вставка туда foreach (T? item in _collection)
// если нет после, ищем до {
// TODO вставка if ((comparer as IEqualityComparer<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
if (position >= _collection.Length || position < 0) throw new ObjectIsEqualException();
return -1; }
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@@ -97,16 +111,15 @@ namespace ProjectContainerShip.CollectionGenericObjects
} }
--index; --index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0) { if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
}
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
@@ -120,5 +133,10 @@ namespace ProjectContainerShip.CollectionGenericObjects
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }
} }

View File

@@ -31,12 +31,16 @@ public class ShipPortService : AbstractCompany
int curHeight = 0; int curHeight = 0;
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
{ {
if (_collection.Get(i) != null) if (_collection.Get(i) != null)
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 55, curHeight * _placeSizeHeight + 20);
} }
}
catch (Exception) { }
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else

View File

@@ -1,4 +1,6 @@
using ProjectContainerShip.Drawings; using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
using System.Numerics;
using System.Text; using System.Text;
namespace ProjectContainerShip.CollectionGenericObjects; namespace ProjectContainerShip.CollectionGenericObjects;
@@ -13,12 +15,12 @@ where T : DrawningShip
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@@ -40,7 +42,7 @@ where T : DrawningShip
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
@@ -50,19 +52,13 @@ where T : DrawningShip
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
// TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) return;
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) if (collectionType == CollectionType.None) return;
{
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
{ _storages[collectionInfo] = new MassiveGenericObjects<T>();
_storages.Add(name, new MassiveGenericObjects<T>()); else if (collectionType == CollectionType.List)
} _storages[collectionInfo] = new ListGenericObjects<T>();
}
} }
/// <summary> /// <summary>
@@ -71,8 +67,9 @@ where T : DrawningShip
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
// TODO Прописать логику для удаления коллекции CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(name)) { _storages.Remove(name); } if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@@ -83,11 +80,9 @@ where T : DrawningShip
{ {
get get
{ {
// TODO Продумать логику получения объекта CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo))
{ return _storages[collectionInfo];
return _storages[name];
}
return null; return null;
} }
} }
@@ -96,12 +91,11 @@ where T : DrawningShip
/// Сохранение информации по кораблям в хранилище в файл /// Сохранение информации по кораблям в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@@ -110,7 +104,7 @@ where T : DrawningShip
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
@@ -121,8 +115,6 @@ where T : DrawningShip
} }
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetColectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
@@ -139,58 +131,69 @@ where T : DrawningShip
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по кораблям в хранилище из файла /// Загрузка информации по кораблям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) return false; if (!File.Exists(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; throw new Exception("Файл не существует");
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0) bufferTextFromFile += temp.GetString(b);
} }
using (StreamReader fs = File.OpenText(filename))
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) return false;
if (!strs[0].Equals(_collectionKey))
// Если нет такой записи, то это не те данные
return false;
_storages.Clear();
foreach (string data in strs)
{ {
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string str = fs.ReadLine();
if (record.Length != 4) continue; if (str == null || str.Length == 0)
{
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); throw new Exception("В файле нет данных");
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); }
if (!str.StartsWith(_collectionKey))
if (collection == null) return false; {
throw new Exception("В файле неверные данные");
collection.MaxCount = Convert.ToInt32(record[2]); }
_storages.Clear();
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.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("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningShip() is T ship) if (elem?.CreateDrawningShip() is T ship)
{ {
if (collection.Insert(ship) == -1) return false; try
{
if (collection.Insert(ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
} }
} }
_storages.Add(record[0], collection); catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
return true;
} }
}
_storages.Add(collectionInfo, collection);
}
}
}
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типу
/// </summary> /// </summary>

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Drawings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return 1;
}
if (y == null || y.EntityShip == null)
{
return -1;
}
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@@ -0,0 +1,32 @@
namespace ProjectContainerShip.Drawings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
internal class DrawningShipCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return 1;
}
if (y == null || y.EntityShip == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@@ -0,0 +1,71 @@
using ProjectContainerShip.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Drawings;
public class DrawiningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return false;
}
if (y == null || y.EntityShip == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if(x is DrawningContainerShip && y is DrawningContainerShip)
{
EntityContainerShip _x = (EntityContainerShip)x.EntityShip;
EntityContainerShip _y = (EntityContainerShip)x.EntityShip;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Crane != _y.Crane)
{
return false;
}
if (_x.Container != _y.Container)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}

View File

@@ -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 ProjectContainerShip.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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.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) { }
}

View File

@@ -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 ProjectContainerShip.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectContainerShip.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@@ -67,15 +69,19 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.ForeColor = Color.Black; groupBoxTools.ForeColor = Color.Black;
groupBoxTools.Location = new Point(1601, 40); groupBoxTools.Location = new Point(1341, 40);
groupBoxTools.Margin = new Padding(4, 2, 4, 2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(388, 1072); groupBoxTools.Padding = new Padding(4, 2, 4, 2);
groupBoxTools.Size = new Size(388, 1189);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddShip); panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(maskedTextBox); panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonRemoveShip); panelCompanyTools.Controls.Add(buttonRemoveShip);
@@ -83,17 +89,19 @@
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 598); panelCompanyTools.Location = new Point(4, 608);
panelCompanyTools.Margin = new Padding(4, 2, 4, 2);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(382, 471); panelCompanyTools.Size = new Size(380, 579);
panelCompanyTools.TabIndex = 10; panelCompanyTools.TabIndex = 10;
// //
// buttonAddShip // buttonAddShip
// //
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddShip.Location = new Point(3, 70); buttonAddShip.Location = new Point(4, 17);
buttonAddShip.Margin = new Padding(4, 2, 4, 2);
buttonAddShip.Name = "buttonAddShip"; buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(370, 77); buttonAddShip.Size = new Size(367, 77);
buttonAddShip.TabIndex = 1; buttonAddShip.TabIndex = 1;
buttonAddShip.Text = "Добавление корабля"; buttonAddShip.Text = "Добавление корабля";
buttonAddShip.UseVisualStyleBackColor = true; buttonAddShip.UseVisualStyleBackColor = true;
@@ -101,7 +109,8 @@
// //
// maskedTextBox // maskedTextBox
// //
maskedTextBox.Location = new Point(3, 201); maskedTextBox.Location = new Point(4, 98);
maskedTextBox.Margin = new Padding(4, 2, 4, 2);
maskedTextBox.Mask = "00"; maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(370, 39); maskedTextBox.Size = new Size(370, 39);
@@ -111,9 +120,10 @@
// buttonRemoveShip // buttonRemoveShip
// //
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(3, 246); buttonRemoveShip.Location = new Point(4, 142);
buttonRemoveShip.Margin = new Padding(4, 2, 4, 2);
buttonRemoveShip.Name = "buttonRemoveShip"; buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(370, 77); buttonRemoveShip.Size = new Size(367, 77);
buttonRemoveShip.TabIndex = 4; buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удалить корабль"; buttonRemoveShip.Text = "Удалить корабль";
buttonRemoveShip.UseVisualStyleBackColor = true; buttonRemoveShip.UseVisualStyleBackColor = true;
@@ -122,9 +132,10 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 329); buttonGoToCheck.Location = new Point(4, 226);
buttonGoToCheck.Margin = new Padding(4, 2, 4, 2);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(370, 77); buttonGoToCheck.Size = new Size(367, 77);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -133,9 +144,10 @@
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 412); buttonRefresh.Location = new Point(4, 309);
buttonRefresh.Margin = new Padding(4, 2, 4, 2);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(370, 77); buttonRefresh.Size = new Size(367, 77);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@@ -144,8 +156,9 @@
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(6, 546); buttonCreateCompany.Location = new Point(6, 546);
buttonCreateCompany.Margin = new Padding(4, 2, 4, 2);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(370, 46); buttonCreateCompany.Size = new Size(370, 47);
buttonCreateCompany.TabIndex = 9; buttonCreateCompany.TabIndex = 9;
buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true; buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -161,15 +174,17 @@
panelStorage.Controls.Add(textBoxCollectionName); panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName); panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 35); panelStorage.Location = new Point(4, 34);
panelStorage.Margin = new Padding(4, 2, 4, 2);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(382, 459); panelStorage.Size = new Size(380, 459);
panelStorage.TabIndex = 8; panelStorage.TabIndex = 8;
// //
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(39, 91); radioButtonMassive.Location = new Point(39, 92);
radioButtonMassive.Margin = new Padding(4, 2, 4, 2);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(128, 36); radioButtonMassive.Size = new Size(128, 36);
radioButtonMassive.TabIndex = 7; radioButtonMassive.TabIndex = 7;
@@ -179,9 +194,10 @@
// //
// buttonCollectionDel // buttonCollectionDel
// //
buttonCollectionDel.Location = new Point(3, 387); buttonCollectionDel.Location = new Point(4, 386);
buttonCollectionDel.Margin = new Padding(4, 2, 4, 2);
buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(370, 46); buttonCollectionDel.Size = new Size(370, 47);
buttonCollectionDel.TabIndex = 6; buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию"; buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true; buttonCollectionDel.UseVisualStyleBackColor = true;
@@ -190,16 +206,18 @@
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.Location = new Point(3, 185); listBoxCollection.Location = new Point(4, 186);
listBoxCollection.Margin = new Padding(4, 2, 4, 2);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(370, 196); listBoxCollection.Size = new Size(370, 196);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 5;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(3, 133); buttonCollectionAdd.Location = new Point(4, 132);
buttonCollectionAdd.Margin = new Padding(4, 2, 4, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(370, 46); buttonCollectionAdd.Size = new Size(370, 47);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию"; buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionAdd.UseVisualStyleBackColor = true;
@@ -208,7 +226,8 @@
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(215, 91); radioButtonList.Location = new Point(215, 92);
radioButtonList.Margin = new Padding(4, 2, 4, 2);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(125, 36); radioButtonList.Size = new Size(125, 36);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 3;
@@ -218,7 +237,8 @@
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(3, 46); textBoxCollectionName.Location = new Point(4, 47);
textBoxCollectionName.Margin = new Padding(4, 2, 4, 2);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(370, 39); textBoxCollectionName.Size = new Size(370, 39);
textBoxCollectionName.TabIndex = 1; textBoxCollectionName.TabIndex = 1;
@@ -227,6 +247,7 @@
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(69, 11); labelCollectionName.Location = new Point(69, 11);
labelCollectionName.Margin = new Padding(4, 0, 4, 0);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(251, 32); labelCollectionName.Size = new Size(251, 32);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
@@ -238,7 +259,8 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 500); comboBoxSelectorCompany.Location = new Point(6, 499);
comboBoxSelectorCompany.Margin = new Padding(4, 2, 4, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(370, 40); comboBoxSelectorCompany.Size = new Size(370, 40);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
@@ -248,8 +270,9 @@
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 40); pictureBox.Location = new Point(0, 40);
pictureBox.Margin = new Padding(4, 2, 4, 2);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1601, 1072); pictureBox.Size = new Size(1341, 1189);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@@ -259,7 +282,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1989, 40); menuStrip.Size = new Size(1729, 40);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@@ -294,15 +317,40 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(4, 413);
buttonSortByType.Margin = new Padding(4, 2, 4, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(367, 77);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(4, 494);
buttonSortByColor.Margin = new Padding(4, 2, 4, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(367, 77);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету ";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1989, 1112); ClientSize = new Size(1729, 1229);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
Margin = new Padding(4, 2, 4, 2);
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@@ -343,5 +391,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
} }
} }

View File

@@ -1,5 +1,8 @@
using ProjectContainerShip.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectContainerShip.CollectionGenericObjects;
using ProjectContainerShip.Drawings; using ProjectContainerShip.Drawings;
using ProjectContainerShip.Exceptions;
using System.Numerics;
namespace ProjectContainerShip; namespace ProjectContainerShip;
/// <summary> /// <summary>
@@ -17,13 +20,20 @@ public partial class FormShipCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection(ILogger<FormShipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@@ -53,6 +63,8 @@ public partial class FormShipCollection : Form
/// </summary> /// </summary>
/// <param name="ship"></param> /// <param name="ship"></param>
private void SetShip(DrawningShip ship) private void SetShip(DrawningShip ship)
{
try
{ {
if (_company == null || ship == null) if (_company == null || ship == null)
{ {
@@ -63,10 +75,14 @@ public partial class FormShipCollection : Form
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + ship.GetDataForSave());
} }
else }
catch (CollectionOverflowException) { }
catch (ObjectIsEqualException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка : {Messsage}", ex.Message);
} }
} }
@@ -88,15 +104,19 @@ public partial class FormShipCollection : Form
} }
int position = Convert.ToInt32(maskedTextBox.Text); int position = Convert.ToInt32(maskedTextBox.Text);
try
{
if (_company - position != null) if (_company - position != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + position);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -114,6 +134,9 @@ public partial class FormShipCollection : Form
DrawningShip? ship = null; DrawningShip? ship = null;
int counter = 100; int counter = 100;
try
{
while (ship == null) while (ship == null)
{ {
ship = _company.GetRandomObject(); ship = _company.GetRandomObject();
@@ -123,18 +146,22 @@ public partial class FormShipCollection : Form
break; break;
} }
} }
if (ship == null)
{
return;
}
FormContainerShip form = new() FormContainerShip form = new()
{ {
SetShip = ship SetShip = ship
}; };
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (ship == null)
{
return;
}
}
/// <summary> /// <summary>
/// Обновление /// Обновление
@@ -164,6 +191,9 @@ public partial class FormShipCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@@ -175,6 +205,12 @@ public partial class FormShipCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@@ -185,7 +221,7 @@ public partial class FormShipCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@@ -209,12 +245,20 @@ public partial class FormShipCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
/// <summary> /// <summary>
@@ -255,15 +299,16 @@ public partial class FormShipCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storageCollection.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -278,17 +323,52 @@ public partial class FormShipCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storageCollection.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
/// <summary>
/// Сравнение по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByType());
}
/// <summary>
/// Сравнение по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByColor());
}
} }

View File

@@ -26,7 +26,7 @@ public partial class FormShipConfig : Form
/// <summary> /// <summary>
/// Событие для передачи объекта /// Событие для передачи объекта
/// </summary> /// </summary>
private event ShipDelegate? ShipDelegate; private event Action<DrawningShip>? ShipDelegate;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@@ -51,7 +51,7 @@ public partial class FormShipConfig : Form
/// Привязка внешнего метода к событию /// Привязка внешнего метода к событию
/// </summary> /// </summary>
/// <param name="shipDelegate"></param> /// <param name="shipDelegate"></param>
public void AddEvent(ShipDelegate shipDelegate) public void AddEvent(Action<DrawningShip> shipDelegate)
{ {
ShipDelegate += shipDelegate; ShipDelegate += shipDelegate;
} }
@@ -64,7 +64,7 @@ public partial class FormShipConfig : Form
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height); Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height); _ship?.SetPictureSize(pictureBoxObject.Width, pictureBoxObject.Height);
_ship?.SetPosition(110, 75); _ship?.SetPosition(40, 25);
_ship?.DrawTransport(gr); _ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp; pictureBoxObject.Image = bmp;
} }

View File

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

View File

@@ -8,6 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@@ -23,4 +38,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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