LabWork_7
This commit is contained in:
parent
53bc228956
commit
a3e707a26c
@ -1,6 +1,9 @@
|
||||
using ProjectTank.CollectionGenericObjects;
|
||||
using ProjectTank.Exceptions;
|
||||
|
||||
|
||||
|
||||
namespace ProjectTank.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
@ -12,14 +15,20 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Список объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _collection;
|
||||
|
||||
/// <summary>
|
||||
/// Максимально допустимое число объектов в списке
|
||||
/// </summary>
|
||||
private int _maxCount;
|
||||
|
||||
public int Count => _collection.Count;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
get => _maxCount;
|
||||
get
|
||||
{
|
||||
return _collection.Count;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
@ -29,7 +38,6 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public CollectionType GetCollectionType => CollectionType.List;
|
||||
|
||||
/// <summary>
|
||||
@ -39,47 +47,63 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_collection = new();
|
||||
}
|
||||
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position <= Count)
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
return _collection[position];
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
else
|
||||
return null;
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count + 1 > _maxCount)
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
// TODO вставка в конец набора
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
return _collection.Count;
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count + 1 > _maxCount)
|
||||
return -1;
|
||||
if (position < 0 || position > Count)
|
||||
return -1;
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
// TODO вставка по позиции
|
||||
_collection.Insert(position, obj);
|
||||
return 1;
|
||||
|
||||
return position;
|
||||
}
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
return null;
|
||||
T? temp = _collection[position];
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
// TODO удаление объекта из списка
|
||||
T? obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return temp;
|
||||
return obj;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < Count; i++)
|
||||
for (int i = 0; i < _collection.Count; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,149 +1,133 @@
|
||||
using ProjectTank.CollectionGenericObjects;
|
||||
using ProjectTank.Exceptions;
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
public int MaxCount
|
||||
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
where T : class
|
||||
{
|
||||
get
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
|
||||
public int MaxCount
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
get
|
||||
{
|
||||
if (Count > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
return _collection.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
public int SetMaxCount {
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
set
|
||||
{
|
||||
if (_collection.Length > 0)
|
||||
if (value > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= 0 && position < Count)
|
||||
{
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// вставка в свободное место набора
|
||||
return Insert(obj, 0);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
// проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
if (_collection[position] != null)
|
||||
{
|
||||
bool pushed = false;
|
||||
for (int index = position + 1; index < Count; index++)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
for (int index = position - 1; index >= 0; index--)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
Array.Resize(ref _collection, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_collection = new T?[value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
public CollectionType GetCollectionType => CollectionType.Massive;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public MassiveGenericObjects()
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position < 0 || position > _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (position >= Count && _collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
|
||||
return Insert(obj,0);
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position > _collection.Length || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
for (int tmp = position + 1; tmp < _collection.Length; tmp++)
|
||||
{
|
||||
if (_collection[tmp] == null)
|
||||
{
|
||||
_collection[tmp] = obj;
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
for (int tmp = position - 1; tmp >= 0; tmp--)
|
||||
{
|
||||
if (_collection[tmp] == null)
|
||||
{
|
||||
_collection[tmp] = obj;
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
// вставка
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count)
|
||||
public T? Remove(int position)
|
||||
{
|
||||
return null;
|
||||
// TODO проверка позиции
|
||||
if (position < 0 || position > _collection.Length)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
T? tmp = _collection[position];
|
||||
_collection[position] = null;
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
return tmp;
|
||||
}
|
||||
|
||||
if (_collection[position] == null) return null;
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
}
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; i++)
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
yield return _collection[i];
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
{
|
||||
yield return _collection[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
|
||||
using ProjectTank.Drawning;
|
||||
using ProjectTank.Exceptions;
|
||||
using System.Text;
|
||||
|
||||
namespace ProjectTank.CollectionGenericObjects
|
||||
@ -90,11 +91,11 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
return _storages[name];
|
||||
}
|
||||
}
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -102,78 +103,66 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter sw = new StreamWriter(fs);
|
||||
sw.WriteLine(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
writer.Write(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
sw.Write(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
continue;
|
||||
}
|
||||
sw.Write(value.Key);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.GetCollectionType);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
sw.Write(value.Value.MaxCount);
|
||||
sw.Write(_separatorForKeyValue);
|
||||
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
if (value.Value.Count == 0)
|
||||
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(data))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
}
|
||||
|
||||
writer.Write(sb);
|
||||
sw.Write(data);
|
||||
sw.Write(_separatorItems);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// Загрузка информации по локомотивам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
}
|
||||
|
||||
using (StreamReader fs = File.OpenText(filename))
|
||||
using (StreamReader reader = new(filename))
|
||||
{
|
||||
string str = fs.ReadLine();
|
||||
|
||||
if (str == null || str.Length == 0)
|
||||
string line = reader.ReadLine();
|
||||
if (line == null || line.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidDataException("В файле нет данных");
|
||||
}
|
||||
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
if (!line.Equals(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("В файле неверные данные");
|
||||
}
|
||||
|
||||
_storages.Clear();
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 4)
|
||||
{
|
||||
continue;
|
||||
@ -183,7 +172,7 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new InvalidOperationException("Не удалось создать коллекцию");
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -191,20 +180,28 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningTank() is T airbus)
|
||||
if (elem?.CreateDrawningTank() is T locomotive)
|
||||
{
|
||||
if (collection.Insert(airbus) == -1)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
if (collection.Insert(locomotive) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типа
|
||||
/// </summary>
|
||||
|
@ -31,7 +31,7 @@ namespace ProjectTank.CollectionGenericObjects
|
||||
int TankWidth = 0;
|
||||
int TankHeight = 0;
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
for (int i = 0; i < (_collection?.Count); i++)
|
||||
{
|
||||
if (_collection?.Get(i) != null)
|
||||
{
|
||||
|
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectTank.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException : ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message) : base(message) { }
|
||||
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectTank.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class ObjectNotFoundException : ApplicationException
|
||||
{
|
||||
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
|
||||
public ObjectNotFoundException() : base() { }
|
||||
public ObjectNotFoundException(string message) : base(message) { }
|
||||
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace ProjectTank.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class PositionOutOfCollectionException : ApplicationException
|
||||
{
|
||||
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
|
||||
public PositionOutOfCollectionException() : base() { }
|
||||
public PositionOutOfCollectionException(string message) : base(message) { }
|
||||
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
|
||||
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
@ -68,9 +68,9 @@ namespace ProjectTank
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(798, 24);
|
||||
groupBoxTools.Location = new Point(824, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(187, 611);
|
||||
groupBoxTools.Size = new Size(187, 623);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "инструменты";
|
||||
@ -250,7 +250,7 @@ namespace ProjectTank
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(798, 611);
|
||||
pictureBox.Size = new Size(824, 623);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -259,7 +259,7 @@ namespace ProjectTank
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(985, 24);
|
||||
menuStrip.Size = new Size(1011, 24);
|
||||
menuStrip.TabIndex = 8;
|
||||
menuStrip.Text = "menuStrip";
|
||||
//
|
||||
@ -298,7 +298,7 @@ namespace ProjectTank
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(985, 635);
|
||||
ClientSize = new Size(1011, 647);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
|
@ -1,5 +1,7 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectTank.CollectionGenericObjects;
|
||||
using ProjectTank.Drawning;
|
||||
using ProjectTank.Exceptions;
|
||||
|
||||
namespace ProjectTank
|
||||
{
|
||||
@ -12,18 +14,23 @@ namespace ProjectTank
|
||||
/// Хранилище коллекций
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningTank> _storageCollection;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormBattleTankCollection()
|
||||
public FormBattleTankCollection(ILogger<FormBattleTankCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -42,17 +49,28 @@ namespace ProjectTank
|
||||
/// <param name="type">Тип создоваемого объекта</param>
|
||||
private void SetTank(DrawningTank tank)
|
||||
{
|
||||
if (_company == null || tank == null)
|
||||
if (_company == null || tank == null)
|
||||
{
|
||||
return;
|
||||
|
||||
if (_company + tank != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
if (_company + tank >= 0)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект добавлен: " + tank.GetDataForSave());
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -76,20 +94,34 @@ namespace ProjectTank
|
||||
|
||||
private void buttonRemoveTank_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) return;
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
|
||||
|
||||
int position = Convert.ToInt32(maskedTextBox.Text);
|
||||
|
||||
if (_company - position != null)
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
return;
|
||||
}
|
||||
else
|
||||
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
try
|
||||
{
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Объект удален, позиция: " + pos);
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -99,20 +131,38 @@ namespace ProjectTank
|
||||
/// <param name="e"></param>
|
||||
private void ButtonGoToCheck_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null) return;
|
||||
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DrawningTank? tank = null;
|
||||
int coutner = 100;
|
||||
|
||||
int counter = 100;
|
||||
while (tank == null)
|
||||
{
|
||||
tank = _company.GetRandomObject();
|
||||
coutner--;
|
||||
if (coutner <= 0) break;
|
||||
try
|
||||
{
|
||||
tank = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
catch (PositionOutOfCollectionException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
if (tank == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (tank == null) return;
|
||||
|
||||
FormBattleTank form = new()
|
||||
{
|
||||
SetTank = tank
|
||||
@ -141,19 +191,26 @@ namespace ProjectTank
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
try
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена: " + textBoxCollectionName.Text);
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
catch (Exception ex)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
//MessageBox.Show(ex.Message);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -163,17 +220,24 @@ namespace ProjectTank
|
||||
/// <param name="e"></param>
|
||||
private void buttonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxСollection.SelectedIndex < 0 || listBoxСollection.SelectedItem == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
if (!radioButtonList.Checked && !radioButtonMassive.Checked || string.IsNullOrEmpty(textBoxCollectionName.Text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxСollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
try
|
||||
{
|
||||
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxСollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция удалена: " + listBoxСollection.SelectedItem.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
@ -225,13 +289,17 @@ namespace ProjectTank
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -245,15 +313,17 @@ namespace ProjectTank
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectTank
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,33 @@ namespace ProjectTank
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBattleTankCollection());
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBattleTankCollection>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBattleTankCollection>().AddLogging(option =>
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,26 +1,45 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net7.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net7.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
20
ProjectTank/ProjectTank/serilog.json
Normal file
20
ProjectTank/ProjectTank/serilog.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": "BattleTank"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user