7 Commits
Lab5 ... Lab8

Author SHA1 Message Date
a67ca743c6 result 2024-06-17 09:44:23 +04:00
7fc6a50c1b comparer & sorting 2024-06-16 23:08:52 +04:00
9c904ea947 In process : wasn't checked [!] 2024-06-16 21:39:45 +04:00
5071187623 logging 2024-06-16 19:46:37 +04:00
7f58bbb1ad In process : solve log problem & add left exceptions 2024-06-15 23:48:53 +04:00
f575f977b0 files and streams 2024-06-15 18:06:35 +04:00
86e57edbc8 In process : fix loading from txt 2024-06-15 13:28:42 +04:00
26 changed files with 1016 additions and 183 deletions

View File

@@ -17,8 +17,8 @@ public abstract class AbstractCompany
// Коллекция автомобилей
protected ICollectionGenObj<DrawningBase>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight /
(_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 20))
* ( _pictureHeight / (_placeSizeHeight + 4));
public AbstractCompany(int picWidth, int picHeight,
ICollectionGenObj<DrawningBase>? collection)
@@ -26,17 +26,21 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
// Перегрузка оператора сложения для класса
// [ ! ] insted of bool:
public static int operator +(AbstractCompany company,
DrawningBase trasport) => company._collection.Insert(trasport);
DrawningBase transport) => company._collection.Insert(transport, new DrawiningShipEqutables());
// Перегрузка оператора удаления для класса
public static DrawningBase operator -(AbstractCompany company,
int pos) => company._collection.Remove(pos);
int pos) => company._collection?.Remove(pos);
// Сортировка ----------------------------------------------------------- [!]
public void Sort(IComparer<DrawningBase?> comparer) =>
_collection?.CollectionSort(comparer);
// Получение случайного объекта из коллекции
public DrawningBase? GetRandomObject()
@@ -51,20 +55,30 @@ public abstract class AbstractCompany
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
SetObjectsPosition(_collection.Count - 1);
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
DrawningBase? obj = _collection?.GetItem(i);
obj?.DrawTransport(graphics);
// try
// {
DrawningBase? obj = _collection?.GetItem(i);
obj?.DrawTransport(graphics);
// } catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }
}
return bitmap;
}
// Вывод заднего фона
protected abstract void DrawBackground(Graphics g);
// Расстановка объектов
protected abstract void SetObjectsPosition();
protected abstract void SetObjectsPosition(int border);
}

View File

