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> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@@ -40,7 +40,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>
/// Конструктор /// Конструктор
@@ -53,7 +53,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>
@@ -62,9 +62,9 @@ public abstract class AbstractCompany
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="boat">Добавляемый объект</param> /// <param name="boat">Добавляемый объект</param>
/// <returns></returns> /// <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> /// <summary>
@@ -100,10 +100,15 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{ {
DrawningAirPlane? obj = _collection?.Get(i); DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics); obj?.DrawTransport(graphics);
} }
catch (Exception) { }
}
return bitmap; return bitmap;
} }

View File

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

View File

@@ -1,4 +1,5 @@
using System; using AirBomber.CollectionGenericObjects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -15,7 +16,7 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@@ -45,4 +46,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); 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.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -16,7 +17,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; 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> /// <summary>
/// Конструктор /// Конструктор
@@ -28,30 +41,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{
return _collection[position]; return _collection[position];
} }
else
{
return null;
}
}
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) { return -1; } if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count || Count == _maxCount) if (position < 0 || position >= Count)
{ throw new PositionOutOfCollectionException(position);
return -1;
} if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
@@ -59,9 +66,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T Remove(int position) 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]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; 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.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -15,8 +16,12 @@ where T : class
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@@ -33,6 +38,8 @@ where T : class
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -43,14 +50,11 @@ where T : class
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
return null;
}
public int Insert(T obj) public int Insert(T obj)
{ {
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
@@ -61,14 +65,14 @@ where T : class
return i; return i;
} }
} }
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) if (position < 0 || position >= Count)
{ {
return -1; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) if (_collection[position] == null)
{ {
@@ -93,17 +97,26 @@ where T : class
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position]; T obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; 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.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -10,7 +12,7 @@ namespace AirBomber.CollectionGenericObjects;
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningAirPlane
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@@ -22,6 +24,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); 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>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@@ -83,4 +100,124 @@ public class StorageCollection<T>
return null; 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); 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) public override void DrawTransport(Graphics g)
{ {
if (EntityAirPlane == null || EntityAirPlane is not EntityAirBomber airbomber || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityAirPlane == null || EntityAirPlane is not EntityAirBomber airbomber || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@@ -69,7 +69,7 @@ public class DrawningAirPlane
/// Пустой конструктор /// Пустой конструктор
/// </summary> /// </summary>
/// ///
private DrawningAirPlane() protected DrawningAirPlane()
{ {
_pictureHeight = null; _pictureHeight = null;
_pictureHeight = null; _pictureHeight = null;
@@ -92,12 +92,21 @@ public class DrawningAirPlane
/// </summary> /// </summary>
/// <param name="drawningAirBomberWidth">Ширина прорисовки самолета</param> /// <param name="drawningAirBomberWidth">Ширина прорисовки самолета</param>
/// <param name="drawningAirBomberWidth">Высота прорисовки самолета</param> /// <param name="drawningAirBomberWidth">Высота прорисовки самолета</param>
protected DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this() public DrawningAirPlane(int drawningAirBomberWidth, int drawningAirBomberHeight) : this()
{ {
_drawningAirPlaneHeight = drawningAirBomberHeight; _drawningAirPlaneHeight = drawningAirBomberHeight;
_drawningAirPlaneWidth = drawningAirBomberWidth; _drawningAirPlaneWidth = drawningAirBomberWidth;
} }
/// <summary>
/// Конструктор через сущность
/// </summary>
/// <param name="entityAirPlane"></param>
public DrawningAirPlane(EntityAirPlane entityAirPlane) : base()
{
EntityAirPlane = entityAirPlane;
}
/// <summary> /// <summary>
/// Установка границ поля /// Установка границ поля
/// </summary> /// </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,8 +4,8 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; 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 Color AdditionalColor { get; private set; }
@@ -37,5 +37,19 @@ namespace AirBomber.Entities
Bombs = bombs; Bombs = bombs;
FuelTanks = fuelTanks; FuelTanks = fuelTanks;
} }
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirBomber), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Bombs.ToString(), FuelTanks.ToString() };
}
public static EntityAirBomber? CreateEntityAirBomber(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAirBomber))
{
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; Weight = weight;
BodyColor = bodyColor; 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(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@@ -59,9 +66,11 @@
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(752, 0); groupBoxTools.Location = new Point(859, 0);
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
groupBoxTools.Name = "groupBoxTools"; 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.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструманты"; groupBoxTools.Text = "Инструманты";
@@ -73,18 +82,18 @@
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonDelAirPlane); panelCompanyTools.Controls.Add(buttonDelAirPlane);
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Location = new Point(14, 342); panelCompanyTools.Location = new Point(16, 456);
panelCompanyTools.Margin = new Padding(3, 2, 3, 2);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(184, 214); panelCompanyTools.Size = new Size(210, 285);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonAddAirPlane // buttonAddAirPlane
// //
buttonAddAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; 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.Name = "buttonAddAirPlane";
buttonAddAirPlane.Size = new Size(175, 41); buttonAddAirPlane.Size = new Size(200, 55);
buttonAddAirPlane.TabIndex = 1; buttonAddAirPlane.TabIndex = 1;
buttonAddAirPlane.Text = "Добавление самолета"; buttonAddAirPlane.Text = "Добавление самолета";
buttonAddAirPlane.UseVisualStyleBackColor = true; buttonAddAirPlane.UseVisualStyleBackColor = true;
@@ -92,18 +101,20 @@
// //
// maskedTextBox // 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.Mask = "00";
maskedTextBox.Name = "maskedTextBox"; maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(176, 23); maskedTextBox.Size = new Size(201, 27);
maskedTextBox.TabIndex = 3; maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int); maskedTextBox.ValidatingType = typeof(int);
// //
// buttonRefresh // 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.Name = "buttonRefresh";
buttonRefresh.Size = new Size(175, 22); buttonRefresh.Size = new Size(200, 29);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@@ -112,9 +123,10 @@
// buttonDelAirPlane // buttonDelAirPlane
// //
buttonDelAirPlane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; 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.Name = "buttonDelAirPlane";
buttonDelAirPlane.Size = new Size(175, 23); buttonDelAirPlane.Size = new Size(200, 31);
buttonDelAirPlane.TabIndex = 4; buttonDelAirPlane.TabIndex = 4;
buttonDelAirPlane.Text = "Удалить Самолет"; buttonDelAirPlane.Text = "Удалить Самолет";
buttonDelAirPlane.UseVisualStyleBackColor = true; buttonDelAirPlane.UseVisualStyleBackColor = true;
@@ -122,9 +134,10 @@
// //
// buttonGoToCheck // 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.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(175, 22); buttonGoToCheck.Size = new Size(200, 29);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@@ -132,10 +145,9 @@
// //
// buttonCreateCompany // buttonCreateCompany
// //
buttonCreateCompany.Location = new Point(14, 274); buttonCreateCompany.Location = new Point(16, 365);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(181, 37); buttonCreateCompany.Size = new Size(207, 49);
buttonCreateCompany.TabIndex = 7; buttonCreateCompany.TabIndex = 7;
buttonCreateCompany.Text = "Создать компанию"; buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true; buttonCreateCompany.UseVisualStyleBackColor = true;
@@ -151,18 +163,16 @@
panelStorage.Controls.Add(textBoxCollectionName); panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName); panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top; panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19); panelStorage.Location = new Point(3, 24);
panelStorage.Margin = new Padding(3, 2, 3, 2);
panelStorage.Name = "panelStorage"; panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(202, 228); panelStorage.Size = new Size(232, 304);
panelStorage.TabIndex = 7; panelStorage.TabIndex = 7;
// //
// buttonCollectionDel // buttonCollectionDel
// //
buttonCollectionDel.Location = new Point(11, 203); buttonCollectionDel.Location = new Point(13, 271);
buttonCollectionDel.Margin = new Padding(3, 2, 3, 2);
buttonCollectionDel.Name = "buttonCollectionDel"; buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(184, 22); buttonCollectionDel.Size = new Size(210, 29);
buttonCollectionDel.TabIndex = 6; buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллецию"; buttonCollectionDel.Text = "Удалить коллецию";
buttonCollectionDel.UseVisualStyleBackColor = true; buttonCollectionDel.UseVisualStyleBackColor = true;
@@ -171,19 +181,17 @@
// listBoxCollection // listBoxCollection
// //
listBoxCollection.FormattingEnabled = true; listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15; listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(3, 121); listBoxCollection.Location = new Point(3, 161);
listBoxCollection.Margin = new Padding(3, 2, 3, 2);
listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(193, 79); listBoxCollection.Size = new Size(220, 104);
listBoxCollection.TabIndex = 5; listBoxCollection.TabIndex = 5;
// //
// buttonCollectionAdd // buttonCollectionAdd
// //
buttonCollectionAdd.Location = new Point(11, 94); buttonCollectionAdd.Location = new Point(13, 125);
buttonCollectionAdd.Margin = new Padding(3, 2, 3, 2);
buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(189, 22); buttonCollectionAdd.Size = new Size(216, 29);
buttonCollectionAdd.TabIndex = 4; buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллецию"; buttonCollectionAdd.Text = "Добавить коллецию";
buttonCollectionAdd.UseVisualStyleBackColor = true; buttonCollectionAdd.UseVisualStyleBackColor = true;
@@ -192,10 +200,9 @@
// radioButtonList // radioButtonList
// //
radioButtonList.AutoSize = true; radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(88, 72); radioButtonList.Location = new Point(101, 96);
radioButtonList.Margin = new Padding(3, 2, 3, 2);
radioButtonList.Name = "radioButtonList"; radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19); radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3; radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true; radioButtonList.TabStop = true;
radioButtonList.Text = "Список"; radioButtonList.Text = "Список";
@@ -204,10 +211,9 @@
// radioButtonMassive // radioButtonMassive
// //
radioButtonMassive.AutoSize = true; radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(11, 72); radioButtonMassive.Location = new Point(13, 96);
radioButtonMassive.Margin = new Padding(3, 2, 3, 2);
radioButtonMassive.Name = "radioButtonMassive"; radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(67, 19); radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2; radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true; radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив"; radioButtonMassive.Text = "Массив";
@@ -215,18 +221,17 @@
// //
// textBoxCollectionName // textBoxCollectionName
// //
textBoxCollectionName.Location = new Point(3, 40); textBoxCollectionName.Location = new Point(3, 53);
textBoxCollectionName.Margin = new Padding(3, 2, 3, 2);
textBoxCollectionName.Name = "textBoxCollectionName"; textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(198, 23); textBoxCollectionName.Size = new Size(226, 27);
textBoxCollectionName.TabIndex = 1; textBoxCollectionName.TabIndex = 1;
// //
// labelCollectionName // labelCollectionName
// //
labelCollectionName.AutoSize = true; labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(11, 9); labelCollectionName.Location = new Point(13, 12);
labelCollectionName.Name = "labelCollectionName"; labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(119, 15); labelCollectionName.Size = new Size(151, 20);
labelCollectionName.TabIndex = 0; labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллеции:"; labelCollectionName.Text = "Название коллеции:";
// //
@@ -236,9 +241,10 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); 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.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(184, 23); comboBoxSelectorCompany.Size = new Size(210, 28);
comboBoxSelectorCompany.TabIndex = 0; comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged; comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged;
// //
@@ -246,18 +252,63 @@
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 0);
pictureBox.Margin = new Padding(3, 4, 3, 4);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(752, 644); pictureBox.Size = new Size(859, 859);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; 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 // FormAirPlaneCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(960, 644); ClientSize = new Size(1097, 859);
Controls.Add(menuStrip);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Margin = new Padding(3, 4, 3, 4);
Name = "FormAirPlaneCollection"; Name = "FormAirPlaneCollection";
Text = "FormAirPlaneCollection"; Text = "FormAirPlaneCollection";
Load += FormAirPlaneCollection_Load; Load += FormAirPlaneCollection_Load;
@@ -267,7 +318,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@@ -290,5 +344,11 @@
private ListBox listBoxCollection; private ListBox listBoxCollection;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -9,9 +9,11 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; 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>
@@ -22,15 +24,19 @@ namespace AirBomber
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
private AbstractCompany? _company; private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormAirPlaneCollection() public FormAirPlaneCollection(ILogger<FormAirPlaneCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@@ -67,6 +73,8 @@ namespace AirBomber
/// </summary> /// </summary>
/// <param name="airplane"></param> /// <param name="airplane"></param>
private void SetAirPlane(DrawningAirPlane airplane) private void SetAirPlane(DrawningAirPlane airplane)
{
try
{ {
if (_company == null || airplane == null) if (_company == null || airplane == null)
{ {
@@ -77,10 +85,14 @@ namespace AirBomber
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
} }
else }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("В коллекции превышено допустимое количество элементов");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -108,10 +120,13 @@ namespace AirBomber
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e) private void ButtonRemoveAirPlane_Click(object sender, EventArgs e)
{
int pos = Convert.ToInt32(maskedTextBox.Text);
try
{ {
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{ {
return; throw new Exception("Входные данные отсутствуют");
} }
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
@@ -119,15 +134,18 @@ namespace AirBomber
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Объект удален");
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не найден объект по позиции " + pos);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@@ -143,11 +161,13 @@ namespace AirBomber
return; return;
} }
DrawningAirPlane? airplane = null; DrawningAirPlane? airPlane = null;
int counter = 100; int counter = 100;
while (airplane == null) try
{ {
airplane = _company.GetRandomObject(); while (airPlane == null)
{
airPlane = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@@ -155,15 +175,20 @@ namespace AirBomber
} }
} }
if (airplane == null) if (airPlane == null)
{ {
return; return;
} }
FormAirBomber form = new FormAirBomber(); FormAirBomber form = new FormAirBomber();
form.SetAirPlane = airplane; form.SetAirPlane = airPlane;
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
@@ -192,6 +217,9 @@ namespace AirBomber
MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данный заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@@ -204,6 +232,12 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void RefreshListBoxItems() private void RefreshListBoxItems()
@@ -263,5 +297,53 @@ namespace AirBomber
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RefreshListBoxItems(); 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
{
_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);
}
}
}
/// <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="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, 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="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"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
@@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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> </root>

View File

@@ -1,5 +1,11 @@
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> /// <summary>
@@ -11,7 +17,29 @@ namespace AirBomber
// 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 FormAirPlaneCollection()); 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"
}
}
}