Compare commits

..

5 Commits

Author SHA1 Message Date
dd95991510 Готовый вариант 2024-05-01 23:12:01 +03:00
4dfab08ee6 4 2024-05-01 18:17:48 +03:00
a272e8dbd0 3 2024-05-01 17:20:31 +03:00
44f7ef01e8 2 2024-05-01 17:15:59 +03:00
92f5da95a6 Недоработка 2024-05-01 16:28:32 +03:00
13 changed files with 385 additions and 194 deletions

View File

@ -1,4 +1,5 @@
using Stormtrooper.Drawnings; using Stormtrooper.Drawnings;
using Stormtrooper.Exceptions;
namespace Stormtrooper.CollectionGenericObjects; namespace Stormtrooper.CollectionGenericObjects;
@ -35,8 +36,7 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -92,20 +92,30 @@ public abstract class AbstractCompany
{ {
Bitmap bitmap = new(_pictureWidth, _pictureHeight); Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap); Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics); DrawBackground(graphics);
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningAircraft? obj = _collection?.Get(i); DrawningAircraft? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
}
return bitmap; return bitmap;
} }
/// <summary> /// <summary>
/// Вывод заднего фона /// Вывод заднего фона
/// </summary> /// </summary>
/// <param name="g"></param> /// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g); protected abstract void DrawBackground(Graphics g);
/// <summary> /// <summary>
/// Расстановка объектов /// Расстановка объектов

View File

