This commit is contained in:
KirillFilippow 2023-12-22 13:47:31 +04:00
parent 3e6e60a533
commit 4d7de3bca3
12 changed files with 206 additions and 91 deletions

View File

@ -67,7 +67,7 @@ namespace ProjectContainerShip.Generics
{ {
return -1; return -1;
} }
return collect?._collection.Insert(obj); return collect?._collection.Insert(obj) ?? -1;
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -75,15 +75,15 @@ namespace ProjectContainerShip.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="pos"></param> /// <param name="pos"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(ContainerGenericCollection<T, U> collect, int public static T operator -(ContainerGenericCollection<T, U> collect, int
pos) pos)
{ {
T? obj = collect._collection[pos]; T obj = collect._collection[pos];
if (obj != null) if (obj != null)
{ {
return collect._collection.Remove(pos); collect?._collection.Remove(pos);
} }
return false; return obj;
} }
/// <summary> /// <summary>
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject

View File

@ -1,4 +1,5 @@
using ProjectContainerShip.DrawningObjects; using ContainerShip.Exceptions;
using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.Generics; using ProjectContainerShip.Generics;
using ProjectContainerShip.MovementStrategy; using ProjectContainerShip.MovementStrategy;
using System; using System;
@ -99,15 +100,14 @@ namespace ProjectContainerShip
/// </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 (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, foreach (KeyValuePair<string, ContainerGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
ContainerGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShip) foreach (DrawningShip? elem in record.Value.GetShip)
@ -118,13 +118,12 @@ namespace ProjectContainerShip
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.WriteLine("shipStorages"); writer.Write($"shipStorage{Environment.NewLine}{data}");
writer.Write(data.ToString());
return true;
} }
} }
/// <summary> /// <summary>
@ -132,22 +131,22 @@ namespace ProjectContainerShip
/// </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 reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
{ {
string cheker = reader.ReadLine(); string cheker = reader.ReadLine();
if (cheker == null) if (cheker == null)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (!cheker.StartsWith("shipStorages")) if (!cheker.StartsWith("shipStorage"))
{ {
return false; throw new Exception("Неверный формат ввода");
} }
_shipStorages.Clear(); _shipStorages.Clear();
string strs; string strs;
@ -156,11 +155,11 @@ namespace ProjectContainerShip
{ {
if (strs == null && firstinit) if (strs == null && firstinit)
{ {
return false; throw new Exception("Нет данных для загрузки");
} }
if (strs == null) if (strs == null)
{ {
return false; break;
} }
firstinit = false; firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0]; string name = strs.Split(_separatorForKeyValue)[0];
@ -171,16 +170,19 @@ namespace ProjectContainerShip
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight); data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null) if (ship != null)
{ {
int? result = collection + ship; try { _ = collection + ship; }
if (result == null || result.Value == -1) catch (ContainerShipNotFoundException e)
{ {
return false; throw e;
}
catch (StorageOverflowException e)
{
throw e;
} }
} }
} }
_shipStorages.Add(name, collection); _shipStorages.Add(name, collection);
} }
return true;
} }
} }
} }

View File

@ -27,4 +27,14 @@
<Folder Include="Resources\" /> <Folder Include="Resources\" />
</ItemGroup> </ItemGroup>
<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" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
[Serializable] internal class ContainerShipNotFoundException : ApplicationException
{
public ContainerShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public ContainerShipNotFoundException() : base() { }
public ContainerShipNotFoundException(string message) : base(message) { }
public ContainerShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ContainerShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -22,7 +22,7 @@ namespace ProjectContainerShip.Entities
/// </summary> /// </summary>
public bool Container { get; private set; } public bool Container { get; private set; }
/// <summary> /// <summary>
/// Инициализация полей объекта-класса контейнеровоза /// Инициализация полей объекта-класса контейнеровоз
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес </param> /// <param name="weight">Вес </param>

View File

@ -2,6 +2,7 @@
using ProjectContainerShip.DrawningObjects; using ProjectContainerShip.DrawningObjects;
using ProjectContainerShip.Generics; using ProjectContainerShip.Generics;
using ProjectContainerShip.MovementStrategy; using ProjectContainerShip.MovementStrategy;
using Microsoft.Extensions.Logging;
namespace ProjectContainerShip namespace ProjectContainerShip
{ {
@ -15,12 +16,17 @@ namespace ProjectContainerShip
/// </summary> /// </summary>
private readonly ContainerGenericStorage _storage; private readonly ContainerGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormContainerCollection() public FormContainerCollection(ILogger<FormContainerCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new ContainerGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new ContainerGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -42,13 +48,6 @@ namespace ProjectContainerShip
index < listBoxStorages.Items.Count) index < listBoxStorages.Items.Count)
{ {
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowContainer();
} }
} }
/// <summary> /// <summary>
@ -62,10 +61,12 @@ namespace ProjectContainerShip
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
@ -87,14 +88,16 @@ namespace ProjectContainerShip
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление невыбранного набора");
return; return;
} }
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
/// <summary> /// <summary>
@ -111,21 +114,23 @@ namespace ProjectContainerShip
var form = new FormContainerConfig(); var form = new FormContainerConfig();
form.AddEvent(ship => form.AddEvent(ship =>
{ {
if (listBoxStorages.SelectedIndex != -1) var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{ {
var obj = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]; _logger.LogWarning("Добавление пустого объекта");
if (obj != null) return;
{ }
if (obj + ship != 1) try
{ {
MessageBox.Show("Объект добавлен"); _ = obj + ship;
pictureBoxCollection.Image = obj.ShowContainer(); MessageBox.Show("Объект добавлен");
} pictureBoxCollection.Image = obj.ShowContainer();
else _logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
{ }
MessageBox.Show("Не удалось добавить объект"); catch (Exception ex)
} {
} MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
}); });
form.Show(); form.Show();
@ -139,6 +144,7 @@ namespace ProjectContainerShip
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning("Удаление объекта из несуществующего набора");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@ -157,10 +163,11 @@ namespace ProjectContainerShip
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowContainer(); pictureBoxCollection.Image = obj.ShowContainer();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект"); _logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
} }
/// <summary> /// <summary>
@ -191,15 +198,16 @@ namespace ProjectContainerShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }
@ -212,27 +220,17 @@ namespace ProjectContainerShip
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storage.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects(); ReloadObjects();
if (listBoxStorages.SelectedIndex == -1) MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
{ _logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowContainer();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось загрузить наборы с ошибкой: {ex.Message}");
} }
} }
} }

