7 лабораторная работа
This commit is contained in:
parent
b4c1796f23
commit
eb2c515645
BIN
ProjectAirBomber.zip
Normal file
BIN
ProjectAirBomber.zip
Normal file
Binary file not shown.
@ -1,4 +1,5 @@
|
||||
using ProjectAirBomber.Drawnings;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -39,10 +40,11 @@ public abstract class AbstractCompany
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningBomber>? _collection = null;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
|
||||
private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
@ -102,8 +104,12 @@ public abstract class AbstractCompany
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
DrawningBomber? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
try
|
||||
{
|
||||
DrawningBomber? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -39,33 +40,35 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) 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 - 1;
|
||||
return Count;
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T? obj, int position)
|
||||
{
|
||||
if (Count == _maxCount) return -1;
|
||||
if (position < 0 || position >= Count) return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count) return null;
|
||||
T? obj = _collection[position];
|
||||
if (position >= _collection.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 < Count; ++i)
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -57,17 +58,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
@ -76,55 +74,57 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
public int Insert(T obj, int position)
|
||||
{
|
||||
if (position < 0 || position > Count)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T? obj, int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
|
||||
for (int i = position + 1; i < Count; i++)
|
||||
int emptyPosition = position + 1;
|
||||
while (emptyPosition < _collection.Length)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
if (_collection[emptyPosition] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
_collection[emptyPosition] = obj;
|
||||
return emptyPosition;
|
||||
}
|
||||
++emptyPosition;
|
||||
}
|
||||
|
||||
for (int i = position - 1; i >= 0; i--)
|
||||
emptyPosition = position - 1;
|
||||
while (emptyPosition >= 0)
|
||||
{
|
||||
if (_collection[i] == null)
|
||||
if (_collection[emptyPosition] == null)
|
||||
{
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
_collection[emptyPosition] = obj;
|
||||
return emptyPosition;
|
||||
}
|
||||
--emptyPosition;
|
||||
}
|
||||
|
||||
return -1;
|
||||
throw new CollectionOverflowException(_collection.Length);
|
||||
}
|
||||
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
if (position < 0 || position > Count || _collection[position] == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
|
||||
|
||||
T? obj = _collection[position];
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
return temp;
|
||||
}
|
||||
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
{
|
||||
for (int i = 0; i < _collection.Length; ++i)
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirBomber.Drawnings;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -99,12 +100,12 @@ public class StorageCollection<T>
|
||||
/// Сохранение информации по бомбардировщикам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (_storages.Count == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
|
||||
if (File.Exists(filename))
|
||||
@ -142,31 +143,28 @@ public class StorageCollection<T>
|
||||
writer.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка информации по бомбардировщикам в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Файл не существует");
|
||||
}
|
||||
|
||||
using StreamReader reader = File.OpenText(filename);
|
||||
string? str = reader.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
string? strs = "";
|
||||
@ -184,7 +182,7 @@ public class StorageCollection<T>
|
||||
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
@ -193,24 +191,29 @@ public class StorageCollection<T>
|
||||
{
|
||||
if (elem?.CreateDrawningBomber() is T bomber)
|
||||
{
|
||||
if (collection.Insert(bomber) == -1)
|
||||
try
|
||||
{
|
||||
return false;
|
||||
if (collection.Insert(bomber) == -1)
|
||||
{
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
/// <summary>
|
||||
/// Создание коллекции по типу
|
||||
/// </summary>
|
||||
/// <param name="collectionType"></param>
|
||||
/// <returns></returns>
|
||||
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
|
||||
{
|
||||
return collectionType switch
|
||||
{
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirBomber.Drawnings;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -34,33 +35,37 @@ public class WarPlaneService : AbstractCompany
|
||||
|
||||
protected override void SetObjectsPosition()
|
||||
{
|
||||
if (_collection == null) return;
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < _collection.Count; i++)
|
||||
{
|
||||
DrawningBomber? _bomber = _collection.Get(i);
|
||||
if (_bomber != null)
|
||||
if (_collection == null) return;
|
||||
int width = _pictureWidth / _placeSizeWidth;
|
||||
int height = _pictureHeight / _placeSizeHeight;
|
||||
|
||||
int curWidth = width - 1;
|
||||
int curHeight = 0;
|
||||
|
||||
for (int i = 0; i < _collection.Count; i++)
|
||||
{
|
||||
if (_bomber.SetPictureSize(_pictureWidth, _pictureHeight))
|
||||
try
|
||||
{
|
||||
_bomber.SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 15);
|
||||
DrawningBomber? _bomber = _collection.Get(i);
|
||||
if (_bomber.SetPictureSize(_pictureWidth, _pictureHeight))
|
||||
{
|
||||
_bomber.SetPosition(_placeSizeWidth * curWidth + 20, curHeight * _placeSizeHeight + 15);
|
||||
}
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
curWidth--;
|
||||
if (curWidth < 0)
|
||||
{
|
||||
curHeight++;
|
||||
curWidth = width - 1;
|
||||
}
|
||||
if (curHeight >= height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
curWidth--;
|
||||
if (curWidth < 0)
|
||||
{
|
||||
curHeight++;
|
||||
curWidth = width - 1;
|
||||
}
|
||||
if (curHeight >= height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirBomber.Exceptions;
|
||||
|
||||
[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) { }
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirBomber.Exceptions;
|
||||
|
||||
[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) { }
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirBomber.Exceptions;
|
||||
|
||||
[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) { }
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
using ProjectAirBomber.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAirBomber.CollectionGenericObjects;
|
||||
using ProjectAirBomber.Drawnings;
|
||||
using ProjectAirBomber.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@ -27,13 +29,20 @@ public partial class FormBomberCollection : Form
|
||||
/// </summary>
|
||||
private AbstractCompany? _company = null;
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// конструктор
|
||||
/// </summary>
|
||||
public FormBomberCollection()
|
||||
public FormBomberCollection(ILogger<FormBomberCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -121,14 +130,23 @@ public partial class FormBomberCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
if (_company + bomber != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox1.Image = _company.Show();
|
||||
if (_company + bomber != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox1.Image = _company.Show();
|
||||
_logger.LogInformation("Объект добавлен");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show("Коллекция переполнена");
|
||||
_logger.LogError("Ошибка: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -144,21 +162,25 @@ public partial class FormBomberCollection : Form
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (MessageBox.Show("Удалить объект", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
if (_company - pos != null)
|
||||
try
|
||||
{
|
||||
var res = _company - pos;
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation($"Объект удален под индексом {pos}");
|
||||
pictureBox1.Image = _company.Show();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message, "Не удалось удалить объект",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@ -177,34 +199,40 @@ public partial class FormBomberCollection : Form
|
||||
DrawningBomber? bomber = null;
|
||||
int counter = 100;
|
||||
|
||||
while (bomber == null)
|
||||
try
|
||||
{
|
||||
bomber = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
while (bomber == null)
|
||||
{
|
||||
break;
|
||||
bomber = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (bomber == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormAirBomber form = new()
|
||||
{
|
||||
SetBomber = bomber
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
if (bomber == null)
|
||||
{
|
||||
return;
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
FormAirBomber form = new()
|
||||
{
|
||||
SetBomber = bomber
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
@ -224,30 +252,38 @@ public partial class FormBomberCollection : Form
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
try
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
collectionType = CollectionType.Massive;
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
}
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
|
||||
}
|
||||
else if (radioButtonList.Checked)
|
||||
catch (Exception ex)
|
||||
{
|
||||
collectionType = CollectionType.List;
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonCollectionDel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
|
||||
{
|
||||
@ -322,13 +358,16 @@ public partial class FormBomberCollection : Form
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -342,14 +381,18 @@ public partial class FormBomberCollection : Form
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAirBomber
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,36 @@ namespace ProjectAirBomber
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBomberCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBomberCollection>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBomberCollection>().AddLogging(option =>
|
||||
{
|
||||
string[] path = Directory.GetCurrentDirectory().Split('\\');
|
||||
string pathNeed = "";
|
||||
for (int i = 0; i < path.Length - 3; i++)
|
||||
{
|
||||
pathNeed += path[i] + "\\";
|
||||
}
|
||||
|
||||
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile(path: $"{pathNeed}serilog.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,21 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog" Version="5.3.2" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.LoggerConfiguration.ConditionExtensions" Version="1.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
20
ProjectAirBomber/ProjectAirBomber/serilog.json
Normal file
20
ProjectAirBomber/ProjectAirBomber/serilog.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "AirBomber\""
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user