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>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</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.MovementStrategy;
using System.Windows.Forms;
using ProjectAircraftCarrier.Exceptions;
namespace ProjectAircraftCarrier
{
/// <summary>
@ -14,13 +15,18 @@ namespace ProjectAircraftCarrier
/// </summary>
private readonly WarshipsGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormWarshipCollection()
public FormWarshipCollection(ILogger<FormWarshipCollection> logger)
{
InitializeComponent();
_storage = new WarshipsGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
@ -34,12 +40,12 @@ namespace ProjectAircraftCarrier
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
@ -59,6 +65,7 @@ namespace ProjectAircraftCarrier
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
@ -83,14 +90,15 @@ namespace ProjectAircraftCarrier
{
return;
}
if (MessageBox.Show($"Delete an object" +
$"{ listBoxStorages.SelectedItem}?",
"Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
string name = listBoxStorages.SelectedItem.ToString() ??
string.Empty;
if (MessageBox.Show($"Delete an object {name}?", "Deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
}
}
/// <summary>
@ -112,15 +120,22 @@ namespace ProjectAircraftCarrier
}
FormWarshipConfig form = new();
form.Show();
Action<DrawingWarship>? warshipDelegate = new((warship) => {
if (obj + warship)
Action<DrawingWarship>? warshipDelegate = new((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();
}
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);
@ -137,26 +152,41 @@ namespace ProjectAircraftCarrier
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Delete an object?", "Deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.No)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Object deleted");
pictureBoxCollection.Image = obj.ShowWarships();
if (obj - pos != null)
{
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>
@ -187,15 +217,19 @@ namespace ProjectAircraftCarrier
{
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);
_logger.LogInformation($"File {saveFileDialog.FileName} " +
$"successfuly saved");
}
else
catch (Exception ex)
{
MessageBox.Show("Not preserved", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Failed to save");
MessageBox.Show($"Not preserved: {ex.Message}",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -208,19 +242,24 @@ namespace ProjectAircraftCarrier
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Load was successful",
"Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Load was successful", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"File {openFileDialog.FileName} " +
$"successfully loaded");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Not loaded", "Result",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Failed to load");
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
{
internal static class Program
@ -11,7 +14,22 @@ namespace ProjectAircraftCarrier
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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 ProjectAircraftCarrier.Exceptions;
namespace ProjectAircraftCarrier.Generics
{
/// <summary>
@ -38,7 +38,7 @@ namespace ProjectAircraftCarrier.Generics
public bool Insert(T warship)
{
if (_places.Count == _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
Insert(warship, 0);
return true;
}
@ -50,8 +50,9 @@ namespace ProjectAircraftCarrier.Generics
/// <returns></returns>
public bool Insert(T warship, int position)
{
if (!(position >= 0 && position <= Count && _places.Count <
_maxCount))
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
_places.Insert(position, warship);
return true;
@ -64,7 +65,7 @@ namespace ProjectAircraftCarrier.Generics
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
return false;
throw new WarshipNotFoundException(position);
_places.RemoveAt(position);
return true;
}
@ -77,15 +78,17 @@ namespace ProjectAircraftCarrier.Generics
{
get
{
if (!(position >= 0 && position <= Count))
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position <= Count))
if (!(position >= 0 && position < Count && _places.Count <
_maxCount))
return;
_places.Insert(position, value);
return;
}
}
/// <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>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -105,13 +105,13 @@ namespace ProjectAircraftCarrier.Generics
}
StringBuilder data = new();
foreach (KeyValuePair<string, WarshipsGenericCollection
<DrawingWarship, DrawingObjectWarship>> record in
_warshipStorages)
<DrawingWarship, DrawingObjectWarship>>
record in _warshipStorages)
{
StringBuilder records = new();
foreach (DrawingWarship? elem in record.Value.GetWarships)
{
records.Append($"" +
records.Append(
$"{elem?.GetDataForSave(_separatorForObject)}" +
$"{_separatorRecords}");
}
@ -120,24 +120,24 @@ namespace ProjectAircraftCarrier.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Invalid operation, no data to save");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes($"WarshipStorage" +
$"{Environment.NewLine}{data}");
byte[] info = new UTF8Encoding(true).GetBytes
($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
return;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </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("File not found");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@ -150,19 +150,19 @@ namespace ProjectAircraftCarrier.Generics
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new Exception("No data to download");
}
if (!strs[0].StartsWith("WarshipStorage"))
{
return false;
throw new Exception("Invalid data format");
}
_warshipStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
@ -170,24 +170,23 @@ namespace ProjectAircraftCarrier.Generics
}
WarshipsGenericCollection<DrawingWarship, DrawingObjectWarship>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarship? warship =
elem?.CreateDrawingWarship(_separatorForObject,
elem?.CreateDrawingWarship(_separatorForObject,
_pictureWidth, _pictureHeight);
if (warship != null)
{
if (!(collection + warship))
{
return false;
throw new Exception("Error adding to 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>