@@ -1,24 +1,34 @@
namespace ProjectCruiser.CollectionGenericObj;
using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj;
public class ArrayGenObj<T> : ICollectionGenObj<T>
where T : class
{
// Массив объектов, которые храним
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
// Максимально допустимое число объектов в массиве
private int _maxCount;
public int Count => _collection.Count(s => (s != null));
public int MaxCount
{
get { return _maxCount; }
set
{
if (value > 0)
{
if (_collection.Length > 0) Array.Resize(ref _collection, value);
else _collection = new T?[value];
_maxCount = value;
if (_collection.Length == 0) _collection = new T?[value];
else Array.Resize(ref _collection, value);
}
}
}
// public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public CollectionType GetCollectionType => CollectionType.Array;
public ArrayGenObj()
{
@@ -26,20 +36,36 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
}
// methods :
public T? GetItem(int index)
{
if (index > Count || index < 0)
{
return null;
}
if (index > _maxCount)
throw new CollectionOverflowException(index);
if (index < 0)
throw new PositionOutOfCollectionException(index);
if (_collection[index] == null)
throw new ObjectNotFoundException(index);
return _collection[index];
}
public int Insert(T? item)
public int Insert(T? item, IEqualityComparer<DrawningBase?>? cmpr = null)
{
// any empty place
for (int i = 0; i < Count; i++)
if (item == null) throw
new NullReferenceException("> Inserting item is null");
else
{
if (cmpr != null && item == cmpr)
{
throw new Exception();
}
}
// выход за границы, курируется CollectionOverflowException
if (Count >= _maxCount) throw new CollectionOverflowException(Count);
// any empty place -> fill immediately
for (int i = Count; i < _maxCount; i++)
{
if (_collection[i] == null)
{
@@ -47,48 +73,75 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
return i;
}
}
return -1;
return Count;
}
public int Insert(T? item, int index)
public int Insert(T? item, int index, IEqualityComparer<DrawningBase?>? cmpr = null)
{
if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index);
if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (item == null) throw
new NullReferenceException("> Inserting item (at position) is null");
else
{
if (cmpr != null && item == cmpr)
{
throw new Exception();
}
}
if (_collection[index] == null)
{
_collection[index] = item;
return index;
}
else
{
int min_diff = 100, min_index = 100;
int min_diff = 100, firstNullIndex = 100;
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null
&& min_diff > Math.Abs(index - i))
if (_collection[i] == null && min_diff > Math.Abs(index - i))
{
min_diff = Math.Abs(index - i);
min_index = i;
firstNullIndex = i;
}
}
_collection[min_index] = item;
return min_index;
_collection[firstNullIndex] = item;
return firstNullIndex;
}
return -1;
}
public T? Remove(int index)
{
T? item;
if (index < Count && index >= 0)
if (index >= _maxCount || index < 0)
// on the other positions items don't exist
{
item = _collection[index];
_collection[index] = null;
return item;
throw new PositionOutOfCollectionException(index);
}
return null;
T? item = _collection[index];
_collection[index] = null;
if (item == null) throw new ObjectNotFoundException(index);
return item;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < MaxCount; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenObj<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@@ -0,0 +1,63 @@
namespace ProjectCruiser.CollectionGenericObj;
// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
// Название коллекции
public string Name { get; private set; }
// Тип
public CollectionType CollectionType { get; private set; }
// Описание
public string Description { get; private set; }
// Разделитель для записи информации по объекту в файл
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
// Создание объекта из строки
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType),
strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
// if (Name != other.Name) return false; >>>
// else if (CollectionType != other.CollectionType) return false;
// else if (Description != other.Description) return false;
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 ProjectCruiser.CollectionGenericObj;
using ProjectCruiser.DrawningSamples;
namespace ProjectCruiser.CollectionGenericObj;
public interface ICollectionGenObj<T> where T : class
{
@@ -6,13 +8,13 @@ public interface ICollectionGenObj<T> where T : class
int Count { get; }
// Установка max кол-ва элементов
int SetMaxCount { set; }
int MaxCount { set; get; }
/// Добавление объекта в коллекцию
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, int position);
int Insert(T obj, IEqualityComparer<DrawningBase?>? cmpr = null);
int Insert(T obj, int position, IEqualityComparer<DrawningBase?>? cmpr = null);
/// Удаление объекта из коллекции с конкретной позиции
/// <param name="position">Позиция</param>
@@ -21,4 +23,14 @@ public interface ICollectionGenObj<T> where T : class
// Получение объекта по позиции
T? GetItem(int position);
// Получение типа коллекции
CollectionType GetCollectionType { get; }
// Получение объектов коллекции по одному
IEnumerable<T?> GetItems();
// Сортировка коллекции
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@@ -1,5 +1,5 @@
using System;
using System.Reflection;
using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Exceptions;
namespace ProjectCruiser.CollectionGenericObj;
@@ -8,13 +8,28 @@ public class ListGenObj<T> : ICollectionGenObj<T>
where T : class
{
// Список объектов, которые храним
private readonly List<T?> _collection;
private List<T?> _collection;
// Максимально допустимое число объектов в списке
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get { return _maxCount; }
set
{
if (value > 0)
{
if (_collection.Count == 0) _collection = new List<T>(value);
else _collection.Capacity = value; // instead of resizing
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenObj()
{
@@ -23,32 +38,50 @@ public class ListGenObj<T> : ICollectionGenObj<T>
public T? GetItem(int position)
{
if (position >= Count || position < 0)
{
return null;
}
if (position > _maxCount)
throw new CollectionOverflowException(position);
if (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<DrawningBase?>? cmpr = null)
{
if (Count >= _maxCount || obj == null)
if (obj == null)
throw new NullReferenceException("> Inserting object is null");
else
{
return -1;
if (cmpr != null && obj == cmpr)
{
throw new Exception();
}
}
// выход за границы, курируется CollectionOverflowException
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<DrawningBase?>? cmpr = null)
{
if (position >= _maxCount || Count >= _maxCount ||
position < 0 || _collection[position] != null
|| obj == null)
if (position < 0 || position >= _maxCount)
throw new PositionOutOfCollectionException(position);
if (Count >= _maxCount) throw new CollectionOverflowException(Count);
if (obj == null)
throw new NullReferenceException("> Inserting object (at position) is null");
else
{
return -1;
if (cmpr != null && obj == cmpr)
{
throw new Exception();
}
}
_collection.Insert(position, obj);
@@ -57,14 +90,30 @@ public class ListGenObj<T> : ICollectionGenObj<T>
public T? Remove(int position)
{
if (position >= Count || position < 0)
if (position >= _maxCount || position < 0)
// on the other positions items don't exist
{
return null;
throw new PositionOutOfCollectionException(position);
}
T? item = _collection[position];
_collection.RemoveAt(position);
if (item == null) throw new ObjectNotFoundException(position);
return item;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
void ICollectionGenObj<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@@ -41,27 +41,38 @@ public class ShipSharingService : AbstractCompany
}
}
protected override void SetObjectsPosition()
protected override void SetObjectsPosition(int border)
{
int index_collection = 0;
int newX = fromBorder + 6, newY = fromCeiling + 6;
int newY = fromCeiling + 4;
if (_collection != null)
{
for (int i = 0; i < MaxInColon; ++i)
for (int i = 0; i < MaxInColon; i++)
{
newX = fromBorder + 2;
for (int j = 0; j < MaxInRow; ++j)
int newX = fromBorder + 2;
for (int j = 0; j < MaxInRow; j++)
{
if (_collection.GetItem(index_collection) != null)
try
{
_collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.GetItem(index_collection).SetPictureSize(
_pictureWidth, _pictureHeight);
_collection.GetItem(index_collection).SetPosition(newX, newY);
newX += _placeSizeWidth + between + 2;
} catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
newX += _placeSizeWidth + between + 2;
if (index_collection < border)
{
index_collection++;
}
else return;
}
newY += _placeSizeHeight + 2;
newY += _placeSizeHeight + 1;
}
}
}

View File

@@ -1,51 +1,181 @@
namespace ProjectCruiser.CollectionGenericObj;
using System.CodeDom;
using System.Text;
using ProjectCruiser.DrawningSamples;
namespace ProjectCruiser.CollectionGenericObj;
public class StorageCollection<T>
where T : class
where T : DrawningBase // class
{
// Словарь (хранилище) с коллекциями < name, type (class) >
readonly Dictionary<string, ICollectionGenObj<T>> _storages;
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
private readonly string _collectionKey = "CollectionsStorage";
// Возвращение списка названий коллекций
public List<string> Keys => _storages.Keys.ToList();
// Словарь (хранилище) с коллекциями < CollectionInfo, type (class) >
readonly Dictionary<CollectionInfo, ICollectionGenObj<T>> _storages;
// Возвращение списка коллекций
public List<CollectionInfo> Keys => _storages.Keys.ToList();
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenObj<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenObj<T>>();
}
/// Добавление коллекции в хранилище
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
// Добавление коллекции в хранилище
public void AddCollection(string name, CollectionType collType)
{
if (name == null || _storages.ContainsKey(name)
// descroption [ ? ] >>>
CollectionInfo coll = new CollectionInfo(name, collType, string.Empty);
if (name == null || _storages.ContainsKey(coll)
|| collType == CollectionType.None)
{
return;
throw new NullReferenceException("> Not enough information to save");
}
switch (collType)
{
case CollectionType.List: _storages.Add(name, new ListGenObj<T>()); break;
// _storages[name] = new ListGenericObjects<T>(); break; [*]
case CollectionType.Array: _storages.Add(name, new ArrayGenObj<T>()); break;
}
_storages.Add(coll, CreateCollection(collType));
}
/// Удаление коллекции ( по ключу-строке - её имени )
/// <param name="name">Название коллекции</param>
// Удаление коллекции ( по ключу-строке - её имени )
public void DelCollection(string name)
{
if (_storages.ContainsKey(name)) _storages.Remove(name);
return;
// descroption [ ? ] >>>
CollectionInfo coll = new CollectionInfo(name,
CollectionType.None, string.Empty);
if (_storages.ContainsKey(coll)) _storages.Remove(coll);
else throw new NullReferenceException("> No such key in the list");
}
/// Доступ к коллекции ( по ключу-строке - её имени )
// Доступ к коллекции , индексатор [!!!]
public ICollectionGenObj<T>? this[string name]
{
get => _storages.ContainsKey(name) ? _storages[name] : null;
get => _storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))
? _storages[new CollectionInfo(name, CollectionType.None, string.Empty)] : null;
}
/// Сохранение информации по автомобилям в хранилище в файл
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно,
/// false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
throw new NullReferenceException("> No existing collections to save");
if (File.Exists(filename)) { File.Delete(filename); }
StringBuilder sb = new();
sb.Append(_collectionKey); // const
foreach (KeyValuePair<CollectionInfo, ICollectionGenObj<T>> pair in _storages)
{
sb.Append(Environment.NewLine); // не сохраняем пустые коллекции
if (pair.Value.Count == 0) { continue; }
sb.Append(pair.Key);
sb.Append(_separatorForKeyValue);
// <...>
sb.Append(pair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in pair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
// Создание коллекции по типу
private static ICollectionGenObj<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Array => new ArrayGenObj<T>(),
CollectionType.List => new ListGenObj<T>(),
_ => null,
};
}
// Загрузка информации по кораблям в хранилище из файла
public void LoadData(string filename)
{
if (!File.Exists(filename)) throw new FileNotFoundException("> No such file");
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(
new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
throw new NullReferenceException("> No data to decode");
if (!strs[0].Equals(_collectionKey))
throw new InvalidDataException("> Incorrect data");
string[] companies = new string[strs.Length - 1];
for (int k = 1; k < strs.Length; k++)
{
companies[k - 1] = strs[k];
}
_storages.Clear();
foreach (string data in companies)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3) // >
// [key + collType] | maxcount | all next inf > 4
{ continue; }
CollectionInfo? collInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("[!] Failed to decode information : " + record[0]);
ICollectionGenObj<T>? collection = StorageCollection<T>.CreateCollection(
collInfo.CollectionType) ??
throw new Exception("[!] Failed to create a collection");
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningCar() is T ship)
{
try
{
collection.Insert(ship);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
_storages.Add(collInfo, collection);
}
}
}

View File

@@ -14,9 +14,9 @@ public class DrawningBase
private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля
// Инициализация свойств (теперь через конструктор)
public DrawningBase(int speed, double weight, Color bodyColor) : this()
public DrawningBase(EntityBase ship) : this()
{
EntityTransport = new EntityBase(speed, weight, bodyColor);
EntityTransport = ship;
}
private DrawningBase()

View File

@@ -5,11 +5,9 @@ namespace ProjectCruiser.DrawningSamples;
public class DrawningCruiser : DrawningBase
{
// Инициализация свойств (все параметры класса (сущности))
public DrawningCruiser(int speed, double weight, Color bodyColor,
Color additionalColor, bool pad, bool hangars) : base(302, 42)
public DrawningCruiser(EntityCruiser ship) : base((EntityBase)ship)
{
EntityTransport = new EntityCruiser(speed, weight,
bodyColor, additionalColor, pad, hangars);
EntityTransport = ship;
}
public override void DrawTransport(Graphics g)

View File

@@ -0,0 +1,31 @@
namespace ProjectCruiser.DrawningSamples;
// Сравнение по типу, скорости, весу
public class DrawningShipCompare : IComparer<DrawningBase?>
{
public int Compare(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null)
{
return 1;
}
if (y == null || y.EntityTransport == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight);
}
}

View File

@@ -0,0 +1,34 @@
namespace ProjectCruiser.DrawningSamples;
public class DrawningShipCompareByColor : IComparer<DrawningBase?>
{
public int Compare(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null)
{
return 1;
}
if (y == null || y.EntityTransport == null)
{
return -1;
}
var bodycolorCompare = x.EntityTransport.MainColor.Name.CompareTo(
y.EntityTransport.MainColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTransport.Speed.CompareTo(y.EntityTransport.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTransport.Weight.CompareTo(y.EntityTransport.Weight);
}
}

View File

@@ -0,0 +1,45 @@
using System.Diagnostics.CodeAnalysis;
using ProjectCruiser.Entities;
namespace ProjectCruiser.DrawningSamples;
// Реализация сравнения двух объектов класса-прорисовки
public class DrawiningShipEqutables : IEqualityComparer<DrawningBase?>
{
public bool Equals(DrawningBase? x, DrawningBase? y)
{
if (x == null || x.EntityTransport == null) return false;
if (y == null || y.EntityTransport == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityTransport.Speed != y.EntityTransport.Speed) return false;
if (x.EntityTransport.Weight != y.EntityTransport.Weight) return false;
if (x.EntityTransport.MainColor != y.EntityTransport.MainColor) return false;
if (x is DrawningCruiser && y is DrawningCruiser)
{
/* public Color AdditionalColor { get; private set; } // доп. цвет
// признаки (наличия)
public bool HelicopterPads { get; private set; } // вертолетная площадка
public bool Hangars { get; private set; } // ангар */
EntityCruiser EntityX = (EntityCruiser)x.EntityTransport;
EntityCruiser EntityY = (EntityCruiser)y.EntityTransport;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
if (EntityX.Hangars != EntityY.Hangars)
return false;
if (EntityX.HelicopterPads != EntityY.HelicopterPads)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBase obj)
{
return obj.GetHashCode();
}
}

View File

@@ -0,0 +1,41 @@
using ProjectCruiser.Entities;
namespace ProjectCruiser.DrawningSamples;
public static class ExtentionDrShip
{
// Разделитель для записи информации по объекту в файл
private static readonly string _separatorForObject = ":";
// Создание объекта из строки
public static DrawningBase? CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBase? ship = EntityCruiser.CreateEntity(strs);
if (ship != null)
{
return new DrawningCruiser((EntityCruiser)ship);
}
ship = EntityBase.CreateEntity(strs);
if (ship != null)
{
return new DrawningBase(ship);
}
return null;
}
// Получение данных для сохранения в файл - - - - - - -
public static string GetDataForSave(this DrawningBase drShip)
// метод расширения за счёт ключевого слова 'this'
// вызов метода достигается не через имя класса,
// а при вызове у объекта типа DrawningBase [*]
{
string[]? array = drShip?.EntityTransport?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -63,12 +63,14 @@ public partial class EditorForm3 : Form
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "BaseLabel":
_cruiser = new DrawningBase((int)SpeedN.Value, (double)WeightN.Value, Color.White);
EntityBase ship = new EntityBase((int)SpeedN.Value, (double)WeightN.Value, Color.White);
_cruiser = new DrawningBase(ship);
break;
case "AdvLabel":
Random rn = new Random();
_cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value,
EntityCruiser cruiser = new EntityCruiser((int)SpeedN.Value, (double)WeightN.Value,
Color.White, Color.Black, checkBoxPads.Checked, checkBoxHangars.Checked);
_cruiser = new DrawningCruiser(cruiser);
break;
}
labelMcolor.BackColor = Color.Empty;

View File

@@ -24,9 +24,26 @@ public class EntityBase
Speed = speed;
Weight = weight;
MainColor = mainc;
// Deckhouse = deckhouse;
values[0] = rn.Next(1, 4);
values[1] = rn.Next(5, 10);
values[2] = rn.Next(1, 3);
}
// Получение массива строк со значениями свойств
// объекта : тип (название класса), скорость, вес, осн. цвет [*]
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBase), Speed.ToString(),
Weight.ToString(), MainColor.Name };
}
// decoding string to object
public static EntityBase? CreateEntity(string[] parameters)
{
if (parameters.Length != 4 || parameters.Length == 0 ||
parameters[0] != "EntityBase") return null;
return new EntityBase(Convert.ToInt32(parameters[1]),
Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]));
}
}

