Compare commits

..

No commits in common. "3bc4f02768b042261984a5bf313831df5e0cbe55" and "ed234124660579d77f4f6544e57ad9d38f8f2e03" have entirely different histories.

8 changed files with 23 additions and 202 deletions

View File

@ -8,29 +8,6 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<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="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,19 +0,0 @@
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(int i) : base($"Не найден объект по позиции {i}") { }
public AirBomberNotFoundException() : base() { }
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,5 +1,4 @@
using Microsoft.Extensions.Logging; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -30,44 +29,17 @@ namespace AirBomber
private Action<DrawingAirBomber> AddAction; private Action<DrawingAirBomber> AddAction;
private readonly ILogger _logger; public FormMapWithSetAirBombers()
public FormMapWithSetAirBombers(ILogger<FormMapWithSetAirBombers> 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)
{ {
comboBoxSelectorMap.Items.Add(elem.Key); comboBoxSelectorMap.Items.Add(elem.Key);
} }
AddAction = addAirBomber; AddAction = airBomber => { _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectAirBomber(airBomber));
} pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();};
private void addAirBomber(DrawingAirBomber airBomber)
{
try
{
int res = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObjectAirBomber(airBomber);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект {airBomber.ToString()}");
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
} }
private void buttonAddAirBomber_Click(object sender, EventArgs e) private void buttonAddAirBomber_Click(object sender, EventArgs e)
@ -96,22 +68,14 @@ 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)
{ {
IDrawingObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удалён объект {drawingObject.ToString()}");
} }
catch (AirBomberNotFoundException ex) else
{ {
MessageBox.Show($"Ошибка удаления: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
@ -195,13 +159,11 @@ namespace AirBomber
} }
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}, тип карты: {comboBoxSelectorMap.Text}");
} }
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
} }
private void buttonDeleteMap_Click(object sender, EventArgs e) private void buttonDeleteMap_Click(object sender, EventArgs e)
@ -210,29 +172,24 @@ namespace AirBomber
{ {
return; return;
} }
string mapName = listBoxMaps.SelectedItem?.ToString();
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps(); ReloadMaps();
} }
_logger.LogInformation($"Удалена карта {mapName}");
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e) private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_mapsCollection.SaveData(saveFileDialog.FileName))
{ {
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные сохранены в файл {saveFileDialog.FileName}");
} }
catch (Exception ex) else
{ {
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
} }
@ -241,27 +198,14 @@ namespace AirBomber
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
try if (_mapsCollection.LoadData(openFileDialog.FileName))
{ {
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps(); ReloadMaps();
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
} }
catch(FileFormatException ex) else
{ {
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch(FileNotFoundException ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
} }
} }
} }

View File

@ -87,7 +87,7 @@ namespace AirBomber
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns></returns> /// <returns></returns>
public void SaveData(string filename) public bool SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -102,6 +102,7 @@ namespace AirBomber
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw); sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw);
} }
} }
return true;
} }
/// <summary> /// <summary>
@ -109,11 +110,11 @@ namespace AirBomber
/// </summary> /// </summary>
/// <param name="filename"></param> /// <param name="filename"></param>
/// <returns></returns> /// <returns></returns>
public void LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new FileNotFoundException("Файл не найден"); return false;
} }
using (FileStream fs = new(filename, FileMode.Open)) using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs)) using (StreamReader sr = new StreamReader(fs))
@ -121,7 +122,7 @@ namespace AirBomber
string line; string line;
line = sr.ReadLine(); line = sr.ReadLine();
line.Trim(); line.Trim();
if (line != "MapsCollection") throw new FileFormatException("Неверный формат файла"); if (line != "MapsCollection") return false;
_mapStorages.Clear(); _mapStorages.Clear();
while ((line = sr.ReadLine()) != null) while ((line = sr.ReadLine()) != null)
{ {
@ -144,6 +145,7 @@ namespace AirBomber
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
} }
return true;
} }
} }
} }

View File

@ -1,10 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using Serilog;
using System;
namespace AirBomber namespace AirBomber
{ {
internal static class Program internal static class Program
@ -18,27 +11,7 @@ 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();
var services = new ServiceCollection(); Application.Run(new FormMapWithSetAirBombers());
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAirBombers>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetAirBombers>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.AddSerilog();
});
} }
} }
} }

View File

@ -36,14 +36,7 @@ namespace AirBomber
/// <returns></returns> /// <returns></returns>
public int Insert(T airBomber) public int Insert(T airBomber)
{ {
if (airBomber == null) if (_places.Count + 1 >= _maxCount) return -1;
{
throw new ArgumentNullException();
}
if (_places.Count + 1 > _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(0, airBomber); _places.Insert(0, airBomber);
return 0; return 0;
} }
@ -56,10 +49,7 @@ namespace AirBomber
public int Insert(T airBomber, int position) public int Insert(T airBomber, int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount) return -1;
if (_places.Count + 1 >= _maxCount) if (_places.Count + 1 >= _maxCount) return -1;
{
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, airBomber); _places.Insert(position, airBomber);
return position; return position;
} }
@ -70,10 +60,7 @@ namespace AirBomber
/// <returns></returns> /// <returns></returns>
public T Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount) return null;
{
throw new AirBomberNotFoundException(position);
}
T removedObject = _places[position]; T removedObject = _places[position];
_places.RemoveAt(position); _places.RemoveAt(position);
return removedObject; return removedObject;

View File

@ -1,19 +0,0 @@
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 exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,24 +0,0 @@
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
],
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs/log.log" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
}
}