Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 477bdcf3d4 |
@@ -48,7 +48,7 @@ public abstract class AbstractCompany
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = collection;
|
||||
_collection.MaxCount = GetMaxCount;
|
||||
_collection.SetMaxCount = GetMaxCount;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
|
||||
@@ -16,6 +16,7 @@ public class AircraftSharingService : AbstractCompany
|
||||
private int? _startPosY;
|
||||
private int? ObjPositionX;
|
||||
private int? ObjPositionY;
|
||||
|
||||
private void DrawPlace(Graphics g)
|
||||
{
|
||||
Pen pen = new(Color.Black);
|
||||
|
||||
@@ -23,7 +23,7 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <summary>
|
||||
/// Установка максимального количества элементов
|
||||
/// </summary>
|
||||
int MaxCount { get; set; }
|
||||
int SetMaxCount { set; }
|
||||
|
||||
/// <summary>
|
||||
/// Добавление объекта в коллекцию
|
||||
@@ -53,15 +53,4 @@ public interface ICollectionGenericObjects<T>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns>Объект</returns>
|
||||
T? Get(int position);
|
||||
|
||||
/// <summary>
|
||||
/// Получение типа коллекции
|
||||
/// </summary>
|
||||
CollectionType GetCollectionType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Получение объектов коллекции по одному
|
||||
/// </summary>
|
||||
/// <returns>Поэлементый вывод элементов коллекции</returns>
|
||||
IEnumerable<T?> GetItems();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using ProectMilitaryAircraft.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -12,7 +11,7 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects;
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр : ограничение - ссылочный тип</typeparam>
|
||||
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public class ListgenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
@@ -27,25 +26,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
get => _maxCount;
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
_maxCount = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public ListGenericObjects()
|
||||
public ListgenericObjects()
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
@@ -53,15 +41,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public T? Get(int position)
|
||||
{
|
||||
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position > _maxCount)
|
||||
{
|
||||
new CollectionOverflowException();
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) return null;
|
||||
return _collection[position];
|
||||
|
||||
}
|
||||
@@ -73,10 +53,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection.Add(obj);
|
||||
return true;
|
||||
}
|
||||
if (_collection.Count == _maxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -87,14 +63,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection.Insert(position, obj);
|
||||
return true;
|
||||
}
|
||||
if (_collection.Count == _maxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(_maxCount);
|
||||
}
|
||||
if (!(Count >= 0 && Count <= Count))
|
||||
{
|
||||
throw new Exception("Неверная позиция для вставки");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -105,18 +73,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
if (!(position >= 0 && position < Count))
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using ProectMilitaryAircraft.Draw;
|
||||
using ProectMilitaryAircraft.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -13,7 +11,7 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр : Ограничение - ссылочный тип</typeparam>
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : DrawningAircraft
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
@@ -22,11 +20,8 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount {
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
public int SetMaxCount
|
||||
{
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
@@ -43,8 +38,6 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
}
|
||||
}
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -55,14 +48,6 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position > MaxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(MaxCount);
|
||||
}
|
||||
if (_collection == null)
|
||||
{
|
||||
throw new ObjectNotFoundException();
|
||||
}
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
return _collection[position];
|
||||
@@ -71,16 +56,10 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public bool Insert(T obj)
|
||||
{
|
||||
if (_collection.Length > Count)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
@@ -99,16 +78,6 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
_collection[position] = obj;
|
||||
return true;
|
||||
}
|
||||
if (position > Count)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
if (!(position >= 0 && position <= Count))
|
||||
{
|
||||
throw new Exception("Неверная позиция для вставки");
|
||||
}
|
||||
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
for (int i = position; i < _collection.Length; i++)
|
||||
@@ -141,21 +110,9 @@ namespace ProectMilitaryAircraft.CollectionGenericObjects
|
||||
_collection[position] = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using ProectMilitaryAircraft.Draw;
|
||||
using ProectMilitaryAircraft.Exceptions;
|
||||
using ProectMilitaryAircraft.MovementStrategy;
|
||||
using ProectMilitaryAircraft.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -10,7 +8,7 @@ using System.Threading.Tasks;
|
||||
namespace ProectMilitaryAircraft.CollectionGenericObjects;
|
||||
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningAircraft
|
||||
where T : class
|
||||
{
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
@@ -21,21 +19,6 @@ public class StorageCollection<T>
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
|
||||
public void AddCollection (string name, CollectionType collectionType)
|
||||
{
|
||||
if (name != null && !_storages.ContainsKey(name))
|
||||
@@ -47,7 +30,7 @@ public class StorageCollection<T>
|
||||
}
|
||||
if (collectionType == CollectionType.List)
|
||||
{
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
_storages.Add(name, new ListgenericObjects<T>());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -74,145 +57,4 @@ public class StorageCollection<T>
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствует коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
StringBuilder sb = new();
|
||||
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.Count);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
|
||||
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 Exception("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!strs[0].Equals(_collectionKey))
|
||||
{
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningCar() is T car)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!collection.Insert(car))
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
CollectionType.Massive => new MassiveGenericObjects<T>(),
|
||||
CollectionType.List => new ListGenericObjects<T>(),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ public class DrawningAircraft
|
||||
/// Верхняя координа прорисовки самолета
|
||||
/// </summary>
|
||||
protected int? _startPosY;
|
||||
public DrawningAircraft aircraft;
|
||||
|
||||
/// <summary>
|
||||
/// Ширина прорисовки самолета
|
||||
@@ -69,14 +68,14 @@ public class DrawningAircraft
|
||||
/// <summary>
|
||||
/// Пустой конструктор
|
||||
/// </summary>
|
||||
public DrawningAircraft()
|
||||
private DrawningAircraft()
|
||||
{
|
||||
_pictureWidth = null;
|
||||
_pictureHeight = null;
|
||||
_startPosX = null;
|
||||
_startPosY = null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@@ -91,7 +90,7 @@ public class DrawningAircraft
|
||||
return;
|
||||
}
|
||||
_pictureWidth = width;
|
||||
_pictureHeight = height;
|
||||
_pictureHeight = height;
|
||||
EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
|
||||
}
|
||||
|
||||
@@ -113,18 +112,6 @@ public class DrawningAircraft
|
||||
_drawingMilitaryAircraftHeight = drawingMilitaryAircraftHeight;
|
||||
EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор для Drawning
|
||||
/// </summary>
|
||||
/// <param name="speed"></param>
|
||||
/// <param name="weight"></param>
|
||||
/// <param name="bodyColor"></param>
|
||||
public DrawningAircraft(EntityAircraft entityAircraft)
|
||||
{
|
||||
EntityAircraft = entityAircraft;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Установка границ поля
|
||||
/// </summary>
|
||||
@@ -133,8 +120,10 @@ public class DrawningAircraft
|
||||
/// <returns>true - границы заданы, false - проверка не пройдена, нельзя разместить объект в этих размерах</returns>
|
||||
public bool SetpictureSize(int width, int height)
|
||||
{
|
||||
// TODO провека, что объект "влезает" в размеры поля
|
||||
// если влезает, сохраняем границы и корректируем позицию объекта, если она была установлена
|
||||
if (width <= _drawningMilitaryAircraftWidth || height <= _drawingMilitaryAircraftHeight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_pictureWidth = width;
|
||||
_pictureHeight = height;
|
||||
return true;
|
||||
|
||||
@@ -15,8 +15,6 @@ namespace ProectMilitaryAircraft.Draw;
|
||||
/// </summary>
|
||||
public class DrawningMilitaryAircraft : DrawningAircraft
|
||||
{
|
||||
private DrawningAircraft aircraft;
|
||||
|
||||
/// <summary>
|
||||
/// Констуктор
|
||||
/// </summary>
|
||||
@@ -36,25 +34,6 @@ public class DrawningMilitaryAircraft : DrawningAircraft
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор для DrawningAircraft2
|
||||
/// </summary>
|
||||
/// <param name="speed"></param>
|
||||
/// <param name="weight"></param>
|
||||
/// <param name="bodyColor"></param>
|
||||
/// <param name="additionalColor"></param>
|
||||
/// <param name="pin"></param>
|
||||
/// <param name="rokets"></param>
|
||||
/// <param name="symbolism"></param>
|
||||
public DrawningMilitaryAircraft(EntityAircraft entityAircraft)
|
||||
{
|
||||
if (entityAircraft != null)
|
||||
{
|
||||
EntityAircraft = entityAircraft;
|
||||
}
|
||||
}
|
||||
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityAircraft is not EntityMilitaryAircraft airCraft || !_startPosX.HasValue || !_startPosY.HasValue)
|
||||
@@ -110,7 +89,7 @@ public class DrawningMilitaryAircraft : DrawningAircraft
|
||||
//Носовая часть
|
||||
g.FillEllipse(abr, _startPosX.Value + 78, _startPosY.Value + 37, 10, 5);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
using ProectMilitaryAircraft.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProectMilitaryAircraft.Draw;
|
||||
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityCar
|
||||
/// </summary>
|
||||
public static class ExtensionDrawningAircraft
|
||||
{
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly string _separatorForObject = ":";
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawningAircraft? CreateDrawningCar(this string info)
|
||||
{
|
||||
string[] strs = info.Split(_separatorForObject);
|
||||
EntityAircraft? aircraft = EntityMilitaryAircraft.CreateEntityMilitaryAircraft(strs);
|
||||
if (aircraft != null)
|
||||
{
|
||||
return new DrawningMilitaryAircraft(aircraft);
|
||||
}
|
||||
|
||||
aircraft = EntityAircraft.CreateEntityAircraft(strs);
|
||||
if (aircraft != null)
|
||||
{
|
||||
return new DrawningAircraft(aircraft);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawningAircraft">Сохраняемый объект</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawningAircraft drawningAircraft)
|
||||
{
|
||||
string[]? array = drawningAircraft?.EntityAircraft?.GetStringRepresentation();
|
||||
|
||||
if (array == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(_separatorForObject, array);
|
||||
}
|
||||
}
|
||||
@@ -45,27 +45,4 @@ public class EntityAircraft
|
||||
BodyColor = bodyColor;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityAircraft? CreateEntityAircraft(string[] strs)
|
||||
{
|
||||
if (strs.Length != 4 || strs[0] != nameof(EntityAircraft))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EntityAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,27 +43,4 @@ public class EntityMilitaryAircraft : EntityAircraft
|
||||
Rokets = rokets;
|
||||
Symbolism = symbolism;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение строк со значениями свойств объекта класса-сущности
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string[] GetStringRepresentation()
|
||||
{
|
||||
return new[] { nameof(EntityMilitaryAircraft), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Pin.ToString(), Rokets.ToString(),Symbolism.ToString() };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание объекта из массива строк
|
||||
/// </summary>
|
||||
/// <param name="strs"></param>
|
||||
/// <returns></returns>
|
||||
public static EntityMilitaryAircraft? CreateEntityMilitaryAircraft(string[] strs)
|
||||
{
|
||||
if (strs.Length != 8 || strs[0] != nameof(EntityMilitaryAircraft))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new EntityMilitaryAircraft(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7]));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProectMilitaryAircraft.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) { }
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProectMilitaryAircraft.Exceptions;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указаной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public 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) { }
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProectMilitaryAircraft.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public 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) { }
|
||||
}
|
||||
@@ -46,17 +46,10 @@
|
||||
labelCollectionName = new Label();
|
||||
comboBoxSelectorCompany = new ComboBox();
|
||||
pictureBox = new PictureBox();
|
||||
menuStrip = new MenuStrip();
|
||||
файлToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveToolStripMenuItem = new ToolStripMenuItem();
|
||||
loadToolStripMenuItem = new ToolStripMenuItem();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
groupBoxTools.SuspendLayout();
|
||||
panelCompanyTools.SuspendLayout();
|
||||
panelStorage.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
|
||||
menuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxTools
|
||||
@@ -66,9 +59,9 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(607, 24);
|
||||
groupBoxTools.Location = new Point(607, 0);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(194, 560);
|
||||
groupBoxTools.Size = new Size(194, 563);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = " Инструменты";
|
||||
@@ -246,61 +239,19 @@
|
||||
// pictureBox
|
||||
//
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Location = new Point(0, 0);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(607, 560);
|
||||
pictureBox.Size = new Size(607, 563);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
// menuStrip
|
||||
//
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(801, 24);
|
||||
menuStrip.TabIndex = 2;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
// файлToolStripMenuItem
|
||||
//
|
||||
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
|
||||
файлToolStripMenuItem.Name = "файлToolStripMenuItem";
|
||||
файлToolStripMenuItem.Size = new Size(48, 20);
|
||||
файлToolStripMenuItem.Text = "Файл";
|
||||
//
|
||||
// saveToolStripMenuItem
|
||||
//
|
||||
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
|
||||
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
saveToolStripMenuItem.Size = new Size(181, 22);
|
||||
saveToolStripMenuItem.Text = "Сохранение";
|
||||
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// loadToolStripMenuItem
|
||||
//
|
||||
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(181, 22);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// FormAircraftCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(801, 584);
|
||||
ClientSize = new Size(801, 563);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
MainMenuStrip = menuStrip;
|
||||
Name = "FormAircraftCollection";
|
||||
Text = "Коллекция самолетов";
|
||||
groupBoxTools.ResumeLayout(false);
|
||||
@@ -309,10 +260,7 @@
|
||||
panelStorage.ResumeLayout(false);
|
||||
panelStorage.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
|
||||
menuStrip.ResumeLayout(false);
|
||||
menuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -335,11 +283,5 @@
|
||||
private Button buttonCreateCompany;
|
||||
private Button buttonCollectionDel;
|
||||
private Panel panelCompanyTools;
|
||||
private MenuStrip menuStrip;
|
||||
private ToolStripMenuItem файлToolStripMenuItem;
|
||||
private ToolStripMenuItem saveToolStripMenuItem;
|
||||
private ToolStripMenuItem loadToolStripMenuItem;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private OpenFileDialog openFileDialog;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProectMilitaryAircraft.CollectionGenericObjects;
|
||||
using ProectMilitaryAircraft.CollectionGenericObjects;
|
||||
using ProectMilitaryAircraft.Draw;
|
||||
using ProectMilitaryAircraft.Exceptions;
|
||||
using ProectMilitaryAircraft.MovementStrategy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -30,19 +28,14 @@ public partial class FormAircraftCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
|
||||
public FormAircraftCollection()
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_storageCollection = new();
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор компании
|
||||
@@ -51,7 +44,7 @@ public partial class FormAircraftCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ComboBoxSelectorCompany_SelectedValueChanged(object sender, EventArgs e)
|
||||
{
|
||||
panelCompanyTools.Enabled = false;
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -81,25 +74,15 @@ public partial class FormAircraftCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
if (_company + aircraft)
|
||||
{
|
||||
if (_company + aircraft )
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект добавлен", _company);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Не удалось добавить объект");
|
||||
}
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}. Не удалось добавить объект", ex.Message);
|
||||
|
||||
MessageBox.Show("не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,20 +104,14 @@ public partial class FormAircraftCollection : Form
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
try
|
||||
if (_company - pos)
|
||||
{
|
||||
if (_company - pos)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект удален", _company);
|
||||
}
|
||||
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,22 +130,12 @@ public partial class FormAircraftCollection : Form
|
||||
int counter = 100;
|
||||
while (aircraft == null)
|
||||
{
|
||||
try
|
||||
aircraft = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
aircraft = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
_logger.LogInformation("Рандомный объект", _company);
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (aircraft == null) { return; }
|
||||
@@ -213,7 +180,7 @@ public partial class FormAircraftCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
@@ -245,7 +212,7 @@ public partial class FormAircraftCollection : Form
|
||||
private void RefreshListBoxItems()
|
||||
{
|
||||
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];
|
||||
if (!string.IsNullOrEmpty(colName))
|
||||
@@ -268,7 +235,7 @@ public partial class FormAircraftCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem?.ToString()?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллкция не проиницилизирована");
|
||||
@@ -286,51 +253,4 @@ public partial class FormAircraftCollection : Form
|
||||
panelCompanyTools.Enabled = true;
|
||||
RefreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия на "Сохранение"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обработка нажатия на "Загрузка"
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RefreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,16 +117,4 @@
|
||||
<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>16, 5</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>125, 5</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>260, 5</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>48</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -8,11 +8,6 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@@ -28,10 +23,4 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,7 +1,3 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
|
||||
namespace ProectMilitaryAircraft
|
||||
{
|
||||
internal static class Program
|
||||
@@ -14,28 +10,8 @@ namespace ProectMilitaryAircraft
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
|
||||
ApplicationConfiguration.Initialize();
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormAircraftCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});
|
||||
Application.Run(new FormAircraftCollection());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true" internalLogLevel="Info">
|
||||
|
||||
<targets>
|
||||
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user