View File

@@ -21,4 +21,26 @@ public class EntityCruiser : EntityBase
HelicopterPads = pad; // non-default now for editor Form3
Hangars = hangars;
}
// Получение массива строк со значениями свойств
// объекта : тип (название класса), скорость, вес, осн. цвет [*],
// доп. цвет, истинность наличия площадки и (,) ангаров.
public override string[] GetStringRepresentation() // :O
{
return new[] { nameof(EntityCruiser), Speed.ToString(),
Weight.ToString(), MainColor.Name, AdditionalColor.Name,
HelicopterPads.ToString(), Hangars.ToString()};
}
// decoding string to object
public static EntityCruiser? CreateEntity(string[] parameters)
{
if (parameters.Length != 7 || parameters.Length == 0 ||
parameters[0] != "EntityCruiser") return null;
return new EntityCruiser(Convert.ToInt32(parameters[1]),
Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]),
Color.FromName(parameters[4]), Convert.ToBoolean(parameters[5]),
Convert.ToBoolean(parameters[6]));
}
}

View File

@@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace ProjectCruiser.Exceptions;
// Класс, описывающий ошибку переполнения коллекции
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count)
: base("<> Possible accsess\nof collection is over : " + 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,16 @@
using System.Runtime.Serialization;
namespace ProjectCruiser.Exceptions;
// Класс, описывающий ошибку, что по указанной позиции нет элемента
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i)
: base("<> Didn't find obj\non this position : " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception)
: base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectCruiser.Exceptions;
// Класс, описывающий ошибку выхода за границы коллекции
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i)
: base("<> Out of collection\nboarder. Position : " + 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

@@ -1,4 +1,5 @@
using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Entities;
using ProjectCruiser.MoveStrategy;
namespace ProjectCruiser
@@ -59,16 +60,18 @@ namespace ProjectCruiser
switch (type)
{
case nameof(DrawningBase):
_drawningCruiser = new DrawningBase(random.Next(100, 300), random.Next(1000, 3000),
EntityBase ship = new EntityBase(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
_drawningCruiser = new DrawningBase(ship);
break;
case nameof(DrawningCruiser):
_drawningCruiser = new DrawningCruiser(
EntityCruiser cruiser = new EntityCruiser(
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)));
_drawningCruiser = new DrawningCruiser(cruiser);
break;
default:

View File

@@ -1,18 +1,45 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace ProjectCruiser
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new ServiceForm2());
// -> OceanForm1() inside*
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<ServiceForm2>());
}
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<ServiceForm2>().AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(
new ConfigurationBuilder().AddJsonFile(
$"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
}
}

