Youdakova D.R. PIbd-21 LabWork07 #7

Closed
Daniya_Youdakova wants to merge 6 commits from LabWork07 into LabWork06
15 changed files with 206 additions and 72 deletions

View File

@ -70,6 +70,7 @@ namespace AircraftCarrier
yNumOfCells = (int)Math.Ceiling(_drawningObject.Step / _size_y);
xObjOffset = (int)(Left / _size_x);
yObjOffset = (int)Math.Ceiling(Bottom / _size_y);
for (int i = 0; i < yNumOfCells; i++)
{
if (!roadIsClear)
@ -90,6 +91,7 @@ namespace AircraftCarrier
}
}
break;
case Direction.Left:
xNumOfCells = (int)Math.Ceiling(_drawningObject.Step / _size_x);
yNumOfCells = (int)Math.Ceiling((Bottom - Top) / _size_y);
@ -116,6 +118,7 @@ namespace AircraftCarrier
}
}
break;
case Direction.Right:
xNumOfCells = (int)Math.Ceiling(_drawningObject.Step / _size_x);
yNumOfCells = (int)Math.Ceiling((Bottom - Top) / _size_y);
@ -162,6 +165,7 @@ namespace AircraftCarrier
int yNumOfCells = (int)Math.Ceiling(Bottom / _size_y) - (int)Math.Floor(Top / _size_y);
int xObjOffset = (int)(x / _size_x);
int yObjOffset = (int)(y / _size_y);
while (y < _height - (Bottom - Top))
{
while (x < _width - (Right - Left))

View File

@ -8,6 +8,29 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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.Extensions.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
[Serializable]
internal class AircraftCarrierNotFoundException: ApplicationException
{
public AircraftCarrierNotFoundException(int i) : base($"Не найден объект по позиции{ i}") { }
public AircraftCarrierNotFoundException() : base() { }
public AircraftCarrierNotFoundException(string message) : base(message) { }
public AircraftCarrierNotFoundException(string message, Exception exception) : base(message, exception)
{ }
protected AircraftCarrierNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -52,6 +52,7 @@ namespace AircraftCarrier
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeigth = height;
}
@ -126,17 +127,16 @@ namespace AircraftCarrier
{
_startPosX = _pictureWidth.Value - _aircraftcarrierWidth;
}
if (_startPosY + _aircraftcarrierHeight > _pictureHeigth)
{
_startPosY = _pictureHeigth.Value - _aircraftcarrierHeight;
}
}
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosY, _startPosX + _aircraftcarrierWidth, _startPosY + _aircraftcarrierHeight);
}
public void ReturnColor(Color returnColor)
{
if (AircraftCarrier is not EntityModernAircraftCarrier modernAircraftCarrier)

View File

@ -30,8 +30,7 @@ namespace AircraftCarrier
{
_aircraftcarrier.DrawTransport(g);
}
public string GetInfo() => _aircraftcarrier?.AircraftCarrier.ToString();
public string GetInfo() => _aircraftcarrier?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectAircraftCarrier(data.CreateDrawningAircraftCarrier());
}
}

View File

@ -8,7 +8,6 @@ namespace AircraftCarrier
{
public class EntityAircraftCarrier
{
private static readonly char _separatorForObject = ':';
public int Speed { get; private set; }
public float Weight { get; private set; }
public Color BodyColor { get; set; }
@ -20,10 +19,5 @@ namespace AircraftCarrier
Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor;
}
public override string ToString()
{
var str = $"{Speed}{_separatorForObject}{Weight}{_separatorForObject}{BodyColor.Name}";
return str;
}
}
}

View File

@ -4,13 +4,11 @@ using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using static System.Reflection.Metadata.BlobBuilder;
namespace AircraftCarrier
{
internal class EntityModernAircraftCarrier : EntityAircraftCarrier
{
private static readonly char _separatorForObject = ':';
public Color DopColor { get; set; }
public bool FlightDeck { get; private set; }
public bool HangarDeck { get; private set; }
@ -22,10 +20,5 @@ namespace AircraftCarrier
HangarDeck = hangarDeck;
Route = route;
}
public override string ToString()
{
var str = base.ToString();
return $"{str}{_separatorForObject}{DopColor.Name}{_separatorForObject}{FlightDeck}{_separatorForObject}{HangarDeck}{_separatorForObject}{Route}";
}
}
}

View File