@ -1,4 +1,5 @@
using Stormtrooper.Drawnings; using Stormtrooper.Drawnings;
using Stormtrooper.Exceptions;
namespace Stormtrooper.CollectionGenericObjects namespace Stormtrooper.CollectionGenericObjects
{ {
@ -17,7 +18,7 @@ namespace Stormtrooper.CollectionGenericObjects
ICollectionGenericObjects<DrawningAircraft> collection) : base(picWidth, picHeight, collection) ICollectionGenericObjects<DrawningAircraft> collection) : base(picWidth, picHeight, collection)
{ {
} }
protected override void DrawBackgound(Graphics g) protected override void DrawBackground(Graphics g)
{ {
int width = _pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight; int height = _pictureHeight / _placeSizeHeight;
@ -41,18 +42,18 @@ namespace Stormtrooper.CollectionGenericObjects
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null) try {
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
} }
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else
{ {
curWidth = width - 1; curWidth = width - 1;
curHeight ++; curHeight++;
} }
if (curHeight >= height) if (curHeight >= height)
@ -63,3 +64,4 @@ namespace Stormtrooper.CollectionGenericObjects
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using Stormtrooper.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -23,7 +24,21 @@ where T : class
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } } public int MaxCount
{
set
{
if (value > 0)
{
_maxCount = value;
}
}
get
{
return Count;
}
}
public CollectionType GetCollectionType => CollectionType.List; public CollectionType GetCollectionType => CollectionType.List;
@ -34,52 +49,36 @@ where T : class
{ {
_collection = new(); _collection = new();
} }
public T? Get(int position) public T Get(int position)
{
// TODO проверка позиции
if( position>= 0 && position < Count)
{ {
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) throw new CollectionOverflowException(Count);
// TODO вставка в конец набора
if (Count <= _maxCount)
{
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
return -1;
}
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов if (Count == _maxCount) throw new CollectionOverflowException(Count);
// TODO проверка позиции if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
// TODO вставка по позиции
if (Count < _maxCount && position>=0 && position < _maxCount)
{
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
return -1;
}
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
// TODO удаление объекта из списка T obj = _collection[position];
T temp = _collection[position];
if(position>=0 && position < _maxCount)
{
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return obj;
}
return null;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < Count; ++i) for (int i = 0; i < Count; ++i)
{ {

View File

@ -1,29 +1,33 @@
using Stormtrooper.Drawnings; using Stormtrooper.Exceptions;
using Stormtrooper.CollectionGenericObjects;
using Stormtrooper.Exceptions;
namespace Stormtrooper.CollectionGenericObjects; namespace Stormtrooper.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam> /// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
/// <summary>
public int MaxCount { /// Установка максимального кол-ва объектов
/// </summary>
public int MaxCount
{
get get
{ {
return _collection.Length; return _collection.Length;
} }
set set
{ {
if (value > 0) { if (value > 0)
{
if (_collection.Length > 0) if (_collection.Length > 0)
{ {
Array.Resize(ref _collection, value); Array.Resize(ref _collection, value);
@ -45,71 +49,86 @@ where T : class
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция (индекс)</param>
/// <returns></returns>
public T? Get(int position) public T? Get(int position)
{ {
// проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0) if (_collection[position] == null) throw new ObjectNotFoundException(position);
{
return null;
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// вставка в свободное место набора // вставка в свободное место набора
int index = 0; for (int i = 0; i < Count; i++)
while (index < _collection.Length)
{ {
if (_collection[index] == null) if (_collection[i] == null)
{ {
_collection[index] = obj; _collection[i] = obj;
return index; return i;
} }
index++;
} }
return -1;
throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// проверка позиции
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0) if (_collection[position] != null)
{ return -1; }
if (_collection[position] == null)
{ {
_collection[position] = obj; bool pushed = false;
return position; for (int index = position + 1; index < Count; index++)
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
_collection[position] = obj; position = index;
return position; pushed = true;
break;
} }
} }
for (index = position - 1; index >= 0; --index) if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{ {
if (_collection[index] == null) if (_collection[index] == null)
{ {
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
}
}
// вставка
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
}
return -1; public T? Remove(int position)
}
public T Remove(int position)
{ {
if (position >= _collection.Length || position < 0) // проверка позиции
{ return null; } if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
T DrawningAircraft = _collection[position];
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return DrawningAircraft; return temp;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < _collection.Length; ++i) for (int i = 0; i < _collection.Length; ++i)

View File

@ -1,5 +1,6 @@
using Stormtrooper.CollectionGenericObjects; using Stormtrooper.CollectionGenericObjects;
using Stormtrooper.Drawnings; using Stormtrooper.Drawnings;
using Stormtrooper.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -53,20 +54,21 @@ where T : DrawningAircraft
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
// TODO Прописать логику для добавления return;
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name)) switch (collectionType)
{
if (collectionType == CollectionType.List)
{ {
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>()); _storages.Add(name, new ListGenericObjects<T>());
} break;
else if (collectionType == CollectionType.Massive) case CollectionType.Massive:
{
_storages.Add(name, new MassiveGenericObjects<T>()); _storages.Add(name, new MassiveGenericObjects<T>());
break;
default:
break;
} }
} }
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
@ -85,11 +87,8 @@ where T : DrawningAircraft
{ {
get get
{ {
// TODO Продумать логику получения объекта if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
if (_storages.ContainsKey(name)) return value;
{
return _storages[name];
}
return null; return null;
} }
} }
@ -98,11 +97,11 @@ where T : DrawningAircraft
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
@ -111,8 +110,6 @@ where T : DrawningAircraft
File.Delete(filename); File.Delete(filename);
} }
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs); using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey); streamWriter.Write(_collectionKey);
@ -148,43 +145,37 @@ where T : DrawningAircraft
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по кораблям в хранилище из файла /// Загрузка информации по кораблям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение
using (StreamReader sr = new StreamReader(filename))
{ {
string? str; string? str;
str = sr.ReadLine(); str = sr.ReadLine();
if (str != _collectionKey.ToString()) if (str != _collectionKey.ToString())
return false; throw new FormatException("В файле неверные данные");
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
string[] record = str.Split(_separatorForKeyValue); string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4) if (record.Length != 4)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -193,16 +184,23 @@ where T : DrawningAircraft
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningAircraft() is T aircraft) if (elem?.CreateDrawningAircraft() is T aircraft)
{
try
{ {
if (collection.Insert(aircraft) == -1) if (collection.Insert(aircraft) == -1)
return false; {
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{ {

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace Stormtrooper.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,21 @@
using System.Runtime.Serialization;
namespace Stormtrooper.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) { }
}

View File

@ -66,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(980, 28); groupBoxTools.Location = new Point(959, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(264, 649); groupBoxTools.Size = new Size(264, 660);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Tag = ""; groupBoxTools.Tag = "";
@ -250,7 +250,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(980, 649); pictureBox.Size = new Size(959, 660);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -260,7 +260,7 @@
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1244, 28); menuStrip.Size = new Size(1223, 28);
menuStrip.TabIndex = 2; menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
@ -285,7 +285,7 @@
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26); loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка"; loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
// //
// saveFileDialog // saveFileDialog
// //
@ -299,7 +299,7 @@
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1244, 677); ClientSize = new Size(1223, 688);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);

View File

@ -1,5 +1,7 @@
using Stormtrooper.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using Stormtrooper.CollectionGenericObjects;
using Stormtrooper.Drawnings; using Stormtrooper.Drawnings;
using Stormtrooper.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -25,13 +27,19 @@ public partial class FormAircraftCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company; private AbstractCompany? _company;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormAircraftCollection() public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -62,38 +70,52 @@ public partial class FormAircraftCollection : Form
{ {
return; return;
} }
try
if (_company + aircraft != -1)
{ {
var res = _company + aircraft;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show(); pictureBox.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 ButtonRemoveAircraft_Click(object sender, EventArgs e) private void ButtonRemoveAircraft_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален!"); var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }
@ -143,13 +165,13 @@ public partial class FormAircraftCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionAdd_Click(object sender, EventArgs e) private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -159,9 +181,20 @@ public partial class FormAircraftCollection : Form
{ {
collectionType = CollectionType.List; collectionType = CollectionType.List;
} }
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -170,22 +203,21 @@ public partial class FormAircraftCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e) private void ButtonCollectionDel_Click(object sender, EventArgs e)
{ {
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
DialogResult.Yes)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
} }
/// <summary> /// <summary>
@ -201,7 +233,8 @@ public partial class FormAircraftCollection : Form
return; return;
} }
ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; ICollectionGenericObjects<DrawningAircraft>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
@ -212,12 +245,12 @@ public partial class FormAircraftCollection : Form
{ {
case "Хранилище": case "Хранилище":
_company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection); _company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary> /// <summary>
/// Обновление списка в listBoxCollection /// Обновление списка в listBoxCollection
@ -244,13 +277,16 @@ public partial class FormAircraftCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -260,18 +296,21 @@ public partial class FormAircraftCollection : Form
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.LoadData(openFileDialog.FileName);
RerfreshListBoxItems(); 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);
} }
} }
} }

View File

@ -1,17 +1,44 @@
namespace Stormtrooper using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
namespace Stormtrooper;
internal static class Program
{ {
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormAircraftCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
} }
} }
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAircraftCollection>().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);
});
}
} }

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View 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": "Stormtrooper"
}
}
}