Antonova D.V. Lab7 #7
@ -8,6 +8,36 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="nlog.config" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Configuration.ConfigurationBuilders.Environment" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.FileProviders.Composite" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="7.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
|
||||
<PackageReference Include="TestBase" Version="4.1.4.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
@ -25,19 +26,18 @@ namespace AirBomber
|
||||
/// Объект от коллекции карт
|
||||
/// </summary>
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Объект от класса карты с набором объектов
|
||||
/// </summary>
|
||||
private MapWithSetJetsGeneric<DrawningObjectJet, AbstractMap> _mapJetsCollectionGeneric;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormMapWithSetJets()
|
||||
public FormMapWithSetJets(ILogger<FormMapWithSetJets> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logger = logger;
|
||||
_mapsCollection = new MapsCollection(pictureBoxJet.Width, pictureBoxJet.Height);
|
||||
comboBoxSelectorMap.Items.Clear();
|
||||
foreach (var elem in _mapsDict)
|
||||
@ -75,15 +75,18 @@ namespace AirBomber
|
||||
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||
return;
|
||||
}
|
||||
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
|
||||
{
|
||||
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
|
||||
return;
|
||||
}
|
||||
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation("Добавлена карта {0}", textBoxNewMapName.Text);
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор карты
|
||||
@ -93,6 +96,7 @@ namespace AirBomber
|
||||
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление карты
|
||||
@ -109,6 +113,7 @@ namespace AirBomber
|
||||
{
|
||||
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
ReloadMaps();
|
||||
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -116,34 +121,37 @@ namespace AirBomber
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddJet_Click(object sender, EventArgs e)
|
||||
private void ButtonAddJet_Click(DrawningJet jet)
|
||||
{
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
try
|
||||
{
|
||||
return;
|
||||
}
|
||||
var formJetConfig = new FormJetConfig();
|
||||
// использование лямбда функции для добавления самолета подписываемся на событие EventAddJet
|
||||
// указываем лямбда функцию - будет добавлять новый самолет, который передала форма добавления
|
||||
formJetConfig.EventAddJet += (DrawningJet djet) =>
|
||||
{
|
||||
if (djet == null)
|
||||
if (listBoxMaps.SelectedIndex == -1)
|
||||
{
|
||||
MessageBox.Show("Сначала создайте объект");
|
||||
return;
|
||||
}
|
||||
DrawningObjectJet jet = new(djet);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + jet != -1)
|
||||
DrawningObjectJet boat = new(jet);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation("Объект добавлен");
|
||||
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
_logger.LogInformation("Не удалось добавить объект");
|
||||
}
|
||||
};
|
||||
formJetConfig.Show();
|
||||
}
|
||||
catch (StorageOverflowException ex)
|
||||
{
|
||||
_logger.LogWarning($"Ошибка, переполнение хранилища: {0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка, хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_logger.LogWarning("Ошибка добавления");
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление объекта
|
||||
@ -167,14 +175,25 @@ namespace AirBomber
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
|
||||
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
var deletedJet = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
|
||||
if (deletedJet != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
_logger.LogInformation("Из текущей карты удален объект {@ship}", deletedJet);
|
||||
pictureBoxJet.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
|
||||
MessageBox.Show($"Ошибка удаления: {ex.Message}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@ -239,13 +258,16 @@ namespace AirBomber
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_mapsCollection.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogInformation("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -254,14 +276,17 @@ namespace AirBomber
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_mapsCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_mapsCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка данных прошла успешно", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadMaps();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
22
AirBomber/AirBomber/JetNotFoundException.cs
Normal file
22
AirBomber/AirBomber/JetNotFoundException.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AirBomber
|
||||
{
|
||||
internal class JetNotFoundException : ApplicationException
|
||||
{
|
||||
public JetNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
|
||||
public JetNotFoundException() : base() { }
|
||||
|
||||
public JetNotFoundException(string message) : base(message) { }
|
||||
|
||||
public JetNotFoundException(string message, Exception exception) : base(message, exception) { }
|
||||
|
||||
protected JetNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -129,7 +129,7 @@ namespace AirBomber
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
{
|
||||
@ -137,7 +137,7 @@ namespace AirBomber
|
||||
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new FileFormatException("Формат данных в файле неправильный");
|
||||
}
|
||||
//очищаем записи
|
||||
_mapStorages.Clear();
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace AirBomber
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +16,27 @@ namespace AirBomber
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormMapWithSetJets());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetJets>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetJets>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: "serilog.json").Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -47,10 +47,15 @@ namespace AirBomber
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (_places.Contains(jet))
|
||||
{
|
||||
throw new ArgumentException($"Объект {jet} уже есть в наборе");
|
||||
}
|
||||
if (Count == _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
}
|
||||
_places.Insert(position, jet);
|
||||
|
||||
_places.Remove(null);
|
||||
|
||||
return position;
|
||||
}
|
||||
/// <summary>
|
||||
@ -61,13 +66,9 @@ namespace AirBomber
|
||||
public T Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= _maxCount) return null;
|
||||
|
||||
T savedJet = _places[position];
|
||||
|
||||
_places[position] = null;
|
||||
|
||||
|
||||
return savedJet;
|
||||
var result = _places[position];
|
||||
_places.RemoveAt(position);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
22
AirBomber/AirBomber/StorageOverflowException.cs
Normal file
22
AirBomber/AirBomber/StorageOverflowException.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AirBomber
|
||||
{
|
||||
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) { }
|
||||
}
|
||||
}
|
14
AirBomber/AirBomber/nlog.config
Normal file
14
AirBomber/AirBomber/nlog.config
Normal 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>
|
Loading…
x
Reference in New Issue
Block a user