View File

@@ -8,4 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<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.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@@ -46,10 +46,19 @@
btnAddCruiser = new Button();
btnCreateCompany = new Button();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
btnSortType = new Button();
btnSortColor = new Button();
groupBox.SuspendLayout();
companyPanel.SuspendLayout();
toolPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// comboBoxArrList
@@ -57,7 +66,7 @@
comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
comboBoxArrList.FormattingEnabled = true;
comboBoxArrList.Items.AddRange(new object[] { "Storage" });
comboBoxArrList.Location = new Point(17, 41);
comboBoxArrList.Location = new Point(17, 38);
comboBoxArrList.Name = "comboBoxArrList";
comboBoxArrList.Size = new Size(241, 40);
comboBoxArrList.TabIndex = 0;
@@ -70,9 +79,9 @@
groupBox.Controls.Add(toolPanel);
groupBox.Controls.Add(btnCreateCompany);
groupBox.Controls.Add(comboBoxArrList);
groupBox.Location = new Point(1421, 10);
groupBox.Location = new Point(1421, 43);
groupBox.Name = "groupBox";
groupBox.Size = new Size(273, 986);
groupBox.Size = new Size(273, 964);
groupBox.TabIndex = 2;
groupBox.TabStop = false;
groupBox.Text = "Tool panel";
@@ -86,17 +95,17 @@
companyPanel.Controls.Add(rBtnArray);
companyPanel.Controls.Add(maskedTxtBoxCName);
companyPanel.Controls.Add(label);
companyPanel.Location = new Point(17, 91);
companyPanel.Location = new Point(17, 83);
companyPanel.Name = "companyPanel";
companyPanel.Size = new Size(243, 391);
companyPanel.Size = new Size(243, 359);
companyPanel.TabIndex = 7;
//
// btnDeleteCollection
//
btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnDeleteCollection.Location = new Point(15, 312);
btnDeleteCollection.Location = new Point(16, 276);
btnDeleteCollection.Name = "btnDeleteCollection";
btnDeleteCollection.Size = new Size(214, 73);
btnDeleteCollection.Size = new Size(214, 76);
btnDeleteCollection.TabIndex = 11;
btnDeleteCollection.Text = "Remove Collection";
btnDeleteCollection.UseVisualStyleBackColor = true;
@@ -105,17 +114,17 @@
// listBox
//
listBox.FormattingEnabled = true;
listBox.Location = new Point(16, 174);
listBox.Location = new Point(16, 171);
listBox.Name = "listBox";
listBox.Size = new Size(214, 132);
listBox.Size = new Size(214, 100);
listBox.TabIndex = 10;
//
// btnAddCollection
//
btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnAddCollection.Location = new Point(15, 119);
btnAddCollection.Location = new Point(15, 118);
btnAddCollection.Name = "btnAddCollection";
btnAddCollection.Size = new Size(214, 50);
btnAddCollection.Size = new Size(214, 49);
btnAddCollection.TabIndex = 7;
btnAddCollection.Text = "Add Collection";
btnAddCollection.UseVisualStyleBackColor = true;
@@ -135,7 +144,7 @@
// rBtnArray
//
rBtnArray.AutoSize = true;
rBtnArray.Location = new Point(16, 80);
rBtnArray.Location = new Point(16, 79);
rBtnArray.Name = "rBtnArray";
rBtnArray.Size = new Size(100, 36);
rBtnArray.TabIndex = 8;
@@ -162,23 +171,25 @@
//
// toolPanel
//
toolPanel.Controls.Add(btnSortColor);
toolPanel.Controls.Add(btnSortType);
toolPanel.Controls.Add(btnUpdate);
toolPanel.Controls.Add(btnTest);
toolPanel.Controls.Add(maskedTextBoxPosition);
toolPanel.Controls.Add(btnDelete);
toolPanel.Controls.Add(btnAddCruiser);
toolPanel.Enabled = false;
toolPanel.Location = new Point(26, 567);
toolPanel.Location = new Point(26, 537);
toolPanel.Name = "toolPanel";
toolPanel.Size = new Size(226, 317);
toolPanel.Size = new Size(226, 415);
toolPanel.TabIndex = 13;
//
// btnUpdate
//
btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnUpdate.Location = new Point(16, 257);
btnUpdate.Location = new Point(16, 350);
btnUpdate.Name = "btnUpdate";
btnUpdate.Size = new Size(192, 41);
btnUpdate.Size = new Size(193, 57);
btnUpdate.TabIndex = 6;
btnUpdate.Text = "Update";
btnUpdate.UseVisualStyleBackColor = true;
@@ -187,9 +198,9 @@
// btnTest
//
btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnTest.Location = new Point(17, 162);
btnTest.Location = new Point(17, 142);
btnTest.Name = "btnTest";
btnTest.Size = new Size(192, 89);
btnTest.Size = new Size(192, 80);
btnTest.TabIndex = 5;
btnTest.Text = "Choose\r\nfor testing";
btnTest.UseVisualStyleBackColor = true;
@@ -198,7 +209,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(17, 68);
maskedTextBoxPosition.Location = new Point(17, 55);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(192, 39);
@@ -208,20 +219,20 @@
// btnDelete
//
btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnDelete.Location = new Point(16, 113);
btnDelete.Location = new Point(17, 99);
btnDelete.Name = "btnDelete";
btnDelete.Size = new Size(192, 43);
btnDelete.Size = new Size(192, 41);
btnDelete.TabIndex = 4;
btnDelete.Text = "Delete";
btnDelete.UseVisualStyleBackColor = true;
btnDelete.Click += btnRemoveCar_Click;
btnDelete.Click += btnRemoveShip_Click;
//
// btnAddCruiser
//
btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnAddCruiser.Location = new Point(17, 13);
btnAddCruiser.Location = new Point(16, 4);
btnAddCruiser.Name = "btnAddCruiser";
btnAddCruiser.Size = new Size(192, 49);
btnAddCruiser.Size = new Size(192, 48);
btnAddCruiser.TabIndex = 2;
btnAddCruiser.Text = "Add cruiser";
btnAddCruiser.UseVisualStyleBackColor = true;
@@ -230,9 +241,9 @@
// btnCreateCompany
//
btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnCreateCompany.Location = new Point(16, 488);
btnCreateCompany.Location = new Point(17, 447);
btnCreateCompany.Name = "btnCreateCompany";
btnCreateCompany.Size = new Size(245, 73);
btnCreateCompany.Size = new Size(245, 85);
btnCreateCompany.TabIndex = 12;
btnCreateCompany.Text = "Create or switch to Company";
btnCreateCompany.UseVisualStyleBackColor = true;
@@ -241,12 +252,75 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Left;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1415, 1007);
pictureBox.Size = new Size(1415, 967);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1700, 40);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(71, 36);
fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(277, 44);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(277, 44);
loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
//
// btnSortType
//
btnSortType.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnSortType.Location = new Point(16, 232);
btnSortType.Name = "btnSortType";
btnSortType.Size = new Size(192, 52);
btnSortType.TabIndex = 7;
btnSortType.Text = "Sort by type";
btnSortType.UseVisualStyleBackColor = true;
btnSortType.Click += btnSortType_Click;
//
// btnSortColor
//
btnSortColor.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnSortColor.Location = new Point(16, 285);
btnSortColor.Name = "btnSortColor";
btnSortColor.Size = new Size(192, 52);
btnSortColor.TabIndex = 8;
btnSortColor.Text = "Sort by color";
btnSortColor.UseVisualStyleBackColor = true;
btnSortColor.Click += btnSortColor_Click;
//
// ServiceForm2
//
AutoScaleDimensions = new SizeF(13F, 32F);
@@ -254,6 +328,8 @@
ClientSize = new Size(1700, 1007);
Controls.Add(pictureBox);
Controls.Add(groupBox);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "ServiceForm2";
Text = "ServiceForm2";
groupBox.ResumeLayout(false);
@@ -262,7 +338,10 @@
toolPanel.ResumeLayout(false);
toolPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -285,5 +364,13 @@
private Button btnDeleteCollection;
private Button btnCreateCompany;
private Panel toolPanel;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button btnSortColor;
private Button btnSortType;
}
}

