diff --git a/Stormtrooper/Stormtrooper/AirplaneNotFoundException.cs b/Stormtrooper/Stormtrooper/AirplaneNotFoundException.cs
new file mode 100644
index 0000000..15efd6c
--- /dev/null
+++ b/Stormtrooper/Stormtrooper/AirplaneNotFoundException.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Stormtrooper
+{
+ internal class AirplaneNotFoundException : ApplicationException
+ {
+ public AirplaneNotFoundException() : base() { }
+ public AirplaneNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+ public AirplaneNotFoundException(string message) : base(message) { }
+ public AirplaneNotFoundException(string message, Exception exception) : base(message, exception) { }
+ protected AirplaneNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
diff --git a/Stormtrooper/Stormtrooper/FormMapWithSetAirplane.cs b/Stormtrooper/Stormtrooper/FormMapWithSetAirplane.cs
index 991a017..e385ff9 100644
--- a/Stormtrooper/Stormtrooper/FormMapWithSetAirplane.cs
+++ b/Stormtrooper/Stormtrooper/FormMapWithSetAirplane.cs
@@ -1,4 +1,5 @@
-using Strormtrooper;
+using Microsoft.Extensions.Logging;
+using Strormtrooper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -20,14 +21,15 @@ namespace Stormtrooper
{"Опасная карта", new DangerMap()},
{"Облачная карта", new CloudMap()}
};
+ private readonly ILogger _logger;
///
/// Объект от коллекции карт
///
private readonly MapCollection _mapCollection;
- private MapWithSetAirplaneGeneric _mapAirsCollectionGeneric;
- public FormMapWithSetAirplane()
+ public FormMapWithSetAirplane(ILogger logger)
{
InitializeComponent();
+ _logger = logger;
openFileDialog.Filter = "Text files(*.txt)|*.txt";
saveFileDialog.Filter = "Text files(*.txt)|*.txt";
_mapCollection = new MapCollection(pictureBox.Width, pictureBox.Height);
@@ -63,16 +65,25 @@ namespace Stormtrooper
{
if (comboBoxMapSelector.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxMapName.Text))
{
+ _logger.LogInformation("Не все данные заполнены при попытке создании карты");
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxMapSelector.Text))
{
+ _logger.LogInformation($"Нет карты с названием {comboBoxMapSelector.Text}");
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
+ if (textBoxMapName.Text.Contains('|') || textBoxMapName.Text.Contains(':') || textBoxMapName.Text.Contains(';'))
+ {
+ _logger.LogInformation("Присутствуют символы, недопустимые для имени карты");
+ MessageBox.Show("Присутствуют символы, недопустимые для имени карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return;
+ }
_mapCollection.AddMap(textBoxMapName.Text, _mapsDict[comboBoxMapSelector.Text]);
ReloadMaps();
+ _logger.LogInformation($"Добавлена карта {textBoxMapName.Text}");
}
///
/// Добавление объекта
@@ -92,15 +103,31 @@ namespace Stormtrooper
return;
}
DrawningObject airplane = new(drawningMilitaryAirplane);
- if (_mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty] + airplane != -1)
+ try
{
- MessageBox.Show("Объект добавлен");
- pictureBox.Image = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ if (_mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty] + airplane != -1)
+ {
+ _logger.LogInformation($"Добавление объекта {airplane}");
+ MessageBox.Show("Объект добавлен");
+ pictureBox.Image = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogInformation("Не удалось добавить объект");
+ MessageBox.Show("Не удалось добавить объект");
+ }
}
- else
+ catch (StorageOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
+ MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
+ catch (Exception ex)
+ {
+ _logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
+ }
+
}
///
/// Удаление объекта
@@ -122,15 +149,31 @@ namespace Stormtrooper
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ var deletedAirplane = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty] - pos;
+ if (deletedAirplane != null)
+ {
+ _logger.LogInformation($"Объект {deletedAirplane} удалён");
+ MessageBox.Show("Объект удален");
+ pictureBox.Image = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (AirplaneNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning($"Ошибка удаления: {ex.Message}");
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
+ catch(Exception ex)
+ {
+ _logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
+ }
+
}
///
/// Вывод набора
@@ -193,6 +236,7 @@ namespace Stormtrooper
private void listBoxMap_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapCollection[listBoxMap.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ _logger.LogInformation($"Текущая карта сменена на {listBoxMap.SelectedItem?.ToString() ?? string.Empty}");
}
private void ButtonRemoveMap_Click(object sender, EventArgs e)
{
@@ -205,6 +249,7 @@ namespace Stormtrooper
{
_mapCollection.DelMap(listBoxMap.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
+ _logger.LogInformation($"Удалена карта {listBoxMap.SelectedItem?.ToString() ?? string.Empty}");
}
}
@@ -212,13 +257,16 @@ namespace Stormtrooper
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapCollection.SaveData(saveFileDialog.FileName))
+ try
{
+ _mapCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation($"Успешное сохранение по пути {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось сохранить данные. Ошибка - {ex.Message}");
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -227,14 +275,17 @@ namespace Stormtrooper
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapCollection.LoadData(openFileDialog.FileName))
+ try
{
+ _mapCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
+ _logger.LogInformation($"Успешная загрузка по пути {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не получилось загрузить файл", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning($"Не удалось загрузить данные. Ошибка - {ex.Message}");
+ MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
diff --git a/Stormtrooper/Stormtrooper/MapCollection.cs b/Stormtrooper/Stormtrooper/MapCollection.cs
index 07d2181..b48d44b 100644
--- a/Stormtrooper/Stormtrooper/MapCollection.cs
+++ b/Stormtrooper/Stormtrooper/MapCollection.cs
@@ -64,7 +64,7 @@ namespace Stormtrooper
_mapStorages.Remove(name);
}
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -78,18 +78,17 @@ namespace Stormtrooper
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
- return true;
}
///
/// Загрузка информации по локомотивам в депо из файла
///
///
///
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@@ -97,7 +96,7 @@ namespace Stormtrooper
if (!str.Contains("MapCollection"))
{
//если нет такой записи, то это не те данные
- return false;
+ throw new FileFormatException("Формат данных в файле неправильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
@@ -120,7 +119,6 @@ namespace Stormtrooper
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
- return true;
}
diff --git a/Stormtrooper/Stormtrooper/Program.cs b/Stormtrooper/Stormtrooper/Program.cs
index 65b5334..50685ff 100644
--- a/Stormtrooper/Stormtrooper/Program.cs
+++ b/Stormtrooper/Stormtrooper/Program.cs
@@ -1,8 +1,7 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using System.Windows.Forms;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
namespace Stormtrooper
{
@@ -16,7 +15,30 @@ namespace Stormtrooper
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new FormMapWithSetAirplane());
+ ApplicationConfiguration.Initialize();
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ using (ServiceProvider serviceProvider = services.BuildServiceProvider())
+ {
+ Application.Run(serviceProvider.GetRequiredService());
+ }
+ }
+ private static void ConfigureServices(ServiceCollection services)
+ {
+ services.AddSingleton()
+ .AddLogging(option =>
+ {
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile(path: "appSettings.json", optional: false, reloadOnChange: true)
+ .Build();
+
+ var logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration);
+
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(logger);
+ });
}
}
}
diff --git a/Stormtrooper/Stormtrooper/SetAirplaneGeneric.cs b/Stormtrooper/Stormtrooper/SetAirplaneGeneric.cs
index bd13158..04001c0 100644
--- a/Stormtrooper/Stormtrooper/SetAirplaneGeneric.cs
+++ b/Stormtrooper/Stormtrooper/SetAirplaneGeneric.cs
@@ -48,7 +48,7 @@ namespace Stormtrooper
public int Insert(T airplane, int position)
{
if (position < 0 || position >= _maxCount - 1)
- return -1;
+ throw new StorageOverflowException(_maxCount);
_places.Insert(position, airplane);
return position;
@@ -61,7 +61,7 @@ namespace Stormtrooper
public T Remove(int position)
{
if (Count == 0 || position < 0 || position >= _maxCount)
- return null;
+ throw new AirplaneNotFoundException(position);
T air = _places[position];
_places[position] = null;
return air;
diff --git a/Stormtrooper/Stormtrooper/StorageOverFlowException.cs b/Stormtrooper/Stormtrooper/StorageOverFlowException.cs
new file mode 100644
index 0000000..fe2aa4a
--- /dev/null
+++ b/Stormtrooper/Stormtrooper/StorageOverFlowException.cs
@@ -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 Stormtrooper
+{
+ [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) { }
+ }
+}
diff --git a/Stormtrooper/Stormtrooper/Stormtrooper.csproj b/Stormtrooper/Stormtrooper/Stormtrooper.csproj
index 9ee8484..30817a2 100644
--- a/Stormtrooper/Stormtrooper/Stormtrooper.csproj
+++ b/Stormtrooper/Stormtrooper/Stormtrooper.csproj
@@ -8,6 +8,15 @@
enable
+
+
+
+
+
+
+
+
+
Form
diff --git a/Stormtrooper/Stormtrooper/appSetting.json b/Stormtrooper/Stormtrooper/appSetting.json
new file mode 100644
index 0000000..a6e6f97
--- /dev/null
+++ b/Stormtrooper/Stormtrooper/appSetting.json
@@ -0,0 +1,20 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
+ "Properties": {
+ "Application": "Stormtrooper"
+ }
+ }
+}
\ No newline at end of file