This commit is contained in:
Ilya Ryabov 2024-05-12 11:47:20 +04:00
parent 274f3b8dc3
commit 79d55471b8
12 changed files with 257 additions and 112 deletions

View File

@ -98,8 +98,12 @@ public abstract class AbstractCompany
SetObjectsPosition(); SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i) for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{ {
DrawningBaseStormtrooper? obj = _collection?.Get(i); try
obj?.DrawTransport(graphics); {
DrawningBaseStormtrooper? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (Exception) { }
} }
return bitmap; return bitmap;
} }

View File

@ -1,4 +1,6 @@
namespace ProjectStormtrooper.CollectionGenericObjects; using ProjectStormtrooper.Exceptions;
namespace ProjectStormtrooper.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -41,47 +43,34 @@ where T : class
} }
public T? Get(int position) public T? Get(int position)
{ {
// TODO проверка позиции //TODO выброс ошибки если выход за границу
if( position>= 0 && position < Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{ return _collection[position];
return _collection[position];
}
return null;
} }
public int Insert(T obj) public int Insert(T obj)
{ {
// TODO проверка, что не превышено максимальное количество элементов // TODO выброс ошибки если переполнение
// TODO вставка в конец набора if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (Count <= _maxCount) _collection.Add(obj);
{ return Count;
_collection.Add(obj);
return Count;
}
return -1;
} }
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 && position>=0 && position < _maxCount) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{ _collection.Insert(position, obj);
_collection.Insert(position, obj); return position;
return position;
}
return -1;
} }
public T Remove(int position) public T Remove(int position)
{ {
// TODO проверка позиции // TODO если выброс за границу
// TODO удаление объекта из списка if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T temp = _collection[position]; T obj = _collection[position];
if(position>=0 && position < _maxCount) _collection.RemoveAt(position);
{ return obj;
_collection.RemoveAt(position);
return temp;
}
return null;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectStormtrooper.Drawnings; using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.Exceptions;
namespace ProjectStormtrooper.CollectionGenericObjects; namespace ProjectStormtrooper.CollectionGenericObjects;
@ -49,14 +50,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<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)
{ {
@ -67,17 +70,14 @@ 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;
@ -103,14 +103,15 @@ 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) return null; if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T temp = _collection[position]; T temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return temp;

View File

@ -1,4 +1,5 @@
using ProjectStormtrooper.Drawnings; using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.Exceptions;
using System.Text; using System.Text;
namespace ProjectStormtrooper.CollectionGenericObjects; namespace ProjectStormtrooper.CollectionGenericObjects;
@ -90,11 +91,11 @@ where T : DrawningBaseStormtrooper
/// </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))
{ {
@ -127,7 +128,6 @@ where T : DrawningBaseStormtrooper
writer.Write(_separatorItems); writer.Write(_separatorItems);
} }
} }
return true;
} }
} }
/// <summary> /// <summary>
@ -135,22 +135,22 @@ where T : DrawningBaseStormtrooper
/// </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 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 = "";
@ -165,7 +165,7 @@ where T : DrawningBaseStormtrooper
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);
@ -173,15 +173,21 @@ where T : DrawningBaseStormtrooper
{ {
if (elem?.CreateDrawningStormtrooper() is T stormtrooper) if (elem?.CreateDrawningStormtrooper() is T stormtrooper)
{ {
if (collection.Insert(stormtrooper) == -1) try
{ {
return false; if (collection.Insert(stormtrooper) == -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

@ -37,11 +37,12 @@ public class StormtrooperSharingService : AbstractCompany
int curHeight = 0; int curHeight = 0;
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 + 15, curHeight * _placeSizeHeight + 3); _collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 15, curHeight * _placeSizeHeight + 3);
} }
catch (Exception) { }
if (curWidth >0) if (curWidth >0)
curWidth--; curWidth--;
else else

View File

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

View File

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

View File

@ -1,5 +1,7 @@
using ProjectStormtrooper.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectStormtrooper.CollectionGenericObjects;
using ProjectStormtrooper.Drawnings; using ProjectStormtrooper.Drawnings;
using ProjectStormtrooper.Exceptions;
namespace ProjectStormtrooper; namespace ProjectStormtrooper;
/// <summary> /// <summary>
@ -16,13 +18,16 @@ public partial class FormStormtrooperCollection : Form
/// Компания /// Компания
/// </summary> /// </summary>
private AbstractCompany? _company; private AbstractCompany? _company;
private readonly ILogger _logger;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormStormtrooperCollection() public FormStormtrooperCollection(ILogger<FormStormtrooperCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@ -39,21 +44,29 @@ public partial class FormStormtrooperCollection : Form
/// <param name="stormtrooper"></param> /// <param name="stormtrooper"></param>
private void SetStormtrooper(DrawningBaseStormtrooper stormtrooper) private void SetStormtrooper(DrawningBaseStormtrooper stormtrooper)
{ {
if (_company == null || stormtrooper == null) try
{ {
return; if (_company == null || stormtrooper == null)
{
return;
}
if (_company + stormtrooper != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + stormtrooper.GetDataForSave());
}
} }
if (_company + stormtrooper != -1) catch (ObjectNotFoundException) { }
{ catch (CollectionOverflowException ex)
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
/// Добавление бомбардировщика /// Добавление бомбардировщика
/// </summary> /// </summary>
@ -85,15 +98,21 @@ public partial class FormStormtrooperCollection : Form
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
int tempSize = StormtrooperSharingService.getAmountOfObjects(); int tempSize = StormtrooperSharingService.getAmountOfObjects();
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);
} }
} }
/// <summary> /// <summary>
@ -109,25 +128,28 @@ public partial class FormStormtrooperCollection : Form
} }
DrawningBaseStormtrooper? stormtrooper = null; DrawningBaseStormtrooper? stormtrooper = null;
int counter = 100; int counter = 100;
while (stormtrooper == null) try
{ {
stormtrooper = _company.GetRandomObject();
counter--;
if (counter < -0)
{
break;
}
}
if (stormtrooper == null)
{
return;
}
FormStormtrooper form = new()
{
SetStormtrooper = stormtrooper
};
form.ShowDialog();
while (stormtrooper == null)
{
stormtrooper = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
FormStormtrooper form = new();
{
SetStormtrooper(stormtrooper);
};
form.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
@ -157,18 +179,25 @@ public partial class FormStormtrooperCollection : 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();
} }
/// <summary> /// <summary>
@ -187,12 +216,20 @@ public partial class FormStormtrooperCollection : 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();
} }
/// <summary> /// <summary>
@ -247,15 +284,17 @@ public partial class FormStormtrooperCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -269,16 +308,19 @@ public partial class FormStormtrooperCollection : Form
//TODO продумать логику //TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", 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,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectStormtrooper namespace ProjectStormtrooper
{ {
internal static class Program internal static class Program
@ -11,7 +16,30 @@ namespace ProjectStormtrooper
// 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 FormStormtrooperCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormStormtrooperCollection>());
}
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<FormStormtrooperCollection>()
.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="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.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="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.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

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