This commit is contained in:
Леонид Малафеев 2023-12-18 15:13:53 +04:00
parent 5d123cc9cb
commit fe7d84e1cb
10 changed files with 184 additions and 42 deletions

View File

@ -23,4 +23,16 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="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>
</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 Cruiser.Exceptions
{
internal class CruiserNotFoundException : ApplicationException
{
public CruiserNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public CruiserNotFoundException() : base() { }
public CruiserNotFoundException(string message) : base(message) { }
public CruiserNotFoundException(string message, Exception exception) : base(message, exception) { }
protected CruiserNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -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 Cruiser.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

@ -177,14 +177,14 @@
// SaveToolStripMenuItem // SaveToolStripMenuItem
// //
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22); SaveToolStripMenuItem.Size = new Size(133, 22);
SaveToolStripMenuItem.Text = "Сохранить"; SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
// //
// UploadToolStripMenuItem // UploadToolStripMenuItem
// //
UploadToolStripMenuItem.Name = "UploadToolStripMenuItem"; UploadToolStripMenuItem.Name = "UploadToolStripMenuItem";
UploadToolStripMenuItem.Size = new Size(180, 22); UploadToolStripMenuItem.Size = new Size(133, 22);
UploadToolStripMenuItem.Text = "Загрузить"; UploadToolStripMenuItem.Text = "Загрузить";
UploadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; UploadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
// //

View File

@ -11,6 +11,9 @@ using System.Windows.Forms;
using Cruiser.Drawing; using Cruiser.Drawing;
using Cruiser.Generics; using Cruiser.Generics;
using Cruiser.MovementStrategy; using Cruiser.MovementStrategy;
using Cruiser.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace Cruiser namespace Cruiser
{ {
@ -24,12 +27,17 @@ namespace Cruiser
/// </summary> /// </summary>
private readonly CruisersGenericStorage _storage; private readonly CruisersGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormCruiserCollection() public FormCruiserCollection(ILogger<FormCruiserCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new CruisersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new CruisersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -65,6 +73,7 @@ namespace Cruiser
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Удаление набора /// Удаление набора
@ -79,8 +88,10 @@ namespace Cruiser
} }
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; //добавил для удаления повторяющегося кода
_storage.DelSet(name);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
@ -105,16 +116,21 @@ namespace Cruiser
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Добавление круизера не удалось (индекс вне границ)");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Добавление круизера не удалось (нет хранилища)");
return; return;
} }
try
{
if ((obj + cruiser)) if ((obj + cruiser))
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавление круизера успешно {listBoxStorages.SelectedItem.ToString()}");
pictureBoxCollection.Image = obj.ShowCruiser(); pictureBoxCollection.Image = obj.ShowCruiser();
} }
else else
@ -122,6 +138,11 @@ namespace Cruiser
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} }
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary> /// <summary>
/// Удаление объекта из набора /// Удаление объекта из набора
/// </summary> /// </summary>
@ -131,29 +152,43 @@ namespace Cruiser
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Удаление круизера не удалось (индекс вне границ)");
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning($"Удаление круизера не удалось (нет хранилища)");
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
_logger.LogWarning($"Удаление круизера не удалось (выбран вариант 'Нет')");
return; return;
} }
int pos = Convert.ToInt32(textBoxNumber.Text); int pos = Convert.ToInt32(textBoxNumber.Text);
try
{
if (obj - pos != null) if (obj - pos != null)
{ {
_logger.LogInformation($"Удаление круизера успешно {listBoxStorages.SelectedItem.ToString()} {pos}");
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowCruiser(); pictureBoxCollection.Image = obj.ShowCruiser();
} }
else else
{ {
_logger.LogWarning($"Удаление круизера не удалось(обьект не найден)");
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch (CruiserNotFoundException ex)
{
_logger.LogWarning($"Удаление круизера не удалось {ex.Message}");
MessageBox.Show(ex.Message);
}
}
/// <summary> /// <summary>
/// Обновление рисунка по набору /// Обновление рисунка по набору
/// </summary> /// </summary>

View File

@ -128,20 +128,16 @@ namespace Cruiser.Generics
{ {
int Ix = 0; int Ix = 0;
int Iy = 0; int Iy = 0;
int i = 0;
foreach (var cruiser in _collection.GetCruisers()) foreach (var cruiser in _collection.GetCruisers())
{ {
cruiser._pictureHeight = _pictureHeight;// добавил для починки отрисовки на форме коллекций cruiser?.SetPosition(Ix, Iy); // починил, для починки удаления
cruiser._pictureWidth = _pictureWidth;// добавил для починки отрисовки на форме коллекций cruiser?.DrawTransport(g);
_collection[i]?.SetPosition(Ix, Iy);
_collection[i]?.DrawTransport(g);
Ix += _placeSizeWidth; Ix += _placeSizeWidth;
if (Ix + _placeSizeHeight > _pictureWidth) if (Ix + _placeSizeHeight > _pictureWidth)
{ {
Ix = 0; Ix = 0;
Iy = _placeSizeHeight; Iy += _placeSizeHeight; // починил, т.к. отрисовывалось максимум 8 кораблей
} }
i++;
} }
} }
} }

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Drawing; using Cruiser.Drawing;
using Cruiser.MovementStrategy; using Cruiser.MovementStrategy;
using System.IO;
namespace Cruiser.Generics namespace Cruiser.Generics
{ {
@ -105,7 +106,7 @@ namespace Cruiser.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
string dataStr = data.ToString(); string dataStr = data.ToString();
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
@ -124,18 +125,18 @@ namespace Cruiser.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader reader = new StreamReader(filename)) using (StreamReader reader = new StreamReader(filename))
{ {
string checker = reader.ReadLine(); string checker = reader.ReadLine();
if (checker == null) if (checker == null)
{ {
return false; throw new NullReferenceException("Нет данных для загрузки");
} }
if (!checker.StartsWith("CruiserStorage")) if (!checker.StartsWith("CruiserStorage"))
{ {
return false; throw new FormatException("Неверный формат данных");
} }
_cruiserStorages.Clear(); _cruiserStorages.Clear();
string strs; string strs;
@ -156,9 +157,13 @@ namespace Cruiser.Generics
DrawingCruiser? cruiser = data?.CreateDrawingCruiser(_separatorForObject, _pictureWidth, _pictureHeight); DrawingCruiser? cruiser = data?.CreateDrawingCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
if (cruiser != null) if (cruiser != null)
{ {
if (collection + cruiser == false) try
{ {
return false; bool? tmp = collection + cruiser;
}
catch (ApplicationException ex)
{
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
} }
} }

View File

@ -1,4 +1,5 @@
using System; using Cruiser.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader; using System.Diagnostics.Eventing.Reader;
using System.Linq; using System.Linq;
@ -40,12 +41,13 @@ namespace Cruiser.Generics
/// </summary> /// </summary>
/// <param name="cruiser">Добавляемый лайнер</param> /// <param name="cruiser">Добавляемый лайнер</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T cruiser) public bool Insert(T cruiser) //починил код, работал неправильно
{ {
if (_places.Count + 1 <= _maxCount) if (_places.Count >= _maxCount)
{ {
_places.Insert(0, cruiser); throw new StorageOverflowException(_places.Count);
} }
_places.Insert(0, cruiser);
return true; return true;
} }
/// <summary> /// <summary>
@ -57,7 +59,7 @@ namespace Cruiser.Generics
{ {
if (position < 0 || position > _places.Count) if (position < 0 || position > _places.Count)
{ {
return false; throw new CruiserNotFoundException(position);
} }
_places[position] = null; _places[position] = null;
return true; return true;
@ -68,15 +70,19 @@ namespace Cruiser.Generics
/// <param name="cruiser">Добавляемый автомобиль</param> /// <param name="cruiser">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public bool Insert(T cruiser, int position) public bool Insert(T cruiser, int position) //починил код, работал неправильно
{ {
if (_places.Count + 1 <= _maxCount && _places.Count >= position) if (_places.Count >= _maxCount)
{ {
throw new StorageOverflowException(_places.Count);
}
if (position < 0 || position > _places.Count)
{
throw new CruiserNotFoundException(position);
}
_places.Insert(position, cruiser); _places.Insert(position, cruiser);
return true; return true;
} }
return false;
}
public T? this[int position] public T? this[int position]
{ {
get get

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Cruiser namespace Cruiser
{ {
internal static class Program internal static class Program
@ -10,8 +15,32 @@ namespace Cruiser
{ {
// 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(); var services = new ServiceCollection();
Application.Run(new FormCruiserCollection()); ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormCruiserCollection>());
}
static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormCruiserCollection>().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);
});
}
} }
} }
} }

20
Cruiser/appsettings.json Normal file
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", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Cruiser"
}
}
}