@ -62,7 +62,6 @@ namespace AircraftCarrier
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -24,9 +25,11 @@ _mapAircraftCarriersCollectionGeneric;
{ "Сложная карта", new ComplexMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetAircraftCarriers()
private readonly ILogger _logger;
public FormMapWithSetAircraftCarriers(ILogger<FormMapWithSetAircraftCarriers> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width,
pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
@ -61,27 +64,32 @@ pictureBox.Height);
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation("Не все данные были заполнены при добавлении карты");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogInformation($"Нет карты с названием: {comboBoxSelectorMap.Text}");
return;
}
if (textBoxNewMapName.Text.Contains('|') || textBoxNewMapName.Text.Contains(':') || textBoxNewMapName.Text.Contains(';'))
{
MessageBox.Show("Присутствуют недопустимые символы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation($"В названии карты присутствуют недопустимые символы: {textBoxNewMapName.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
@ -95,6 +103,7 @@ pictureBox.Height);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ??
string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
}
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
@ -129,48 +138,67 @@ pictureBox.Height);
}
private void AddAircraftCarrier(DrawningAircraftCarrier drawningAircraftCarrier)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawningObjectAircraftCarrier aircraftcarrier = new(drawningAircraftCarrier);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + aircraftcarrier != -1)
{
_logger.LogInformation($"Добавлен объект {aircraftcarrier}");
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation($"Не удалось добавить объект {aircraftcarrier}");
MessageBox.Show("Не удалось добавить объект");
}
}
DrawningObjectAircraftCarrier aircraftcarrier = new(drawningAircraftCarrier);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + aircraftcarrier != -1)
catch (StorageOverflowException ex)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonRemoveAircraftCarrier_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 = _mapAircraftCarriersCollectionGeneric.ShowSet();
var delAircraftCarrier = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (delAircraftCarrier != null)
{
_logger.LogInformation($"Объект {delAircraftCarrier} удалён");
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation($"Не удалось удалить объект по позиции {pos}");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (AircraftCarrierNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка удаления: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void buttonShowStorage_Click(object sender, EventArgs e)
{
@ -219,30 +247,35 @@ string.Empty] - pos != null)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.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);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Успешная загрузка в файл {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -184,8 +184,10 @@ namespace AircraftCarrier
{
int yNumOfPlaces = _pictureHeight / _placeSizeHeight;
int xNumOfPlaces = _pictureWidth / _placeSizeWidth;
int rowNum = yNumOfPlaces - 1;
int columnNum = 0;
for (int i = 0; i < _setAircraftCarriers.Count; i++)
{
if (_setAircraftCarriers[i] != null)

View File

@ -34,7 +34,7 @@ namespace AircraftCarrier
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,MapWithSetAircraftCarriersGeneric<IDrawningObject, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetAircraftCarriersGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -94,7 +94,7 @@ namespace AircraftCarrier
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -108,18 +108,18 @@ namespace AircraftCarrier
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
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("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@ -127,7 +127,7 @@ namespace AircraftCarrier
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new FileFormatException("Формат данных в файле неправильный");
}
//очищаем записи
_mapStorages.Clear();
@ -148,7 +148,6 @@ namespace AircraftCarrier
_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 AircraftCarrier;
using Serilog;
namespace AircraftCarrier
{
internal static class Program
@ -11,7 +17,31 @@ namespace AircraftCarrier
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetAircraftCarriers());
var services = new ServiceCollection();
ConfigureServices(services);
//Application.Run(new FormMapWithSetAircraftCarriers());
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetAircraftCarriers>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetAircraftCarriers>()
.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);
});
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
@ -46,16 +47,16 @@ namespace AircraftCarrier
/// <returns></returns>
public int Insert(T AircraftCarrier, int position)
{
// проверка позиции
if (!CorrectPos(position))
// TODO проверка позиции
if (Count == _maxCount)
{
return -1;
throw new StorageOverflowException(_maxCount);
}
// вставка по позиции
if (position < 0 || position > _maxCount) return -1;
// TODO вставка по позиции
_places.Insert(position, AircraftCarrier);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
@ -63,13 +64,14 @@ namespace AircraftCarrier
/// <returns></returns>
public T Remove(int position)
{
// проверка позиции
if (!CorrectPos(position))
return null;
// удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
// TODO проверка позиции
if (position >= Count || position < 0)
{
throw new AircraftCarrierNotFoundException(position);
}
T aircraftcarrier = _places[position];
_places.RemoveAt(position);
return temp;
return aircraftcarrier;
}
/// <summary>
/// Получение объекта из набора по позиции

View 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 AircraftCarrier
{
[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,14 @@
{
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "./Logs/program_log.log",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}