7 лабортаорная

This commit is contained in:
Kudyaeva 2024-06-08 01:09:47 +04:00
parent 3f7b38ad18
commit 265eb071be
12 changed files with 299 additions and 174 deletions

View File

@ -41,11 +41,12 @@ public class ArtilleryBase : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++) for (int i = 0; i < (_collection?.Count ?? 0); i++)
{ {
if (_collection.Get(i) != null) try
{ {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4); _collection?.Get(i)?.SetPosition(_placeSizeWidth * curWidth + 40, curHeight * _placeSizeHeight + 4);
} }
catch (Exception) { };
if (curWidth > 0) if (curWidth > 0)
curWidth--; curWidth--;
else else

View File

@ -1,4 +1,6 @@
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
@ -38,33 +40,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции //TODO выброс ошибки если выход за границу
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO выброс ошибки если переполнение
// TODO вставка в конец набора if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) return -1;
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO выброс ошибки если переполнение
// TODO проверка позиции // TODO выброс ошибки если за границу
// TODO вставка по позиции if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count == _maxCount) return -1; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции //TODO если выброс за границу
// TODO удаление объекта из списка if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (position >= Count || position < 0) return null;
T obj = _collection[position]; T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;

View File

@ -1,4 +1,6 @@
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; using SelfPropelledArtilleryUnit.Exceptions;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -38,15 +40,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T? Get(int position) public T Get(int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) return null; // TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO вставка в свободное место набора // TODO выброс ошибки если переполнение
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@ -57,17 +61,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
++index; ++index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если переполнение
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то // TODO выброс ошибки если выход за границу
// ищется свободное место после этой позиции и идет вставка туда if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -93,14 +93,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
--index; --index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO выброс ошибки если выход за границу
// TODO удаление объекта из массива, присвоив элементу массива значение null // TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
return null; 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;

View File

@ -1,4 +1,5 @@
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.Exceptions;
using System.Text; using System.Text;
namespace SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace SelfPropelledArtilleryUnit.CollectionGenericObjects;
@ -14,21 +15,6 @@ 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>
@ -79,15 +65,26 @@ public class StorageCollection<T>
} }
} }
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по автомобилям в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> public void SaveData(string filename)
public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -98,19 +95,18 @@ public class StorageCollection<T>
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); writer.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); writer.Write(value.Key);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); writer.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -118,47 +114,39 @@ public class StorageCollection<T>
{ {
continue; continue;
} }
sb.Append(data); writer.Write(data);
sb.Append(_separatorItems); writer.Write(_separatorItems);
} }
writer.Write(sb);
} }
} }
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
//по идее этого произойти не должно
//if (strs == null)
//{
// return false;
//}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
@ -168,23 +156,30 @@ 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]);
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?.CreateDrawningPropelledArtillery() is T ship) if (elem?.CreateDrawningPropelledArtillery() is T PropelledArtillery)
{ {
if (collection.Insert(ship) == -1) try
{ {
return false; if (collection.Insert(PropelledArtillery) == -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;
} }
} }

View File

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

@ -85,17 +85,7 @@
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 213); panelCompanyTools.Size = new Size(200, 213);
panelCompanyTools.TabIndex = 9; panelCompanyTools.TabIndex = 9;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(0, 95);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(188, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
maskedTextBox.MaskInputRejected += maskedTextBox_MaskInputRejected;
// //
// buttonAddPropelledArtillery // buttonAddPropelledArtillery
// //

View File

@ -1,14 +1,8 @@
 using SelfPropelledArtilleryUnit.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using SelfPropelledArtilleryUnit.CollectionGenericObjects;
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using System; using SelfPropelledArtilleryUnit.Exceptions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SelfPropelledArtilleryUnit; namespace SelfPropelledArtilleryUnit;
@ -24,13 +18,20 @@ public partial class FormPropelledArtilleryCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormPropelledArtilleryCollection() public FormPropelledArtilleryCollection(ILogger<FormPropelledArtilleryCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
@ -46,53 +47,39 @@ public partial class FormPropelledArtilleryCollection : Form
private void buttonAddPropelledArtillery_Click(object sender, EventArgs e) private void buttonAddPropelledArtillery_Click(object sender, EventArgs e)
{ {
if (_company == null)
{
return;
}
FormPropelledArtilleryConfig form = new(); FormPropelledArtilleryConfig form = new();
form.PropelledArtilleryDelegate += SetCar; // TODO передать метод
form.Show(); form.Show();
} form.AddEvent(SetPropelledArtillery);
/// <summary>
/// Добавление
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddSelfPropelledArtilleryUnit_Click(object sender, EventArgs e)
{
} }
/// <summary> /// <summary>
/// Создание объекта класса-перемещения /// Создание объекта класса-перемещения
/// </summary> /// </summary>
/// <param name="type">Тип создаваемого объекта</param> /// <param name="type">Тип создаваемого объекта</param>
private void SetCar(DrawningPropelledArtillery propelledArtilleryk) private void SetPropelledArtillery(DrawningPropelledArtillery propelledArtillery)
{ {
try
if (_company == null || propelledArtilleryk == null)
{ {
return; if (_company == null || propelledArtillery == null)
{
return;
}
if (_company + propelledArtillery != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + propelledArtillery.GetDataForSave());
}
} }
if (_company + propelledArtilleryk != -1) catch (ObjectNotFoundException) { }
{ catch (CollectionOverflowException ex)
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
private void maskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
/// <summary> /// <summary>
/// Удаление объекта /// Удаление объекта
/// </summary> /// </summary>
@ -109,14 +96,19 @@ public partial class FormPropelledArtilleryCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -134,26 +126,27 @@ public partial class FormPropelledArtilleryCollection : Form
DrawningPropelledArtillery? propelledartillery = null; DrawningPropelledArtillery? propelledartillery = null;
int counter = 100; int counter = 100;
while (propelledartillery == null) try
{ {
propelledartillery = _company.GetRandomObject(); while (propelledartillery == null)
counter--;
if (counter <= 0)
{ {
break; propelledartillery = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
} }
SelfPropelledArtilleryUnit form = new()
{
SetPropelledArtillery = propelledartillery
};
form.ShowDialog();
} }
catch (Exception ex)
if (propelledartillery == null)
{ {
return; MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
SelfPropelledArtilleryUnit form = new()
{
SetPropelledArtillery = propelledartillery
};
form.ShowDialog();
} }
/// <summary> /// <summary>
@ -178,17 +171,25 @@ public partial class FormPropelledArtilleryCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None; try
if (radioButtonMassive.Checked)
{ {
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();
} }
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
@ -213,12 +214,20 @@ public partial class FormPropelledArtilleryCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) try
{ {
return; if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
} }
private void buttonCreateCompany_Click(object sender, EventArgs e) private void buttonCreateCompany_Click(object sender, EventArgs e)
@ -249,13 +258,16 @@ public partial class FormPropelledArtilleryCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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);
} }
} }
} }
@ -264,16 +276,17 @@ public partial class FormPropelledArtilleryCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storageCollection.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,4 +1,27 @@
namespace SelfPropelledArtilleryUnit //namespace SelfPropelledArtilleryUnit
//{
// internal static class Program
// {
// /// <summary>
// /// The main entry point for the application.
// /// </summary>
// [STAThread]
// static void Main()
// {
// // To customize application configuration such as set high DPI settings or default font,
// // see https://aka.ms/applicationconfiguration.
// ApplicationConfiguration.Initialize();
// Application.Run(new FormPropelledArtilleryCollection());
// }
// }
//}
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using SelfPropelledArtilleryUnit;
using Microsoft.Extensions.Configuration;
namespace ProjectWarmlyShip
{ {
internal static class Program internal static class Program
{ {
@ -11,7 +34,31 @@ namespace SelfPropelledArtilleryUnit
// 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 FormPropelledArtilleryCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormPropelledArtilleryCollection>());
}
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<FormPropelledArtilleryCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile($"{pathNeed}serilog.json")
.Build())
.CreateLogger());
});
} }
} }
} }

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<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>
@ -23,4 +34,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

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