ISEbd-12_Isaeva_V.D._Simple_LabWork07 #13
@ -1,4 +1,5 @@
|
||||
using ProjectAirbus.Drawnings;
|
||||
using ProjectAirbus.Exceptions;
|
||||
|
||||
namespace ProjectAirbus.CollectionGenericObjects;
|
||||
|
||||
@ -35,7 +36,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -96,8 +97,15 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningBus? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningBus? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{ }
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{ }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
|
@ -1,6 +1,7 @@
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Drawnings;
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Exceptions;
|
||||
|
||||
namespace ProjectAirbus.CollectionGenericObjects;
|
||||
|
||||
@ -23,27 +24,17 @@ public class AerodromService : AbstractCompany
|
||||
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
Pen pen = new Pen(Color.LightBlue, 3);
|
||||
int offsetX = 10;
|
||||
int offsetY = -12;
|
||||
int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY;
|
||||
numRows = 0;
|
||||
while (y >= 0)
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
Pen pen = new(Color.Black, 2);
|
||||
for (int i = 0; i < width + 1; i++)
|
||||
{
|
||||
int numCols = 0;
|
||||
while (x + _placeSizeWidth <= _pictureWidth)
|
||||
for (int j = 0; j < height + 1; ++j)
|
||||
{
|
||||
numCols++;
|
||||
g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y);
|
||||
g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8);
|
||||
locCoord.Add(new Tuple<int, int>(x, y));
|
||||
x += _placeSizeWidth + 2;
|
||||
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight);
|
||||
g.DrawLine(pen, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight, i * _placeSizeWidth - _placeSizeWidth + 8, j * _placeSizeHeight - _placeSizeHeight);
|
||||
}
|
||||
numRows++;
|
||||
x = 1 + offsetX;
|
||||
y -= _placeSizeHeight + 5 + offsetY;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected override void SetObjectsPosition()
|
||||
@ -56,12 +47,13 @@ public class AerodromService : AbstractCompany
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
try
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 35);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 20);
|
||||
}
|
||||
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (PositionOutOfCollectionException e) { }
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Exceptions;
|
||||
|
||||
namespace ProjectAirBus.CollectionGenericObjects;
|
||||
|
||||
@ -17,14 +18,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
private int _maxCount = 10;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
|
||||
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
public int MaxCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -36,32 +38,34 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
|
||||
if (position >= Count || position < 0) return null;
|
||||
//TODO выброс ошибки если выход за границу
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
|
||||
if (Count + 1 > _maxCount) return -1;
|
||||
// TODO выброс ошибки если переполнение
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
|
||||
if (Count + 1 > _maxCount) return -1;
|
||||
if (position < 0 || position > Count) return -1;
|
||||
// TODO выброс ошибки если переполнение
|
||||
// TODO выброс ошибки если за границу
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return 1;
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
|
||||
if (position < 0 || position > Count) return null;
|
||||
|
||||
// TODO если выброс за границу
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T? pos = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return pos;
|
||||
|
@ -1,4 +1,4 @@
|
||||
|
||||
using ProjectAirbus.Exceptions;
|
||||
|
||||
namespace ProjectAirbus.CollectionGenericObjects;
|
||||
|
||||
@ -48,15 +48,16 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return null; }
|
||||
// TODO выброс ошибки если выход за границу
|
||||
// TODO выброс ошибки если объект пустой
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
|
||||
// TODO выброс ошибки если переполнение
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
@ -65,52 +66,50 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
|
||||
index++;
|
||||
++index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return -1; }
|
||||
|
||||
if (_collection[position] == null)
|
||||
// TODO выброс ошибки если переполнение
|
||||
// TODO выброс ошибки если выход за границу
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index;
|
||||
|
||||
for (index = position + 1; index < _collection.Length; ++index)
|
||||
int index = position + 1;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
++index;
|
||||
}
|
||||
|
||||
for (index = position - 1; index >= 0; --index)
|
||||
index = position - 1;
|
||||
while (index >= 0)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
--index;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// TODO выброс ошибки если выход за границу
|
||||
// TODO выброс ошибки если объект пустой
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T obj = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Drawnings;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
|
||||
@ -10,41 +11,29 @@ namespace ProjectAirBus.CollectionGenericObjects;
|
||||
|
||||
public class StorageCollection<T>
|
||||
where T : DrawningBus
|
||||
{/// <summary>
|
||||
/// Словарь (хранилище) с коллекциями
|
||||
/// </summary>
|
||||
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий коллекций
|
||||
/// </summary>
|
||||
{
|
||||
|
||||
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
|
||||
|
||||
|
||||
public List<string> Keys => _storages.Keys.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Ключевое слово, с которого должен начинаться файл
|
||||
/// </summary>
|
||||
private readonly string _collectionKey = "CollectionsStorage";
|
||||
private readonly string _collectionKey = "CollectionStorage";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private readonly string _separatorForKeyValue = "|";
|
||||
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly string _separatorItems = ";";
|
||||
private readonly string _separatorItem = ";";
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public StorageCollection()
|
||||
{
|
||||
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
|
||||
}
|
||||
|
||||
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (name == null || _storages.ContainsKey(name)) { return; }
|
||||
switch (collectionType)
|
||||
|
||||
@ -63,7 +52,7 @@ public class StorageCollection<T>
|
||||
|
||||
public void DelCollection(string name)
|
||||
{
|
||||
|
||||
// TODO Прописать логику для удаления коллекции
|
||||
if (_storages.ContainsKey(name))
|
||||
_storages.Remove(name);
|
||||
}
|
||||
@ -73,122 +62,126 @@ public class StorageCollection<T>
|
||||
{
|
||||
get
|
||||
{
|
||||
|
||||
// TODO Продумать логику получения объекта
|
||||
if (name == null || !_storages.ContainsKey(name)) { return null; }
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по самолетам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
StringBuilder sb = new();
|
||||
|
||||
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter streamWriter = new StreamWriter(fs);
|
||||
streamWriter.Write(_collectionKey);
|
||||
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
streamWriter.Write(Environment.NewLine);
|
||||
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
sb.Append(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
streamWriter.Write(value.Key);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
streamWriter.Write(value.Value.GetCollectionType);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
streamWriter.Write(value.Value.MaxCount);
|
||||
streamWriter.Write(_separatorForKeyValue);
|
||||
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
streamWriter.Write(data);
|
||||
streamWriter.Write(_separatorItems);
|
||||
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItem);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new UTF8Encoding().GetBytes(sb.ToString());
|
||||
fs.Write(info, 0, info.Length);
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
return false;
|
||||
|
||||
_storages.Clear();
|
||||
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new UTF8Encoding(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
string[] record = str.Split(_separatorForKeyValue);
|
||||
|
||||
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningBus() is T aircraft)
|
||||
{
|
||||
if (collection.Insert(aircraft) == -1)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs.Length == 0 || strs == null)
|
||||
{
|
||||
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("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
|
||||
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningBus() is T bus)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(bus) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3] );
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
|
@ -0,0 +1,22 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirbus.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) { }
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirbus.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int count) : base("В коллекции превышено допустимое количество : " + count) { }
|
||||
|
||||
public ObjectNotFoundException() : base() { }
|
||||
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectAirbus.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
|
||||
internal class PositionOutOfCollectionException : ApplicationException
|
||||
{
|
||||
public PositionOutOfCollectionException(int count) : base("В коллекции превышено допустимое количество : " + count) { }
|
||||
|
||||
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) { }
|
||||
|
||||
}
|
@ -140,6 +140,7 @@
|
||||
buttonDelBus.TabIndex = 4;
|
||||
buttonDelBus.Text = "Удалить самолет";
|
||||
buttonDelBus.UseVisualStyleBackColor = true;
|
||||
buttonDelBus.Click += buttonDelBus_Click;
|
||||
//
|
||||
// maskedTextBox
|
||||
//
|
||||
|
@ -1,6 +1,9 @@
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Drawnings;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using ProjectAirBus.CollectionGenericObjects;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectAirbus;
|
||||
|
||||
@ -8,11 +11,15 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
private readonly StorageCollection<DrawningBus> _storageCollection;
|
||||
|
||||
private AbstractCompany? _company;
|
||||
public FormBusCollection()
|
||||
private AbstractCompany? _company = null;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public FormBusCollection(ILogger<FormBusCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -20,10 +27,6 @@ public partial class FormBusCollection : Form
|
||||
panelCompanyTools.Enabled = false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// добавить самолет
|
||||
/// </summary>
|
||||
@ -44,46 +47,52 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + bus != -1)
|
||||
try
|
||||
{
|
||||
var res = _company + bus;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox1.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Удаление объекта
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void buttonDelPlane_Click(object sender, EventArgs e)
|
||||
private void buttonDelBus_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||
DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox1.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -110,14 +119,14 @@ public partial class FormBusCollection : Form
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (bus == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
FormAirbus form = new();
|
||||
form.SetBus = bus;
|
||||
FormAirbus form = new()
|
||||
{
|
||||
SetBus = bus
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
@ -143,7 +152,8 @@ public partial class FormBusCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void buttonCollectionAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
|
||||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
@ -159,8 +169,18 @@ public partial class FormBusCollection : Form
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
try
|
||||
{
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
_logger.LogInformation("Добавление коллекции");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
@ -169,18 +189,20 @@ public partial class FormBusCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void buttonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
|
||||
if (listBoxCollection.SelectedItem == null)
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
|
||||
DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
@ -215,7 +237,8 @@ public partial class FormBusCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningBus>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
ICollectionGenericObjects<DrawningBus>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
@ -226,6 +249,7 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new AerodromService(pictureBox1.Width, pictureBox1.Height, collection);
|
||||
_logger.LogInformation("Компания создана");
|
||||
break;
|
||||
}
|
||||
|
||||
@ -237,15 +261,17 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -253,17 +279,18 @@ public partial class FormBusCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -247,6 +247,7 @@
|
||||
pictureBoxObject.Size = new Size(204, 121);
|
||||
pictureBoxObject.TabIndex = 1;
|
||||
pictureBoxObject.TabStop = false;
|
||||
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
|
@ -36,7 +36,7 @@ public partial class FormBusConfig : Form
|
||||
BusDelegate += busDelegate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void DrawObject()
|
||||
{
|
||||
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
@ -73,8 +73,8 @@ public partial class FormBusConfig : Form
|
||||
}
|
||||
|
||||
private void Panel_MouseDown(object? sender, MouseEventArgs e)
|
||||
{
|
||||
|
||||
{
|
||||
|
||||
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
|
||||
@ -126,7 +126,7 @@ public partial class FormBusConfig : Form
|
||||
|
||||
private void ButtonAddAirbus_Click(object sender, EventArgs e)
|
||||
{
|
||||
if(_bus != null)
|
||||
if (_bus != null)
|
||||
{
|
||||
BusDelegate?.Invoke(_bus);
|
||||
Close();
|
||||
|
@ -1,17 +1,44 @@
|
||||
namespace ProjectAirbus
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAirbus;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
internal static class Program
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
/// <summary>
|
||||
/// 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();
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBusCollection());
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBusCollection>().AddLogging(option =>
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
|
||||
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
@ -8,6 +8,15 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog" Version="5.3.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +32,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilogConfig.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
20
ProjectAirbus/ProjectAirbus/serilogConfig.json
Normal file
20
ProjectAirbus/ProjectAirbus/serilogConfig.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Airbus"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user
Требовалось заменить класс Exception на его более подходящих наследников