Compare commits
3 Commits
da415e754b
...
eac299fe2c
Author | SHA1 | Date | |
---|---|---|---|
eac299fe2c | |||
9688585e32 | |||
668d6a7a7f |
@ -9,7 +9,7 @@ public abstract class AbstractCompany
|
||||
/// <summary>
|
||||
/// Размер места (ширина)
|
||||
/// </summary>
|
||||
protected readonly int _placeSizeWidth = 210;
|
||||
protected readonly int _placeSizeWidth = 220;
|
||||
/// <summary>
|
||||
/// Размер места (высота)
|
||||
/// </summary>
|
||||
@ -22,10 +22,15 @@ public abstract class AbstractCompany
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
protected readonly int _pictureHeight;
|
||||
protected static int amountOfObjects = 0;
|
||||
/// <summary>
|
||||
/// Коллекция штурмовика
|
||||
/// </summary>
|
||||
protected ICollectionGenericObjects<DrawningStormtrooperBase>? _collection = null;
|
||||
public static int getAmountOfObjects()
|
||||
{
|
||||
return amountOfObjects;
|
||||
}
|
||||
/// <summary>
|
||||
/// Вычисление максимального количества элементов, который можно разместить в окне
|
||||
/// </summary>
|
||||
@ -84,10 +89,14 @@ public abstract class AbstractCompany
|
||||
|
||||
SetObjectsPosition();
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
DrawningStormtrooperBase? obj = _collection?.Get(i);
|
||||
obj?.DrawTransport(graphics);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectStormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -48,23 +49,18 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position>=0 && position < _collection.Count)
|
||||
{
|
||||
if (position>=Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int Insert(T obj)
|
||||
{
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
if (_collection.Count <= _maxCount)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return _collection.Count;
|
||||
}
|
||||
return -1;
|
||||
return Count;
|
||||
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -72,22 +68,17 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
if (position >= 0 && position < _maxCount && _collection.Count <= _maxCount)
|
||||
{
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
if (position < 0 || position > _maxCount)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T temp = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return temp;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectStormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -52,7 +53,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public T? Get(int position)
|
||||
{
|
||||
// проверка позиции
|
||||
if (position >= _collection.Length || position < 0) return null;
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
@ -69,7 +71,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -79,7 +81,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// ищется свободное место после этой позиции и идет вставка туда
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
if (position >= _collection.Length || position < 0) return -1;
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
@ -105,14 +107,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
}
|
||||
index--;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T? Remove(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
if(position >= _collection.Length || position < 0) return null;
|
||||
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
if (_collection[position] == null) throw new ObjectNotFoundException(position);
|
||||
T temp = _collection[position];
|
||||
_collection[position] = null;
|
||||
return temp;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectStormtrooper.Drawnings;
|
||||
using ProjectStormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -95,12 +96,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))
|
||||
{
|
||||
@ -133,30 +134,30 @@ 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 fs = File.OpenText(filename))
|
||||
{
|
||||
string str = fs.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 = "";
|
||||
@ -171,23 +172,32 @@ public class StorageCollection<T>
|
||||
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
|
||||
if (collection == null)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Не удалось создать коллекцию");
|
||||
}
|
||||
collection.MaxCount = Convert.ToInt32(record[2]);
|
||||
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
if (elem?.CreateDrawningStormtrooper() is T stormtrooper)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(stormtrooper) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Объект не удалось добавить в коллекцию" + record[3]);
|
||||
}
|
||||
}
|
||||
catch(CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -44,13 +44,17 @@ public class StormtrooperSharingService : AbstractCompany
|
||||
int curHeight = 0;
|
||||
for (int i = 0; i < (_collection?.Count ?? 0); i++)
|
||||
{
|
||||
if (_collection.Get(i) != null)
|
||||
try
|
||||
{
|
||||
|
||||
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
|
||||
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 15, curHeight * _placeSizeHeight + 3);
|
||||
|
||||
}
|
||||
catch (Exception) { }
|
||||
if (curWidth > 0)
|
||||
curWidth--;
|
||||
|
||||
else
|
||||
{
|
||||
curWidth = width - 1;
|
||||
|
@ -20,7 +20,7 @@ public class DrawingStormtrooper: DrawningStormtrooperBase
|
||||
/// <param name="rockets"></param>
|
||||
/// <param name="bombs"></param>
|
||||
|
||||
public DrawingStormtrooper(int speed,double weight, Color bodyColor,Color additionalColor, bool rockets, bool bombs):base(140,140)
|
||||
public DrawingStormtrooper(int speed,double weight, Color bodyColor,Color additionalColor, bool rockets, bool bombs):base(140,135)
|
||||
{
|
||||
EntityStormtrooperBase = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, rockets, bombs);
|
||||
|
||||
|
@ -36,7 +36,7 @@ public class DrawningStormtrooperBase
|
||||
/// Высота прорисовки
|
||||
/// </summary>
|
||||
|
||||
private readonly int _drawningStormtooperHeight = 140;
|
||||
private readonly int _drawningStormtooperHeight = 135;
|
||||
|
||||
/// <summary>
|
||||
/// Координата Х объекта
|
||||
|
@ -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 ProjectStormtrooper.Exceptions;
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal class CollectionOverflowException:ApplicationException
|
||||
{
|
||||
public CollectionOverflowException(int count): base("В коллекции превышено допустимое количество: count " + count) { }
|
||||
public CollectionOverflowException() : base() { }
|
||||
public CollectionOverflowException(string message): base(message) { }
|
||||
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
|
||||
protected CollectionOverflowException(SerializationInfo info,StreamingContext context) : base(info, context) { }
|
||||
|
||||
|
||||
}
|
21
ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs
Normal file
21
ProjectStormtrooper/Exceptions/ObjectNotFoundException.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectStormtrooper.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) { }
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectStormtrooper.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) { }
|
||||
}
|
@ -68,7 +68,7 @@
|
||||
groupBoxTools.Dock = DockStyle.Right;
|
||||
groupBoxTools.Location = new Point(911, 24);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Size = new Size(173, 604);
|
||||
groupBoxTools.Size = new Size(173, 646);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Инструменты";
|
||||
@ -248,7 +248,7 @@
|
||||
pictureBox.Dock = DockStyle.Fill;
|
||||
pictureBox.Location = new Point(0, 24);
|
||||
pictureBox.Name = "pictureBox";
|
||||
pictureBox.Size = new Size(911, 604);
|
||||
pictureBox.Size = new Size(911, 646);
|
||||
pictureBox.TabIndex = 3;
|
||||
pictureBox.TabStop = false;
|
||||
//
|
||||
@ -296,7 +296,7 @@
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1084, 628);
|
||||
ClientSize = new Size(1084, 670);
|
||||
Controls.Add(pictureBox);
|
||||
Controls.Add(groupBoxTools);
|
||||
Controls.Add(menuStrip);
|
||||
|
@ -1,5 +1,7 @@
|
||||
using ProjectStormtrooper.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectStormtrooper.CollectionGenericObjects;
|
||||
using ProjectStormtrooper.Drawnings;
|
||||
using ProjectStormtrooper.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
@ -22,16 +24,22 @@ public partial class FormStormtrooperCollection : Form
|
||||
/// </summary>
|
||||
private readonly StorageCollection<DrawningStormtrooperBase> _storageCollection;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Компания
|
||||
/// </summary>
|
||||
private AbstractCompany? _company;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormStormtrooperCollection()
|
||||
public FormStormtrooperCollection(ILogger<FormStormtrooperCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storageCollection = new();
|
||||
_logger = logger;
|
||||
_logger.LogInformation("Форма загрузилась");
|
||||
}
|
||||
|
||||
|
||||
@ -63,6 +71,8 @@ public partial class FormStormtrooperCollection : Form
|
||||
/// </summary>
|
||||
/// <param name="stormtrooper"></param>
|
||||
private void SetStormtrooper(DrawningStormtrooperBase stormtrooper)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_company == null || stormtrooper == null)
|
||||
{
|
||||
@ -72,10 +82,14 @@ public partial class FormStormtrooperCollection : Form
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Добавлен объект:" + stormtrooper.GetDataForSave);
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (ObjectNotFoundException) { }
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
@ -86,10 +100,7 @@ public partial class FormStormtrooperCollection : Form
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveStormtrooper_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_company == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
|
||||
{
|
||||
return;
|
||||
@ -99,14 +110,20 @@ public partial class FormStormtrooperCollection : Form
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBox.Text);
|
||||
int tempSize = StormtrooperSharingService.getAmountOfObjects();
|
||||
try
|
||||
{
|
||||
if (_company - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBox.Image = _company.Show();
|
||||
_logger.LogInformation("Удален объект по позиции" + pos);
|
||||
}
|
||||
else
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -122,25 +139,29 @@ public partial class FormStormtrooperCollection : Form
|
||||
}
|
||||
DrawningStormtrooperBase? stormtrooper = null;
|
||||
int counter = 100;
|
||||
try
|
||||
{
|
||||
|
||||
while (stormtrooper == null)
|
||||
{
|
||||
stormtrooper = _company.GetRandomObject();
|
||||
counter--;
|
||||
if (counter < -0)
|
||||
if (counter <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (stormtrooper == null)
|
||||
FormStormtrooper form = new();
|
||||
{
|
||||
return;
|
||||
}
|
||||
FormStormtrooper form = new()
|
||||
{
|
||||
SetStormtrooper = stormtrooper
|
||||
SetStormtrooper(stormtrooper);
|
||||
};
|
||||
form.ShowDialog();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Перерисовка коллекции
|
||||
/// </summary>
|
||||
@ -165,6 +186,8 @@ public partial class FormStormtrooperCollection : Form
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
CollectionType collectionType = CollectionType.None;
|
||||
if (radioButtonMassive.Checked)
|
||||
{
|
||||
@ -177,7 +200,12 @@ public partial class FormStormtrooperCollection : Form
|
||||
|
||||
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
|
||||
RerfreshListBoxItems();
|
||||
|
||||
_logger.LogInformation("Коллекция добавлена" + textBoxCollectionName.Text);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление коллекции
|
||||
@ -195,12 +223,21 @@ public partial class FormStormtrooperCollection : Form
|
||||
MessageBox.Show("Коллекция не выбрана");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
|
||||
RerfreshListBoxItems();
|
||||
_logger.LogInformation("Коллекция:" + listBoxCollection.SelectedItem.ToString() + "удалена");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление списка в listBoxCollection
|
||||
@ -254,16 +291,20 @@ public partial class FormStormtrooperCollection : 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("Не сохранилось", "Результат",
|
||||
MessageBox.Show(ex.Message, "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -276,17 +317,21 @@ public partial class FormStormtrooperCollection : Form
|
||||
// TODO продумать логику
|
||||
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("Загрузка не удалась", "Результат",
|
||||
MessageBox.Show(ex.Message, "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -126,4 +126,7 @@
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>261, 17</value>
|
||||
</metadata>
|
||||
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>25</value>
|
||||
</metadata>
|
||||
</root>
|
@ -1,3 +1,9 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectStormtrooper
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +17,27 @@ namespace ProjectStormtrooper
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormStormtrooperCollection());
|
||||
ServiceCollection service = new();
|
||||
ConfigureServices(service);
|
||||
using ServiceProvider serviceProvider = service.BuildServiceProvider();
|
||||
|
||||
Application.Run(serviceProvider.GetRequiredService<FormStormtrooperCollection>());
|
||||
}
|
||||
/// <summary>
|
||||
/// Êîíôèãóðàöèÿ ñåðâèñà DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
|
||||
services.AddSingleton<FormStormtrooperCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(new LoggerConfiguration()
|
||||
.WriteTo.File("log.txt")
|
||||
.CreateLogger());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,18 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +35,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="serilog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
13
ProjectStormtrooper/serilog.config
Normal file
13
ProjectStormtrooper/serilog.config
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true" internalLogLevel="Info">
|
||||
<targets>
|
||||
<target xsi:type="File" name="tofile" fileName="carlog- ${shortdate}.log" />
|
||||
</targets>
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
Loading…
Reference in New Issue
Block a user