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

View File

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

View File

@ -27,4 +27,14 @@
<Folder Include="Resources\" />
</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>

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>
public bool Container { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса контейнеровоза
/// Инициализация полей объекта-класса контейнеровоз
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес </param>

View File

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

View File

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

View File

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

View File

@ -1,5 +1,10 @@
using ProjectContainerShip;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectContainerShip
{
internal static class Program
@ -13,7 +18,28 @@ namespace ProjectContainerShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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.Linq;
using System.Text;
@ -41,16 +42,39 @@ namespace ProjectContainerShip.Generics
/// <returns></returns>
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)
return -1;
throw new ContainerShipNotFoundException(position);
if (Count >= _maxCount)
return -1;
_places.Insert(position, ship);
return position;
throw new StorageOverflowException(position);
_places.Insert(0, ship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@ -59,11 +83,13 @@ namespace ProjectContainerShip.Generics
/// <returns></returns>
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;
}
/// <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"
}
}
}