This commit is contained in:
DeerElk 2024-02-14 06:14:59 +04:00
parent da05da61a1
commit d7068579dc
8 changed files with 180 additions and 63 deletions

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,7 +1,8 @@
using ProjectAircraftCarrier.DrawingObjects; using Microsoft.VisualBasic.Logging;
using Microsoft.Extensions.Logging;
using ProjectAircraftCarrier.DrawingObjects;
using ProjectAircraftCarrier.Generics; using ProjectAircraftCarrier.Generics;
using ProjectAircraftCarrier.MovementStrategy; using ProjectAircraftCarrier.Exceptions;
using System.Windows.Forms;
namespace ProjectAircraftCarrier namespace ProjectAircraftCarrier
{ {
/// <summary> /// <summary>
@ -14,13 +15,18 @@ namespace ProjectAircraftCarrier
/// </summary> /// </summary>
private readonly WarshipsGenericStorage _storage; private readonly WarshipsGenericStorage _storage;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormWarshipCollection() public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new WarshipsGenericStorage(pictureBoxCollection.Width, _storage = new WarshipsGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height); pictureBoxCollection.Height);
_logger = logger;
} }
/// <summary> /// <summary>
/// Заполнение listBoxObjects /// Заполнение listBoxObjects
@ -34,12 +40,12 @@ namespace ProjectAircraftCarrier
listBoxStorages.Items.Add(_storage.Keys[i]); listBoxStorages.Items.Add(_storage.Keys[i]);
} }
if (listBoxStorages.Items.Count > 0 && (index == -1 || index if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count)) >= listBoxStorages.Items.Count))
{ {
listBoxStorages.SelectedIndex = 0; listBoxStorages.SelectedIndex = 0;
} }
else if (listBoxStorages.Items.Count > 0 && index > -1 && else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count) index < listBoxStorages.Items.Count)
{ {
listBoxStorages.SelectedIndex = index; listBoxStorages.SelectedIndex = index;
} }
@ -59,6 +65,7 @@ namespace ProjectAircraftCarrier
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
} }
/// <summary> /// <summary>
/// Выбор набора /// Выбор набора
@ -83,14 +90,15 @@ namespace ProjectAircraftCarrier
{ {
return; return;
} }
if (MessageBox.Show($"Delete an object" + string name = listBoxStorages.SelectedItem.ToString() ??
$"{ listBoxStorages.SelectedItem}?", string.Empty;
"Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) if (MessageBox.Show($"Delete an object {name}?", "Deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(name);
?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
} }
} }
/// <summary> /// <summary>
@ -112,15 +120,22 @@ namespace ProjectAircraftCarrier
} }
FormWarshipConfig form = new(); FormWarshipConfig form = new();
form.Show(); form.Show();
Action<DrawingWarship>? warshipDelegate = new((warship) => { Action<DrawingWarship>? warshipDelegate = new((warship) =>
if (obj + warship) {
try
{ {
MessageBox.Show("Object added"); bool q = obj + warship;
MessageBox.Show("Object Added");
_logger.LogInformation($"Object added to collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarships(); pictureBoxCollection.Image = obj.ShowWarships();
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Failed to add an object"); _logger.LogWarning($"Collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty} " +
$"is full");
MessageBox.Show(ex.Message);
} }
}); });
form.AddEvent(warshipDelegate); form.AddEvent(warshipDelegate);
@ -137,26 +152,41 @@ namespace ProjectAircraftCarrier
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty]; string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
} }
if (MessageBox.Show("Delete an object?", "Deletion", if (MessageBox.Show("Delete an object?", "Deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.No) DialogResult.No)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{ {
MessageBox.Show("Object deleted"); if (obj - pos != null)
pictureBoxCollection.Image = obj.ShowWarships(); {
MessageBox.Show("Object deleted");
_logger.LogInformation($"Object has been removed from the " +
$"collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty} " +
$"at position {pos}");
pictureBoxCollection.Image = obj.ShowWarships();
}
else
{
MessageBox.Show("Failed to delete an object");
_logger.LogWarning($"Failed to remove object from the " +
$"collection " +
$"{listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
} }
else catch (WarshipNotFoundException ex)
{ {
MessageBox.Show("Failed to delete an object"); _logger.LogWarning($"No number was entered");
MessageBox.Show(ex.Message);
} }
} }
/// <summary> /// <summary>
@ -187,15 +217,19 @@ namespace ProjectAircraftCarrier
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Save was successful", "Result", _storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Save was successful", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"File {saveFileDialog.FileName} " +
$"successfuly saved");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Not preserved", "Result", _logger.LogWarning("Failed to save");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Not preserved: {ex.Message}",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -208,19 +242,24 @@ namespace ProjectAircraftCarrier
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Load was successful", _storage.LoadData(openFileDialog.FileName);
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Load was successful", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"File {openFileDialog.FileName} " +
$"successfully loaded");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }
ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Not loaded", "Result", _logger.LogWarning("Failed to load");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Didn't load: {ex.Message}", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -1,3 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectAircraftCarrier namespace ProjectAircraftCarrier
{ {
internal static class Program internal static class Program
@ -11,7 +14,22 @@ namespace ProjectAircraftCarrier
// 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 FormWarshipCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.
GetRequiredService<FormWarshipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormWarshipCollection>().AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -1,5 +1,5 @@
using System.Numerics; using System.Numerics;
using ProjectAircraftCarrier.Exceptions;
namespace ProjectAircraftCarrier.Generics namespace ProjectAircraftCarrier.Generics
{ {
/// <summary> /// <summary>
@ -38,7 +38,7 @@ namespace ProjectAircraftCarrier.Generics
public bool Insert(T warship) public bool Insert(T warship)
{ {
if (_places.Count == _maxCount) if (_places.Count == _maxCount)
return false; throw new StorageOverflowException(_maxCount);
Insert(warship, 0); Insert(warship, 0);
return true; return true;
} }
@ -50,8 +50,9 @@ namespace ProjectAircraftCarrier.Generics
/// <returns></returns> /// <returns></returns>
public bool Insert(T warship, int position) public bool Insert(T warship, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < if (_places.Count == _maxCount)
_maxCount)) throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false; return false;
_places.Insert(position, warship); _places.Insert(position, warship);
return true; return true;
@ -64,7 +65,7 @@ namespace ProjectAircraftCarrier.Generics
public bool Remove(int position) public bool Remove(int position)
{ {
if (!(position >= 0 && position < Count)) if (!(position >= 0 && position < Count))
return false; throw new WarshipNotFoundException(position);
_places.RemoveAt(position); _places.RemoveAt(position);
return true; return true;
} }
@ -77,15 +78,17 @@ namespace ProjectAircraftCarrier.Generics
{ {
get get
{ {
if (!(position >= 0 && position <= Count)) if (!(position >= 0 && position < Count))
return null; return null;
return _places[position]; return _places[position];
} }
set set
{ {
if (!(position >= 0 && position <= Count)) if (!(position >= 0 && position < Count && _places.Count <
_maxCount))
return; return;
_places.Insert(position, value); _places.Insert(position, value);
return;
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"The allowed " +
$"number is exceeded in the set: { 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,17 @@
using System.Runtime.Serialization;
namespace ProjectAircraftCarrier.Exceptions
{
[Serializable]
internal class WarshipNotFoundException : ApplicationException
{
public WarshipNotFoundException(int i) : base($"Object not found at" +
$" position {i}") { }
public WarshipNotFoundException() : base() { }
public WarshipNotFoundException(string message) : base(message) { }
public WarshipNotFoundException(string message, Exception exception) :
base(message, exception) { }
protected WarshipNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -97,7 +97,7 @@ namespace ProjectAircraftCarrier.Generics
/// </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))
{ {
@ -105,13 +105,13 @@ namespace ProjectAircraftCarrier.Generics
} }
StringBuilder data = new(); StringBuilder data = new();
foreach (KeyValuePair<string, WarshipsGenericCollection foreach (KeyValuePair<string, WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>> record in <DrawingWarship, DrawingObjectWarship>>
_warshipStorages) record in _warshipStorages)
{ {
StringBuilder records = new(); StringBuilder records = new();
foreach (DrawingWarship? elem in record.Value.GetWarships) foreach (DrawingWarship? elem in record.Value.GetWarships)
{ {
records.Append($"" + records.Append(
$"{elem?.GetDataForSave(_separatorForObject)}" + $"{elem?.GetDataForSave(_separatorForObject)}" +
$"{_separatorRecords}"); $"{_separatorRecords}");
} }
@ -120,24 +120,24 @@ namespace ProjectAircraftCarrier.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Invalid operation, no data to save");
} }
using FileStream fs = new(filename, FileMode.Create); using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes($"WarshipStorage" + byte[] info = new UTF8Encoding(true).GetBytes
$"{Environment.NewLine}{data}"); ($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length); fs.Write(info, 0, info.Length);
return true; return;
} }
/// <summary> /// <summary>
/// Загрузка информации по кораблям в хранилище из файла /// Загрузка информации по кораблям в хранилище из файла
/// </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("File not found");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
@ -150,19 +150,19 @@ namespace ProjectAircraftCarrier.Generics
} }
} }
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new Exception("No data to download");
} }
if (!strs[0].StartsWith("WarshipStorage")) if (!strs[0].StartsWith("WarshipStorage"))
{ {
return false; throw new Exception("Invalid data format");
} }
_warshipStorages.Clear(); _warshipStorages.Clear();
foreach (string data in strs) foreach (string data in strs)
{ {
string[] record = data.Split(_separatorForKeyValue, string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
@ -170,24 +170,23 @@ namespace ProjectAircraftCarrier.Generics
} }
WarshipsGenericCollection<DrawingWarship, DrawingObjectWarship> WarshipsGenericCollection<DrawingWarship, DrawingObjectWarship>
collection = new(_pictureWidth, _pictureHeight); collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
DrawingWarship? warship = DrawingWarship? warship =
elem?.CreateDrawingWarship(_separatorForObject, elem?.CreateDrawingWarship(_separatorForObject,
_pictureWidth, _pictureHeight); _pictureWidth, _pictureHeight);
if (warship != null) if (warship != null)
{ {
if (!(collection + warship)) if (!(collection + warship))
{ {
return false; throw new Exception("Error adding to collection");
} }
} }
} }
_warshipStorages.Add(record[0], collection); _warshipStorages.Add(record[0], collection);
} }
return true;
} }
} }
} }

View File

@ -0,0 +1,14 @@
<?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>