Lab7
This commit is contained in:
parent
f711e6df7a
commit
c839a502da
@ -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
|
||||
/// </summary>
|
||||
private readonly MapsCollection _mapsCollection;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Объект от класса карты с набором объектов
|
||||
/// </summary>
|
||||
private MapWithSetShipsGeneric<DrawingObject, AbstractMap> _mapShipsCollectionGeneric;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormMapWithSetShips()
|
||||
public FormMapWithSetShips(ILogger<FormMapWithSetShips> 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();
|
||||
}
|
||||
/// <summary>
|
||||
@ -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);
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление карты
|
||||
@ -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}");
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Вывод набора
|
||||
@ -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();
|
||||
|
@ -80,7 +80,7 @@ namespace Ship
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
/// <returns></returns>
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -98,18 +98,17 @@ namespace Ship
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка нформации по автомобилям на парковках из файла
|
||||
/// </summary>
|
||||
/// <param name="filename"></param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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<FormMapWithSetShips>());
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormMapWithSetShips>().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);
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -45,7 +45,12 @@ namespace Ship
|
||||
/// <returns></returns>
|
||||
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;
|
||||
}
|
||||
|
@ -8,6 +8,19 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
|
||||
<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.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.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>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
@ -23,4 +36,6 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties appconfig_1json__JsonSchema="https://json.schemastore.org/appsettings.json" /></VisualStudio></ProjectExtensions>
|
||||
|
||||
</Project>
|
14
Ship/Ship/ShipNotFoundException.cs
Normal file
14
Ship/Ship/ShipNotFoundException.cs
Normal file
@ -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) { }
|
||||
}
|
||||
}
|
14
Ship/Ship/StorageOverflowException.cs
Normal file
14
Ship/Ship/StorageOverflowException.cs
Normal file
@ -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) { }
|
||||
}
|
||||
}
|
17
Ship/Ship/appsettings.json
Normal file
17
Ship/Ship/appsettings.json
Normal file
@ -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" ]
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user