Markov D.P. LabWork07 #10

Closed
khehelk wants to merge 1 commits from LabWork07 into LabWork06
8 changed files with 203 additions and 55 deletions
Showing only changes of commit 8062cf5a60 - Show all commits

View File

@ -8,6 +8,18 @@
<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="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>

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -20,10 +21,12 @@ namespace ContainerShip
};
private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
public FormMapWithSetShip()
public FormMapWithSetShip(ILogger<FormMapWithSetShip> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach(var elem in _mapsDict)
@ -50,7 +53,7 @@ namespace ContainerShip
listBoxMaps.SelectedIndex = index;
}
}
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 ||
@ -58,17 +61,22 @@ namespace ContainerShip
{
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.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ButtonAddShip_Click(object sender, EventArgs e)
@ -80,48 +88,76 @@ namespace ContainerShip
private void AddShip(DrawingShip ship)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectShip objectShip = new(ship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1)
{
MessageBox.Show("Object added");
_logger.LogInformation("Добавлен корабль {@Ship}", ship);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Failed to add object");
_logger.LogInformation("Не удалось добавить объект");
}
}
DrawingObjectShip objectShip = new(ship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + objectShip != -1)
catch (StorageOverflowException ex)
{
MessageBox.Show("Object added");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogWarning("Ошибка хранилище переполнено: {0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
catch (ArgumentException ex)
{
MessageBox.Show("Failed to add object");
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Ship}", ex.Message, ship);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
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("Из текущей карты удалён объект {@Ship}", pos);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект не существует", pos);
}
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
@ -171,6 +207,7 @@ namespace ContainerShip
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);
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
@ -181,6 +218,7 @@ namespace ContainerShip
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ??
string.Empty);
ReloadMaps();
@ -190,15 +228,18 @@ namespace ContainerShip
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Файл {0} сохранен", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}': {1}", saveFileDialog.FileName, ex.Message);
}
}
}
@ -206,14 +247,17 @@ namespace ContainerShip
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
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);
}
}
}

View File

@ -73,41 +73,48 @@ namespace ContainerShip
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))
{
bool isFirst = true;
string str;
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
while ((str = sr.ReadLine()) != null)
{
return false;
}
_mapStorages.Clear();
while((str = sr.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
if (isFirst)
{
case "SimpleMap":
map = new SimpleMap();
break;
case "IslandsMap":
map = new IslandsMap();
break;
case "RocksMap":
map = new RocksMap();
break;
if (!str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
isFirst = false;
}
else
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "Простая карта":
map = new SimpleMap();
break;
case "Острова":
map = new IslandsMap();
break;
case "Скалы":
map = new RocksMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetShipGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
_mapStorages.Add(elem[0], new MapWithSetShipGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ContainerShip
{
internal static class Program
@ -11,7 +17,30 @@ namespace ContainerShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetShip());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetShip>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetShip>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -9,7 +9,6 @@ namespace ContainerShip
internal class SetShipGeneric<T>
where T : class
{
private readonly List<T> _places;
public int Count => _places.Count;
@ -31,7 +30,7 @@ namespace ContainerShip
{
if (position < 0 || position > Count || Count == _maxCount)
{
return -1;
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, ship);
return position;
@ -41,7 +40,7 @@ namespace ContainerShip
{
if (position >= Count || position < 0)
{
return null;
throw new ShipNotFoundException(position);
}
T removedObject = _places[position];
_places.RemoveAt(position);

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ContainerShip
{
[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) { }
}
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ContainerShip
{
[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

@ -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": "ContainerShip"
}
}
}