5 Commits
Lab06 ... 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
13 changed files with 423 additions and 269 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>
/// Конструктор /// Конструктор
@@ -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>
@@ -101,8 +101,13 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningAirPlane? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningAirPlane? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
} }
return bitmap; return bitmap;
@@ -118,4 +123,4 @@ public abstract class AbstractCompany
/// Расстановка объектов /// Расстановка объектов
/// </summary> /// </summary>
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
} }

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)
@@ -60,8 +63,12 @@ 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--)
{ {
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); try
_collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); {
_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) if (col == 1)
{ {
col = numCols + 1; col = numCols + 1;

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;
@@ -40,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;
@@ -71,7 +66,7 @@ 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;
@@ -84,4 +79,4 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[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;
@@ -49,12 +50,9 @@ 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)
@@ -67,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)
{ {
@@ -99,15 +97,16 @@ 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;
@@ -120,4 +119,4 @@ where T : class
yield return _collection[i]; yield return _collection[i];
} }
} }
} }

View File

@@ -1,4 +1,5 @@
using AirBomber.Drawnings; using AirBomber.Drawnings;
using AirBomber.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -105,11 +106,11 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@@ -145,7 +146,6 @@ public class StorageCollection<T>
sb.Clear(); sb.Clear();
} }
} }
return true;
} }
/// <summary> /// <summary>
@@ -153,19 +153,21 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader sr = new StreamReader(filename))
{ {
string? str; string? str;
str = sr.ReadLine(); str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString()) if (str != _collectionKey.ToString())
return false; throw new Exception("В файле неверные данные");
_storages.Clear(); _storages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
{ {
@@ -178,7 +180,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@@ -186,17 +188,22 @@ public class StorageCollection<T>
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningAirPlane() is T boat) if (elem?.CreateDrawningAirPlane() is T airplane)
{ {
if (collection.Insert(boat) == -1) try
return false; {
if (collection.Insert(airplane) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
/// <summary> /// <summary>

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

@@ -275,7 +275,6 @@
файлToolStripMenuItem.Name = айлToolStripMenuItem"; файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24); файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл"; файлToolStripMenuItem.Text = "Файл";
файлToolStripMenuItem.Click += saveToolStripMenuItem_Click;
// //
// saveToolStripMenuItem // saveToolStripMenuItem
// //

View File

@@ -9,64 +9,72 @@ 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>
private readonly StorageCollection<DrawningAirPlane> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirPlaneCollection(ILogger<FormAirPlaneCollection> logger)
{ {
/// <summary> InitializeComponent();
/// Хранилище коллекций _storageCollection = new();
/// </summary> _logger = logger;
private readonly StorageCollection<DrawningAirPlane> _storageCollection; _logger.LogInformation("Форма загрузилась");
}
/// <summary> /// <summary>
/// Компания /// Выбор компании
/// </summary> /// </summary>
private AbstractCompany? _company; /// <param name="sender"></param>
/// <param name="e"></param>
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary> /// <summary>
/// Конструктор /// Создание объекта класса-перемещения
/// </summary> /// </summary>
public FormAirPlaneCollection() /// <param name="type">Тип создаваемого объекта</param>
{
InitializeComponent();
_storageCollection = new();
}
/// <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>
/// Добавление самолета /// Добавление самолета
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private void buttonAddAirPlane_Click(object sender, EventArgs e) private void buttonAddAirPlane_Click(object sender, EventArgs e)
{ {
FormAirPlaneConfig form = new(); FormAirPlaneConfig form = new();
//TODO передать метод //TODO передать метод
form.Show(); form.Show();
form.AddEvent(SetAirPlane); form.AddEvent(SetAirPlane);
} }
/// <summary> /// <summary>
/// Добавление самолета в коллекцию /// Добавление самолета в коллекцию
/// </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,41 +85,48 @@ namespace AirBomber
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + airplane.GetDataForSave());
} }
else
{
MessageBox.Show("Не удалось добавить объект");
}
} }
catch (ObjectNotFoundException) { }
/// <summary> catch (CollectionOverflowException ex)
/// Получение цвета
/// </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)); MessageBox.Show("В коллекции превышено допустимое количество элементов");
ColorDialog dialog = new(); _logger.LogError("Ошибка: {Message}", ex.Message);
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
return color;
} }
/// <summary> }
/// Удаление объекта
/// </summary> /// <summary>
/// <param name="sender"></param> /// Получение цвета
/// <param name="e"></param> /// </summary>
private void ButtonRemoveAirPlane_Click(object sender, EventArgs e) /// <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) 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,35 +134,40 @@ 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
{
MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (Exception ex)
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{ {
if (_company == null) MessageBox.Show("Не найден объект по позиции " + pos);
{ _logger.LogError("Ошибка: {Message}", ex.Message);
return; }
} }
DrawningAirPlane? airplane = null; /// <summary>
int counter = 100; /// Передача объекта в другую форму
while (airplane == null) /// </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--; counter--;
if (counter <= 0) if (counter <= 0)
{ {
@@ -155,43 +175,51 @@ 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)
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{ {
if (_company == null) MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
return; }
}
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; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@@ -204,104 +232,117 @@ namespace AirBomber
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems(); RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция:", textBoxCollectionName.Text);
} }
catch (Exception ex)
private void RefreshListBoxItems()
{ {
listBoxCollection.Items.Clear(); _logger.LogError("Ошибка: {Message}", ex.Message);
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) }
}
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]; listBoxCollection.Items.Add(colName);
if (!string.IsNullOrEmpty(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;
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
} }
/// <summary> if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateCompany_Click(object sender, EventArgs e)
{ {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) return;
{ }
MessageBox.Show("Коллекция не выбрана"); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
return; RefreshListBoxItems();
} }
/// <summary>
ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; /// Создание компании
if (collection == null) /// </summary>
{ /// <param name="sender"></param>
MessageBox.Show("Коллекция не проинициализирована"); /// <param name="e"></param>
return; private void buttonCreateCompany_Click(object sender, EventArgs e)
} {
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
switch (comboBoxSelectorCompany.Text) {
{ MessageBox.Show("Коллекция не выбрана");
case "Хранилище": return;
_company = new AirPlaneSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
} }
/// <summary> ICollectionGenericObjects<DrawningAirPlane>? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
/// Обработка нажатия "Сохранение" if (collection == null)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) MessageBox.Show("Коллекция не проинициализирована");
{ return;
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
/// <summary> switch (comboBoxSelectorCompany.Text)
/// Обработка кнопки загрузки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) 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
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) _storageCollection.SaveData(saveFileDialog.FileName);
{ MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems(); _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); }
} catch (Exception ex)
else {
{ MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Загрузка не выполнена", "Результат", 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

@@ -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> // To customize application configuration such as set high DPI settings or default font,
/// The main entry point for the application. // see https://aka.ms/applicationconfiguration.
/// </summary> ApplicationConfiguration.Initialize();
[STAThread] ServiceCollection services = new();
static void Main() ConfigureServices(services);
{ using ServiceProvider serviceProvider = services.BuildServiceProvider();
// To customize application configuration such as set high DPI settings or default font, Application.Run(serviceProvider.GetRequiredService<FormAirPlaneCollection>());
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new 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"
}
}
}