diff --git a/Ship/Ship/FormMapWithSetShips.cs b/Ship/Ship/FormMapWithSetShips.cs
index 6b02a5e..ff294a2 100644
--- a/Ship/Ship/FormMapWithSetShips.cs
+++ b/Ship/Ship/FormMapWithSetShips.cs
@@ -1,4 +1,5 @@
-using System;
+using Microsoft.Extensions.Logging;
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -27,15 +28,20 @@ namespace Ship
///
private readonly MapsCollection _mapsCollection;
///
+ /// Логер
+ ///
+ private readonly ILogger _logger;
+ ///
/// Объект от класса карты с набором объектов
///
private MapWithSetShipsGeneric _mapShipsCollectionGeneric;
///
/// Конструктор
///
- public FormMapWithSetShips()
+ public FormMapWithSetShips(ILogger logger)
{
InitializeComponent();
+ _logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -75,15 +81,17 @@ namespace Ship
string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("При добавлении карты не были указаны все параметры.");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Нет карты с названием: {0}", textBoxNewMapName.Text);
return;
}
- _mapsCollection.AddMap(textBoxNewMapName.Text,
- _mapsDict[comboBoxSelectorMap.Text]);
+ _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
+ _logger.LogInformation("Добавлена карта с названием \"{1}\" типа \"{0}\"", textBoxNewMapName.Text, comboBoxSelectorMap.Text);
ReloadMaps();
}
///
@@ -98,6 +106,7 @@ namespace Ship
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ _logger.LogInformation("Переход на карту \"{0}\"", listBoxMaps.SelectedItem?.ToString() ?? String.Empty);
}
///
/// Удаление карты
@@ -112,8 +121,8 @@ namespace Ship
}
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);
+ _logger.LogInformation("Удалена карта \"{0}\"", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
@@ -131,17 +140,30 @@ namespace Ship
{
return;
}
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObject(ship) != -1)
+ try
{
- MessageBox.Show("Объект добавлен");
+ if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawingObject(ship) != -1)
+ {
+ MessageBox.Show("Объект добавлен");
+ _logger.LogInformation("Добавлен новый объект");
+ }
+ else
+ {
+ MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning("Не удалось добавить объект");
+ }
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
- else
+ catch (StorageOverflowException ex)
{
- MessageBox.Show("Не удалось добавить объект");
+ _logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
+ MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Неизвестная ошибка: {0}", ex.Message);
+ MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
-
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].ShowSet();
});
form.Show();
}
@@ -160,21 +182,31 @@ namespace Ship
{
return;
}
- if (MessageBox.Show("Удалить объект?", "Удаление",
- MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
+ if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
- if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ try
{
- MessageBox.Show("Объект удален");
- pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
+ {
+ MessageBox.Show("Объект удален");
+ _logger.LogInformation("Удалён объект на позиции {0}", pos);
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
+ }
+ else
+ {
+ _logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
+ MessageBox.Show("Не удалось удалить объект");
+ }
}
- else
+ catch (ShipNotFoundException ex)
{
- MessageBox.Show("Не удалось удалить объект");
+ _logger.LogWarning("Ошибка удаления: {0}", ex.Message);
+ MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
+
}
///
/// Вывод набора
@@ -243,15 +275,16 @@ namespace Ship
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.SaveData(saveFileDialog.FileName))
+ try
{
- MessageBox.Show("Сохранение прошло успешно", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _mapsCollection.SaveData(saveFileDialog.FileName);
+ _logger.LogInformation("Сохранение в файл \"{0}\"", saveFileDialog.FileName);
+ MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не сохранилось", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не удалось сохранить файл \"{0}\": {1}", saveFileDialog.FileName, ex.Message);
+ MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@@ -264,15 +297,17 @@ namespace Ship
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
- if (_mapsCollection.LoadData(openFileDialog.FileName))
+ try
{
- MessageBox.Show("Загрузка прошла успешно", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Information);
+ _mapsCollection.LoadData(openFileDialog.FileName);
+ _logger.LogInformation("Загрузка из файла \"{0}\"", openFileDialog.FileName);
+ MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
- else
+ catch (Exception ex)
{
- MessageBox.Show("Не удалось загрузить", "Результат",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ _logger.LogWarning("Не удалось загрузить файл \"{0}\": {1}", openFileDialog.FileName, ex.Message);
+ MessageBox.Show($"Не удалось загрузить: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadMaps();
diff --git a/Ship/Ship/MapsCollection.cs b/Ship/Ship/MapsCollection.cs
index 5590319..65e156b 100644
--- a/Ship/Ship/MapsCollection.cs
+++ b/Ship/Ship/MapsCollection.cs
@@ -80,7 +80,7 @@ namespace Ship
///
/// Путь и имя файла
///
- public bool SaveData(string filename)
+ public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -98,18 +98,17 @@ namespace Ship
}
}
}
- return true;
}
///
/// Загрузка нформации по автомобилям на парковках из файла
///
///
///
- public bool LoadData(string filename)
+ public void LoadData(string filename)
{
if (!File.Exists(filename))
{
- return false;
+ throw new FileNotFoundException("Файл не найден");
}
string bufferTextFromFile = "";
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@@ -120,7 +119,7 @@ namespace Ship
string cur_line = sr.ReadLine();
if (cur_line == null || !cur_line.Contains("Maps Collection"))
{
- return false;
+ throw new FileFormatException("Неверный формат файла");
}
_mapStorages.Clear();
while ((cur_line = sr.ReadLine()) != null)
@@ -142,7 +141,6 @@ namespace Ship
_mapStorages[elements[0]].LoadData(elements[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
- return true;
}
}
}
diff --git a/Ship/Ship/Program.cs b/Ship/Ship/Program.cs
index f783bbe..9617a2e 100644
--- a/Ship/Ship/Program.cs
+++ b/Ship/Ship/Program.cs
@@ -1,3 +1,9 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Serilog;
+using System.ServiceProcess;
+
namespace Ship
{
internal static class Program
@@ -11,7 +17,31 @@ namespace Ship
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
- Application.Run(new FormMapWithSetShips());
+ 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)
+ .CreateLogger();
+
+ option.SetMinimumLevel(LogLevel.Information);
+ option.AddSerilog(logger);
+
+ });
}
}
}
\ No newline at end of file
diff --git a/Ship/Ship/SetShipsGeneric.cs b/Ship/Ship/SetShipsGeneric.cs
index 04a95e3..0d11df5 100644
--- a/Ship/Ship/SetShipsGeneric.cs
+++ b/Ship/Ship/SetShipsGeneric.cs
@@ -45,7 +45,12 @@ namespace Ship
///
public int Insert(T ship, int position)
{
- if (position > _maxCount || Count == _maxCount || position < 0) return -1;
+ if (Count == _maxCount)
+ {
+ throw new StorageOverflowException(_maxCount);
+ }
+
+ if (position > _maxCount || position < 0) return -1;
_places.Insert(position, ship);
return position;
@@ -64,6 +69,11 @@ namespace Ship
var result = _places[position];
+ if (result == null)
+ {
+ throw new ShipNotFoundException(position);
+ }
+
_places.RemoveAt(position);
return result;
}
diff --git a/Ship/Ship/Ship.csproj b/Ship/Ship/Ship.csproj
index 13ee123..d3b7c95 100644
--- a/Ship/Ship/Ship.csproj
+++ b/Ship/Ship/Ship.csproj
@@ -8,6 +8,19 @@
enable
+
+
+
+
+
+
+
+
+
+
+
+
+
True
@@ -23,4 +36,6 @@
+
+
\ No newline at end of file
diff --git a/Ship/Ship/ShipNotFoundException.cs b/Ship/Ship/ShipNotFoundException.cs
new file mode 100644
index 0000000..84b3394
--- /dev/null
+++ b/Ship/Ship/ShipNotFoundException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace Ship
+{
+ [Serializable]
+ internal class ShipNotFoundException : ApplicationException
+ {
+ public ShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
+ public ShipNotFoundException() : base() { }
+ public ShipNotFoundException(string message) : base(message) { }
+ public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
+ protected ShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
+ }
+}
\ No newline at end of file
diff --git a/Ship/Ship/StorageOverflowException.cs b/Ship/Ship/StorageOverflowException.cs
new file mode 100644
index 0000000..b388aef
--- /dev/null
+++ b/Ship/Ship/StorageOverflowException.cs
@@ -0,0 +1,14 @@
+using System.Runtime.Serialization;
+
+namespace Ship
+{
+ [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) { }
+ }
+}
\ No newline at end of file
diff --git a/Ship/Ship/appsettings.json b/Ship/Ship/appsettings.json
new file mode 100644
index 0000000..fb814f9
--- /dev/null
+++ b/Ship/Ship/appsettings.json
@@ -0,0 +1,17 @@
+{
+ "Serilog": {
+ "Using": [ "Serilog.Sinks.File" ],
+ "MinimumLevel": "Information",
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "Logs/log_.log",
+ "rollingInterval": "Day",
+ "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
+ }
+}
\ No newline at end of file