View File

@ -172,7 +172,6 @@
Margin = new Padding(3, 4, 3, 4); Margin = new Padding(3, 4, 3, 4);
Name = "FormContainerShip"; Name = "FormContainerShip";
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
Load += FormContainerShip_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxContainerShip).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();

View File

@ -13,7 +13,6 @@ namespace ProjectContainerShip
/// Ďîëĺ-îáúĺęň äë˙ ďđîđčńîâęč îáúĺęňŕ /// Ďîëĺ-îáúĺęň äë˙ ďđîđčńîâęč îáúĺęňŕ
/// </summary> /// </summary>
private DrawningShip? _drawingContainerShip; private DrawningShip? _drawingContainerShip;
/// <summary> /// <summary>
/// Ńňđŕňĺăč˙ ďĺđĺěĺůĺíč˙ /// Ńňđŕňĺăč˙ ďĺđĺěĺůĺíč˙
/// </summary> /// </summary>
@ -71,12 +70,14 @@ namespace ProjectContainerShip
{ {
Random random = new(); Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO выбор основного цвета
ColorDialog dialog = new(); ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK) if (dialog.ShowDialog() == DialogResult.OK)
{ {
color = dialog.Color; color = dialog.Color;
} }
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO выбор дополнительного цвета
ColorDialog dialog2 = new(); ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK) if (dialog2.ShowDialog() == DialogResult.OK)
{ {
@ -161,9 +162,5 @@ namespace ProjectContainerShip
SelectedShip = _drawingContainerShip; SelectedShip = _drawingContainerShip;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
private void FormContainerShip_Load(object sender, EventArgs e)
{
}
} }
} }

View File

@ -1,5 +1,10 @@
using ProjectContainerShip; using ProjectContainerShip;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectContainerShip namespace ProjectContainerShip
{ {
internal static class Program internal static class Program
@ -13,7 +18,28 @@ namespace ProjectContainerShip
// 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 FormContainerCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormContainerCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormContainerCollection>().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}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using ContainerShip.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -41,16 +42,39 @@ namespace ProjectContainerShip.Generics
/// <returns></returns> /// <returns></returns>
public int Insert(T ship) public int Insert(T ship)
{ {
return Insert(ship, 0); if (_places.Count == 0)
{
_places.Add(ship);
return 0;
}
else
{
if (_places.Count < _maxCount)
{
_places.Add(ship);
for (int i = 0; i < _places.Count; i++)
{
T temp = _places[i];
_places[i] = _places[_places.Count - 1];
_places[_places.Count - 1] = temp;
}
return 0;
}
else
{
throw new StorageOverflowException(_places.Count);
}
}
} }
public int Insert(T ship, int position) public bool Insert(T ship, int position)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
return -1; throw new ContainerShipNotFoundException(position);
if (Count >= _maxCount) if (Count >= _maxCount)
return -1; throw new StorageOverflowException(position);
_places.Insert(position, ship); _places.Insert(0, ship);
return position; return true;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@ -59,11 +83,13 @@ namespace ProjectContainerShip.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= _places.Count) if (position < 0 || position > _maxCount || position >= Count)
throw new ContainerShipNotFoundException();
if (_places[position] == null)
{ {
return false; throw new ContainerShipNotFoundException();
} }
_places.RemoveAt(position); _places[position] = null;
return true; return true;
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
[Serializable] internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View 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", "WithShipName", "WithThreadId" ],
"Properties": {
"Application": "ContainerShip"
}
}
}