Compare commits
No commits in common. "dd959915105c52857620ec656a4ab0774fd0a6ee" and "dd419fa25c34a0a8e2aca276b0942636dcdaa6b4" have entirely different histories.
dd95991510
...
dd419fa25c
@ -1,5 +1,4 @@
|
||||
using Stormtrooper.Drawnings;
|
||||
using Stormtrooper.Exceptions;
|
||||
|
||||
namespace Stormtrooper.CollectionGenericObjects;
|
||||
|
||||
@ -36,7 +35,8 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
@ -92,30 +92,20 @@ public abstract class AbstractCompany
|
||||
{
|
||||
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
|
||||
Graphics graphics = Graphics.FromImage(bitmap);
|
||||
DrawBackground(graphics);
|
||||
|
||||
DrawBackgound(graphics);
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawningAircraft? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException e)
|
||||
{ }
|
||||
catch (PositionOutOfCollectionException e)
|
||||
{ }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Вывод заднего фона
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
protected abstract void DrawBackground(Graphics g);
|
||||
protected abstract void DrawBackgound(Graphics g);
|
||||
|
||||
/// <summary>
|
||||
/// Расстановка объектов
|
||||
|
@ -1,5 +1,4 @@
|
||||
using Stormtrooper.Drawnings;
|
||||
using Stormtrooper.Exceptions;
|
||||
|
||||
namespace Stormtrooper.CollectionGenericObjects
|
||||
{
|
||||
@ -18,7 +17,7 @@ namespace Stormtrooper.CollectionGenericObjects
|
||||
ICollectionGenericObjects<DrawningAircraft> collection) : base(picWidth, picHeight, collection)
|
||||
{
|
||||
}
|
||||
protected override void DrawBackground(Graphics g)
|
||||
protected override void DrawBackgound(Graphics g)
|
||||
{
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
@ -42,12 +41,12 @@ namespace Stormtrooper.CollectionGenericObjects
|
||||
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
try {
|
||||
if (_collection.Get(i) != null)
|
||||
{
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (PositionOutOfCollectionException e) { }
|
||||
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
else
|
||||
@ -64,4 +63,3 @@ namespace Stormtrooper.CollectionGenericObjects
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,4 @@
|
||||
using Stormtrooper.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -24,21 +23,7 @@ where T : class
|
||||
private int _maxCount;
|
||||
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;
|
||||
|
||||
@ -49,33 +34,49 @@ where T : class
|
||||
{
|
||||
_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 null;
|
||||
}
|
||||
public int Insert(T obj)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
if (Count <= _maxCount)
|
||||
{
|
||||
_collection.Add(obj);
|
||||
return Count;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (Count < _maxCount && position>=0 && position < _maxCount)
|
||||
{
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
T temp = _collection[position];
|
||||
if(position>=0 && position < _maxCount)
|
||||
{
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
return temp;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
|
@ -1,8 +1,7 @@
|
||||
using Stormtrooper.Exceptions;
|
||||
using Stormtrooper.CollectionGenericObjects;
|
||||
using Stormtrooper.Exceptions;
|
||||
using Stormtrooper.Drawnings;
|
||||
|
||||
namespace Stormtrooper.CollectionGenericObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
@ -14,20 +13,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private T?[] _collection;
|
||||
|
||||
public int Count => _collection.Length;
|
||||
/// <summary>
|
||||
/// Установка максимального кол-ва объектов
|
||||
/// </summary>
|
||||
public int MaxCount
|
||||
{
|
||||
|
||||
public int MaxCount {
|
||||
get
|
||||
{
|
||||
return _collection.Length;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value > 0)
|
||||
{
|
||||
if (value > 0) {
|
||||
if (_collection.Length > 0)
|
||||
{
|
||||
Array.Resize(ref _collection, value);
|
||||
@ -49,86 +45,71 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
_collection = Array.Empty<T?>();
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта по позиции
|
||||
/// </summary>
|
||||
/// <param name="position">Позиция (индекс)</param>
|
||||
/// <returns></returns>
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
// проверка позиции
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// вставка в свободное место набора
|
||||
for (int i = 0; i < Count; i++)
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
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 (position >= _collection.Length || position < 0)
|
||||
{ return -1; }
|
||||
|
||||
if (!pushed)
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
for (int index = position - 1; index >= 0; index--)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
position = index;
|
||||
pushed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!pushed)
|
||||
{
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
}
|
||||
|
||||
// вставка
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index;
|
||||
|
||||
public T? Remove(int position)
|
||||
for (index = position + 1; index < _collection.Length; ++index)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
|
||||
T? temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
}
|
||||
|
||||
for (index = position - 1; index >= 0; --index)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{ return null; }
|
||||
T DrawningAircraft = _collection[position];
|
||||
_collection[position] = null;
|
||||
return DrawningAircraft;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
|
@ -1,6 +1,5 @@
|
||||
using Stormtrooper.CollectionGenericObjects;
|
||||
using Stormtrooper.Drawnings;
|
||||
using Stormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -54,21 +53,20 @@ where T : DrawningAircraft
|
||||
/// <param name="collectionType">тип коллекции</param>
|
||||
public void AddCollection(string name, CollectionType collectionType)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
|
||||
return;
|
||||
switch (collectionType)
|
||||
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
|
||||
// TODO Прописать логику для добавления
|
||||
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
|
||||
{
|
||||
if (collectionType == CollectionType.List)
|
||||
{
|
||||
case CollectionType.List:
|
||||
_storages.Add(name, new ListGenericObjects<T>());
|
||||
break;
|
||||
case CollectionType.Massive:
|
||||
}
|
||||
else if (collectionType == CollectionType.Massive)
|
||||
{
|
||||
_storages.Add(name, new MassiveGenericObjects<T>());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
@ -87,8 +85,11 @@ where T : DrawningAircraft
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value))
|
||||
return value;
|
||||
// TODO Продумать логику получения объекта
|
||||
if (_storages.ContainsKey(name))
|
||||
{
|
||||
return _storages[name];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -97,11 +98,11 @@ where T : DrawningAircraft
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public void SaveData(string filename)
|
||||
public bool SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@ -110,6 +111,8 @@ where T : DrawningAircraft
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
|
||||
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
using StreamWriter streamWriter = new StreamWriter(fs);
|
||||
streamWriter.Write(_collectionKey);
|
||||
@ -145,37 +148,43 @@ where T : DrawningAircraft
|
||||
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по кораблям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
public void LoadData(string filename)
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не существует");
|
||||
return false;
|
||||
}
|
||||
|
||||
using (StreamReader sr = new StreamReader(filename))
|
||||
using (StreamReader sr = new StreamReader(filename))// открываем файла на чтение
|
||||
{
|
||||
string? str;
|
||||
str = sr.ReadLine();
|
||||
if (str != _collectionKey.ToString())
|
||||
throw new FormatException("В файле неверные данные");
|
||||
return false;
|
||||
|
||||
_storages.Clear();
|
||||
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
{
|
||||
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)
|
||||
{
|
||||
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
|
||||
return false;
|
||||
}
|
||||
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
@ -184,23 +193,16 @@ where T : DrawningAircraft
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningAircraft() is T aircraft)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(aircraft) == -1)
|
||||
{
|
||||
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new CollectionOverflowException("Коллекция переполнена", ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
|
@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace 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) { }
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
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) { }
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
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) { }
|
||||
}
|
@ -66,9 +66,9 @@
|
||||
groupBoxTools.Controls.Add(panelStorage);
|
||||
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(959, 28);
|
||||
groupBoxTools.Location = new Point(980, 28);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(264, 660);
|
||||
groupBoxTools.Size = new Size(264, 649);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Tag = "";
|
||||
@ -250,7 +250,7 @@
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 28);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(959, 660);
|
||||
pictureBox.Size = new Size(980, 649);
|
||||
pictureBox.TabIndex = 1;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -260,7 +260,7 @@
|
||||
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
|
||||
menuStrip.Location = new Point(0, 0);
|
||||
menuStrip.Name = "menuStrip";
|
||||
menuStrip.Size = new Size(1223, 28);
|
||||
menuStrip.Size = new Size(1244, 28);
|
||||
menuStrip.TabIndex = 2;
|
||||
menuStrip.Text = "menuStrip1";
|
||||
//
|
||||
@ -285,7 +285,7 @@
|
||||
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
|
||||
loadToolStripMenuItem.Size = new Size(227, 26);
|
||||
loadToolStripMenuItem.Text = "Загрузка";
|
||||
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
|
||||
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
@ -299,7 +299,7 @@
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1223, 688);
|
||||
ClientSize = new Size(1244, 677);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
|
@ -1,7 +1,5 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Stormtrooper.CollectionGenericObjects;
|
||||
using Stormtrooper.CollectionGenericObjects;
|
||||
using Stormtrooper.Drawnings;
|
||||
using Stormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@ -27,19 +25,13 @@ public partial class FormAircraftCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company;
|
||||
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
|
||||
public FormAircraftCollection()
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -70,52 +62,38 @@ public partial class FormAircraftCollection : Form
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
|
||||
if (_company + aircraft != -1)
|
||||
{
|
||||
var res = _company + aircraft;
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Объект добавлен под индексом {res}");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Кнопка удаления самолета
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveAircraft_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);
|
||||
try
|
||||
if (_company - pos != null)
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
MessageBox.Show("Объект удален!");
|
||||
pictureBox.Image = _company.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
|
||||
@ -165,13 +143,13 @@ public partial class FormAircraftCollection : 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);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@ -181,20 +159,9 @@ public partial class FormAircraftCollection : Form
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
|
||||
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>
|
||||
/// Удаление коллекции
|
||||
@ -203,21 +170,22 @@ public partial class FormAircraftCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
// TODO прописать логику удаления элемента из коллекции
|
||||
// нужно убедиться, что есть выбранная коллекция
|
||||
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
|
||||
// удалить и обновить ListBox
|
||||
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.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
_logger.LogInformation("Коллекция удалена");
|
||||
RerfreshListBoxItems();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -233,8 +201,7 @@ public partial class FormAircraftCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
ICollectionGenericObjects<DrawningAircraft>? collection =
|
||||
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
ICollectionGenericObjects<DrawningAircraft>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
|
||||
if (collection == null)
|
||||
{
|
||||
MessageBox.Show("Коллекция не проинициализирована");
|
||||
@ -245,12 +212,12 @@ public partial class FormAircraftCollection : Form
|
||||
{
|
||||
case "Хранилище":
|
||||
_company = new AircraftHangarService(pictureBox.Width, pictureBox.Height, collection);
|
||||
_logger.LogInformation("Компания создана");
|
||||
break;
|
||||
}
|
||||
|
||||
panelCompanyTools.Enabled = true;
|
||||
RerfreshListBoxItems();
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление списка в listBoxCollection
|
||||
@ -277,16 +244,13 @@ public partial class FormAircraftCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -296,21 +260,18 @@ public partial class FormAircraftCollection : Form
|
||||
/// </summary>
|
||||
/// <param name="sender"></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)
|
||||
{
|
||||
try
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,44 +1,17 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
|
||||
namespace Stormtrooper;
|
||||
|
||||
namespace Stormtrooper
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
/// <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())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
|
||||
Application.Run(new 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);
|
||||
});
|
||||
}
|
||||
}
|
@ -8,16 +8,6 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,20 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user