Compare commits

..

2 Commits

8 changed files with 133 additions and 23 deletions

View File

@ -16,6 +16,23 @@
<LangVersion>preview</LangVersion> <LangVersion>preview</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.1.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

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 AirBomber
{
[Serializable]
internal class AirBomberNotFoundException : ApplicationException
{
public AirBomberNotFoundException() : base() { }
public AirBomberNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public AirBomberNotFoundException(string message) : base(message) { }
public AirBomberNotFoundException(string message, Exception exception) : base (message, exception) { }
protected AirBomberNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -23,9 +24,12 @@ namespace AirBomber
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
public FormMapWithSetAirBomber() private readonly ILogger _logger;
public FormMapWithSetAirBomber(ILogger<FormMapWithSetAirBomber> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict) foreach (var elem in _mapsDict)
@ -93,6 +97,8 @@ namespace AirBomber
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
@ -103,6 +109,15 @@ namespace AirBomber
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
catch(AirBomberNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e) private void ButtonShowStorage_Click(object sender, EventArgs e)
{ {
@ -162,6 +177,7 @@ namespace AirBomber
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
} }
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
@ -187,13 +203,14 @@ namespace AirBomber
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(saveFileDialog.FileName)) try
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); ; ;
} }
} }
} }
@ -202,15 +219,16 @@ namespace AirBomber
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(openFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps(); ReloadMaps();
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -45,7 +45,7 @@ namespace AirBomber
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -60,14 +60,13 @@ namespace AirBomber
separatorData)}{Environment.NewLine}"); separatorData)}{Environment.NewLine}");
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
string bufferTextFromFile = ""; string bufferTextFromFile = "";
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
@ -80,7 +79,7 @@ namespace AirBomber
{ {
if (!str.Contains("MapsCollection")) if (!str.Contains("MapsCollection"))
{ {
return false; throw new Exception("Формат данных в файлен не правильный");
} }
else else
{ {
@ -111,7 +110,6 @@ namespace AirBomber
} }
} }
} }
return true;
} }
} }
} }

View File

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

View File

@ -30,7 +30,7 @@ namespace AirBomber
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount)
{ {
return -1; throw new StorageOverflowException(_maxCount);
} }
_places.Insert(position, airBomber); _places.Insert(position, airBomber);
return position; return position;
@ -40,10 +40,16 @@ namespace AirBomber
{ {
if (position < 0 || position > _maxCount) if (position < 0 || position > _maxCount)
{ {
return null; throw new StorageOverflowException(_maxCount);
} }
T elem = _places[position]; T elem = _places[position];
_places[position] = null; _places[position] = null;
if (elem == null)
{
throw new AirBomberNotFoundException(position);
}
return elem; return elem;
} }

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 AirBomber
{
[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 innerException) : base(message, innerException) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

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