7 Commits
Lab05 ... Lab07

Author SHA1 Message Date
93274b9a00 переделал метод прорисовки заднего фона 2024-05-21 03:46:06 +04:00
ef1bec9f3c переделал метод прорисовки заднего фона 2024-05-21 03:45:30 +04:00
6ead7f2b69 finish 2024-05-21 03:28:00 +04:00
5e46d4770d 1 2024-05-21 03:17:11 +04:00
1dc111bb61 123 2024-05-21 01:53:54 +04:00
c61f10fa34 Lab06 Finish 2024-05-21 01:03:29 +04:00
ed6631e1ea Class finish 2024-05-21 00:47:54 +04:00
20 changed files with 854 additions and 302 deletions

View File

@@ -8,6 +8,15 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -40,7 +40,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
@@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
@@ -62,9 +62,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param>
/// <param name="boat">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningAirPlane boat)
public static int operator +(AbstractCompany company, DrawningAirPlane airPlane)
{
return company._collection?.Insert(boat) ?? -1;
return company._collection?.Insert(airPlane) ?? -1;
}
/// <summary>
@@ -101,8 +101,13 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
}
return bitmap;
@@ -118,4 +123,4 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}
}

View File

@@ -32,10 +32,12 @@ public class AirPlaneSharingService : AbstractCompany
int offsetX = 10, offsetY = -12;
int x = _pictureWidth - _placeSizeWidth, y = offsetY;
numRows = 0;
while (y + _placeSizeHeight <= _pictureHeight)
int adjustedHeight = _pictureHeight - (_placeSizeHeight + 5 + offsetY);
while (y + _placeSizeHeight <= adjustedHeight)
{
int numCols = 0;
int initialX = x; // сохраняем начальное значение x
int initialX = x;
while (x >= 0)
{
numCols++;
@@ -45,12 +47,13 @@ public class AirPlaneSharingService : AbstractCompany
x -= _placeSizeWidth + 2;
}
numRows++;
x = initialX; // возвращаем x к начальному значению после завершения строки
x = initialX;
y += _placeSizeHeight + 5 + offsetY;
}
numCols = numCols; // сохраняем значение numCols для использования в других методах
numCols = numCols;
}
protected override void SetObjectsPosition()
{
if (locCoord == null || _collection == null)
@@ -60,8 +63,12 @@ public class AirPlaneSharingService : AbstractCompany
int row = numRows - 1, col = numCols;
for (int i = 0; i < _collection?.Count; i++, col--)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9);
}
catch (Exception) { }
if (col == 1)
{
col = numCols + 1;

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -15,7 +16,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@@ -45,4 +46,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Поэлементный вывод элементов коллекции
/// </summary>
/// <returns></returns>
IEnumerable<T?> GetItems();
}

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,7 +17,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@@ -28,30 +41,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
else
{
return null;
}
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount) { return -1; }
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count || Count == _maxCount)
{
return -1;
}
if (position < 0 || position >= Count)
throw new PositionOutOfCollectionException(position);
if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj);
return position;
@@ -59,9 +66,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -15,8 +16,12 @@ where T : class
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
@@ -33,6 +38,8 @@ where T : class
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@@ -43,12 +50,9 @@ where T : class
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
public int Insert(T obj)
@@ -61,14 +65,14 @@ where T : class
return i;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count)
{
return -1;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
@@ -93,17 +97,26 @@ where T : class
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T Remove(int position)
{
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;
}
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@@ -1,4 +1,6 @@
using System;
using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -10,7 +12,7 @@ namespace AirBomber.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningAirPlane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@@ -22,6 +24,21 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@@ -83,4 +100,124 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_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 Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningAirPlane() is T airplane)
{
try
{
if (collection.Insert(airplane) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@@ -28,6 +28,14 @@ public class DrawningAirBomber : DrawningAirPlane
EntityAirPlane = new EntityAirBomber(speed, weight, bodyColor, additionalColor, bombs, fuelTanks);
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="entityAirPlane"></param>
public DrawningAirBomber(EntityAirPlane entityAirPlane) : base()
{
EntityAirPlane = entityAirPlane;
}
public override void DrawTransport(Graphics g)
{
if (EntityAirPlane == null || EntityAirPlane is not EntityAirBomber airbomber || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -69,7 +69,7 @@ public class DrawningAirPlane
/// Пустой конструктор
/// </summary>
///
private DrawningAirPlane()
protected DrawningAirPlane()
{
_pictureHeight = null;
_pictureHeight = null;
@@ -92,11 +92,20 @@ public class DrawningAirPlane
/// </summary>
/// <param name="drawningAirBomberWidth">Ширина прорисовки самолета</param>
/// <param name="drawningAirBomberWidth">Высота прорисовки самолета</param>
protected DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
public DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
{
_drawningAirPlaneHeight = drawningAirBomberHeight;
_drawningAirPlaneWidth = drawningAirBomberWidth;
}
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="entityAirPlane"></param>
public DrawningAirPlane(EntityAirPlane entityAirPlane) : base()
{
EntityAirPlane = entityAirPlane;
}
/// <summary>
/// Установка границ поля

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.Drawnings;
public static class ExtentionDrawningAirPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningAirPlane? CreateDrawningAirPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityAirPlane? airPlane = EntityAirBomber.CreateEntityAirBomber(strs);
if (airPlane != null)
{
return new DrawningAirBomber(airPlane);
}
airPlane = EntityAirPlane.CreateEntityAirPlane(strs);
if (airPlane != null)
{
return new DrawningAirPlane(airPlane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirPlane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningAirPlane drawningAirPlane)
{
string[]? array = drawningAirPlane?.EntityAirPlane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@@ -4,38 +4,52 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.Entities
namespace AirBomber.Entities;
public class EntityAirBomber : EntityAirPlane
{
public class EntityAirBomber : EntityAirPlane
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
{
public Color AdditionalColor { get; private set; }
public void SetAdditionalColor(Color color) => AdditionalColor = color;
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
}
/// <summary>
/// Признак (опция) наличия бомб
/// </summary>
public bool Bombs { get; private set; }
/// <summary>
/// Признак (опция) наличия дополнительных топливных баков
/// </summary>
public bool FuelTanks { get; private set; }
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() };
}
/// <summary>
///
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bombs">Признак наличия бомб</param>
/// <param name="fuelTanks">Признак наличия дополнительных топливных баков</param>
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool bombs, bool fuelTanks) : base(speed, weight, bodyColor)
public static EntityAirBomber? CreateEntityAirBomber(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber))
{
AdditionalColor = additionalColor;
Bombs = bombs;
FuelTanks = fuelTanks;
return null;
}
return new EntityAirBomber(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]),
Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@@ -42,4 +42,28 @@ public class EntityAirPlane
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirPlane? CreateEntityAirPlane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityAirPlane))
{
return null;
}
return new EntityAirPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

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

View File

@@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace AirBomber.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,16 @@
using System.Runtime.Serialization;
namespace AirBomber.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

@@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@@ -59,9 +66,11 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(752, 0);
groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(208, 644);
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
groupBoxTools.Size = new Size(238, 859);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструманты";
@@ -73,18 +82,18 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonDelAirPlane);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Location = new Point(14, 342);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Location = new Point(16, 456);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(184, 214);
panelCompanyTools.Size = new Size(210, 285);
panelCompanyTools.TabIndex = 8;
//
// buttonAddAirPlane
//
buttonAddAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddAirPlane.Location = new Point(6, 3);
buttonAddAirPlane.Location = new Point(7, 4);
buttonAddAirPlane.Margin = new Padding(3, 4, 3, 4);
buttonAddAirPlane.Name = "buttonAddAirPlane";
buttonAddAirPlane.Size = new Size(175, 41);
buttonAddAirPlane.Size = new Size(200, 55);
buttonAddAirPlane.TabIndex = 1;
buttonAddAirPlane.Text = "Добавление самолета";
buttonAddAirPlane.UseVisualStyleBackColor = true;
@@ -92,18 +101,20 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(6, 98);
maskedTextBox.Location = new Point(7, 131);
maskedTextBox.Margin = new Padding(3, 4, 3, 4);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(176, 23);
maskedTextBox.Size = new Size(201, 27);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonRefresh
//
buttonRefresh.Location = new Point(6, 182);
buttonRefresh.Location = new Point(7, 243);
buttonRefresh.Margin = new Padding(3, 4, 3, 4);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(175, 22);
buttonRefresh.Size = new Size(200, 29);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@@ -112,9 +123,10 @@
// buttonDelAirPlane
//
buttonDelAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelAirPlane.Location = new Point(6, 124);
buttonDelAirPlane.Location = new Point(7, 165);
buttonDelAirPlane.Margin = new Padding(3, 4, 3, 4);
buttonDelAirPlane.Name = "buttonDelAirPlane";
buttonDelAirPlane.Size = new Size(175, 23);
buttonDelAirPlane.Size = new Size(200, 31);
buttonDelAirPlane.TabIndex = 4;
buttonDelAirPlane.Text = "Удалить Самолет";
buttonDelAirPlane.UseVisualStyleBackColor = true;
@@ -122,9 +134,10 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(6, 154);
buttonGoToCheck.Location = new Point(7, 205);
buttonGoToCheck.Margin = new Padding(3, 4, 3, 4);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(175, 22);
buttonGoToCheck.Size = new Size(200, 29);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -132,10 +145,9 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(14, 274);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Location = new Point(16, 365);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(181, 37);
buttonCreateCompany.Size = new Size(207, 49);
buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -151,18 +163,16 @@
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Location = new Point(3, 24);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(202, 228);
panelStorage.Size = new Size(232, 304);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(11, 203);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Location = new Point(13, 271);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(184, 22);
buttonCollectionDel.Size = new Size(210, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллецию";
buttonCollectionDel.UseVisualStyleBackColor = true;
@@ -171,19 +181,17 @@
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 121);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(3, 161);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(193, 79);
listBoxCollection.Size = new Size(220, 104);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(11, 94);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Location = new Point(13, 125);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(189, 22);
buttonCollectionAdd.Size = new Size(216, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллецию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
@@ -192,10 +200,9 @@
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(88, 72);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Location = new Point(101, 96);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
@@ -204,10 +211,9 @@
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(11, 72);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Location = new Point(13, 96);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19);
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
@@ -215,18 +221,17 @@
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 40);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Location = new Point(3, 53);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(198, 23);
textBoxCollectionName.Size = new Size(226, 27);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(11, 9);
labelCollectionName.Location = new Point(13, 12);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(119, 15);
labelCollectionName.Size = new Size(151, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллеции:";
//
@@ -236,9 +241,10 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(14, 248);
comboBoxSelectorCompany.Location = new Point(16, 331);
comboBoxSelectorCompany.Margin = new Padding(3, 4, 3, 4);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(184, 23);
comboBoxSelectorCompany.Size = new Size(210, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
//
@@ -246,18 +252,63 @@
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(752, 644);
pictureBox.Size = new Size(859, 859);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(7, 3, 0, 3);
menuStrip.Size = new Size(859, 30);
menuStrip.TabIndex = 3;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormAirPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(960, 644);
ClientSize = new Size(1097, 859);
Controls.Add(menuStrip);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Margin = new Padding(3, 4, 3, 4);
Name = "FormAirPlaneCollection";
Text = "FormAirPlaneCollection";
Load += FormAirPlaneCollection_Load;
@@ -267,7 +318,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -290,5 +344,11 @@
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@@ -9,109 +9,124 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
namespace AirBomber
namespace AirBomber;
public partial class FormAirPlaneCollection : Form
{
public partial class FormAirPlaneCollection : Form
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection(ILogger<FormAirPlaneCollection> logger)
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company;
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection()
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e)
{
FormAirPlaneConfig form = new();
//TODO передать метод
form.Show();
form.AddEvent(SetAirPlane);
}
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
/// <summary>
/// Добавление самолета в коллекцию
/// </summary>
/// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane)
{
try
{
if (_company == null || airplane == null)
{
return;
}
if (_company + airplane != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
throw new Exception("Входные данные отсутствуют");
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@@ -119,35 +134,40 @@ namespace AirBomber
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Объект удален");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
DrawningAirPlane? airplane = null;
int counter = 100;
while (airplane == null)
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningAirPlane? airPlane = null;
int counter = 100;
try
{
while (airPlane == null)
{
airplane = _company.GetRandomObject();
airPlane = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
@@ -155,43 +175,51 @@ namespace AirBomber
}
}
if (airplane == null)
if (airPlane == null)
{
return;
}
FormAirBomber form = new FormAirBomber();
form.SetAirPlane = airplane;
form.SetAirPlane = airPlane;
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
catch (Exception ex)
{
if (_company == null)
{
return;
}
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
pictureBox.Image = _company.Show();
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
pictureBox.Image = _company.Show();
}
private void FormAirPlaneCollection_Load(object sender, EventArgs e)
{
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
private void buttonCollectionAdd_Click(object sender, EventArgs e)
try
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
@@ -204,64 +232,118 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
private void RefreshListBoxItems()
catch (Exception ex)
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void RefreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
listBoxCollection.Items.Add(colName);
}
}
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
MessageBox.Show("Коллекция не выбрана");
return;
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
MessageBox.Show("Коллекция не выбрана");
return;
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
}
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
/// <summary>
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
}

View File

@@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>

View File

@@ -1,17 +1,45 @@
namespace AirBomber
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace AirBomber;
internal static class Program
{
internal static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirPlaneCollection());
}
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormAirPlaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
services.AddSingleton<FormAirPlaneCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder().
AddJsonFile($"{pathNeed}serilog.json").Build()).CreateLogger());
});
}
}

15
AirBomber/serilog.json Normal file
View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Applicatoin": "Sample"
}
}
}