View File

@@ -1,5 +1,9 @@
using ProjectCruiser.CollectionGenericObj;
using ProjectCruiser.DrawningSamples;
using Microsoft.Extensions.Logging;
using ProjectCruiser.Exceptions;
// using NLog.Extensions.Logging;
namespace ProjectCruiser;
public partial class ServiceForm2 : Form
@@ -9,10 +13,16 @@ public partial class ServiceForm2 : Form
private readonly StorageCollection<DrawningBase> _storageCollection;
public ServiceForm2()
// Логер
private readonly ILogger _logger;
// Конструктор > logger
public ServiceForm2(ILogger<ServiceForm2> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("> Form is loaded successfully");
}
// Выбор компании
@@ -21,23 +31,10 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = false;
}
// Color picker (default : random)
private static Color pickColor(Random r)
{
Color cl = new Color();
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK) cl = dialog.Color;
else Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256));
return cl;
}
// Добавление корабля
private void btnAddTransport_Click(object sender, EventArgs e)
{
EditorForm3 form3 = new();
// TODO передать метод :
form3.AddEvent(CreateObject);
form3.Show();
}
@@ -45,37 +42,53 @@ public partial class ServiceForm2 : Form
// Создание объекта класса-перемещения
private void CreateObject(DrawningBase? ship)
{
if (_company == null || ship == null)
{
return;
}
if (_company + ship != -1)
try
{
if (_company == null || ship == null)
{
throw new NullReferenceException(" > No existing collections to save");
}
int count = _company + ship;
MessageBox.Show("> Object was added");
pictureBox.Image = _company.Show();
_logger.LogInformation("> Adding object succeed {ship} at {count} position", ship, count);
}
else
catch (Exception ex)
{
MessageBox.Show("[!] Failed to add object");
MessageBox.Show("[!] Failed to add object\n" + ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
}
}
// Удаление объекта
private void btnRemoveCar_Click(object sender, EventArgs e)
private void btnRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)
|| _company == null) return;
if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - Convert.ToInt32(maskedTextBoxPosition.Text) != null)
try
{
MessageBox.Show("> Object was removed");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("> Object was removed");
pictureBox.Image = _company.Show();
_logger.LogInformation("Object at " +
pos + "position was deleted successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("[!] Failed to remove object");
_logger.LogError("< Error > : {Message}", ex.Message);
}
else MessageBox.Show("[!] Failed to remove object");
}
// Передача объекта в другую форму
@@ -85,27 +98,37 @@ public partial class ServiceForm2 : Form
{
return;
}
DrawningBase? car = null;
DrawningBase? ship = null;
int counter = 100;
while (car == null)
while (ship == null)
{
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
try
{
break;
ship = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
if (car == null)
if (ship == null)
{
return;
}
OceanForm1 form = new() { SetShip = car };
OceanForm1 form = new() { SetShip = ship };
form.ShowDialog();
}
// Перерисовка коллекции
private void btnRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
@@ -134,7 +157,17 @@ public partial class ServiceForm2 : Form
collType = CollectionType.List;
}
_storageCollection.AddCollection(maskedTxtBoxCName.Text, collType);
try
{
_storageCollection.AddCollection(maskedTxtBoxCName.Text, collType);
_logger.LogInformation("Adding collection succeed : {Name}, {Type}", maskedTxtBoxCName.Text, collType);
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
}
RefreshListBoxItems();
}
@@ -145,12 +178,21 @@ public partial class ServiceForm2 : Form
MessageBox.Show("Collection was not choosed");
return;
}
if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK)
if (MessageBox.Show("Are you sure?", "Removing",
MessageBoxButtons.OK, MessageBoxIcon.Question)
!= DialogResult.OK) return;
try
{
return;
_storageCollection.DelCollection(listBox.SelectedItem.ToString());
RefreshListBoxItems();
_logger.LogInformation("Removing collection succeed : {Name}", listBox.SelectedItem.ToString);
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
_logger.LogError("< Error > : {Message}", ex.Message);
}
_storageCollection.DelCollection(listBox.SelectedItem.ToString());
RefreshListBoxItems();
}
private void RefreshListBoxItems()
@@ -158,7 +200,8 @@ public partial class ServiceForm2 : Form
listBox.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? collName = _storageCollection.Keys?[i];
string? collName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(collName))
{
listBox.Items.Add(collName);
@@ -187,11 +230,76 @@ public partial class ServiceForm2 : Form
{
case "Storage":
_company = new ShipSharingService(pictureBox.Width,
pictureBox.Height, collection);
pictureBox.Height, collection);
break;
}
toolPanel.Enabled = true; // block of buttons at the right bottom
RefreshListBoxItems();
}
// saving to file
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show(" < Saved succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Saving to file : {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Result :", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("< Error > : {Message}", ex.Message);
}
}
}
// loading from file
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show(" < Loaded succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Loading from file : {Filename}", openFileDialog.FileName);
RefreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show("< Failed to load >" + ex.Message,
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("< Error > : {Message}", ex.Message);
}
}
}
// Сортировка по сравнителю
private void CompareShips(IComparer<DrawningBase?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
private void btnSortType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompare());
}
private void btnSortColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByColor());
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>217, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>460, 17</value>
</metadata>
</root>

View File

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