PIbd-23 Yakobchuk S.V. LabWork_07 #8

Closed
sofia7ya wants to merge 4 commits from LabWork_07 into LabWork_06
11 changed files with 194 additions and 172 deletions
Showing only changes of commit 3331db9236 - Show all commits

View File

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

View File

@ -37,9 +37,6 @@ namespace Sailboat.Generics
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats();
/// <summary>
/// Конструктор
@ -74,13 +71,13 @@ namespace Sailboat.Generics
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(BoatsGenericCollection<T, U> collect, int pos)
public static T? operator -(BoatsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return false;
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
@ -134,6 +131,8 @@ namespace Sailboat.Generics
if (boat != null)
{
int width = _pictureWidth / _placeSizeWidth;
boat._pictureWidth = _pictureWidth;
boat._pictureHeight = _pictureHeight;
boat.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight);
boat.DrawTransport(g);
}

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat.Generics
{
@ -46,8 +47,7 @@ namespace Sailboat.Generics
/// <param name="pictureHeight"></param>
public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{
_boatStorages = new Dictionary<string,
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_boatStorages = new Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -80,8 +80,7 @@ namespace Sailboat.Generics
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>?
this[string ind]
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
{
get
{
@ -97,12 +96,14 @@ namespace Sailboat.Generics
/// Сохранение информации по лодкам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
public bool SaveData(string filename)
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{
@ -112,72 +113,75 @@ namespace Sailboat.Generics
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
throw new InvalidOperationException("Файл не найден, невалидная операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"SailboatStorage{Environment.NewLine}{data}");
writer.WriteLine("BoatStorage");
writer.Write(data.ToString());
}
return true;
}
/// <summary>
/// Загрузка информации по лодкам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка призагрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
using (StreamReader reader = new StreamReader(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
string checker = reader.ReadLine();
if (checker == null)
throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("BoatStorage"))
{
throw new Exception("Нет данных для загрузки");
}
if (!str.StartsWith("BoatStorage"))
{
throw new Exception("Неверный формат данных");
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
}
_boatStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
throw new NullReferenceException("Нет данных для загрузки");
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
break;
firstinit = false;
string name = strs.Split('|')[0];
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
foreach (string data in strs.Split('|')[1].Split(';'))
{
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
DrawingBoat? vehicle = data?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle != null)
{
if (!(collection + boat))
try
{
throw new Exception("Ошибка добавления в коллекцию");
_ = collection + vehicle;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_boatStorages.Add(record[0], collection);
_boatStorages.Add(name, collection);
}
return true;
}
}
}

View File

@ -15,8 +15,8 @@ namespace Sailboat.DrawingObjects
public class DrawingBoat
{
public EntityBoat? EntityBoat { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
public int _pictureWidth;
public int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private readonly int _boatWidth = 185;

View File

@ -1,21 +1,18 @@
using Microsoft.Extensions.Logging;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Metrics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Serilog;
using Microsoft.Extensions.Logging;
using Sailboat.DrawingObjects;
using Sailboat.Exceptions;
using Sailboat.Generics;
using Sailboat.MovementStrategy;
using Sailboat.Exceptions;
namespace Sailboat
{
@ -23,7 +20,7 @@ namespace Sailboat
{
private readonly BoatsGenericStorage _storage;
private readonly ILogger _logger;
public FormBoatCollection()
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
@ -34,12 +31,10 @@ namespace Sailboat
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
@ -55,46 +50,63 @@ namespace Sailboat
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Коллекция не выбрана");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormBoatConfig form = new FormBoatConfig(pictureBoxCollection.Width, pictureBoxCollection.Height);
form.Show();
Action<DrawingBoat>? boatDelegate = new((plane) =>
var formBoatConfig = new FormBoatConfig();
formBoatConfig.AddEvent(AddBoat);
formBoatConfig.Show();
}
private void AddBoat(DrawingBoat drawingBoat)
{
if (listBoxStorages.SelectedIndex == -1)
{
if (obj + plane)
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if (obj + drawingBoat)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Объект {obj.GetType()} добавлен");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
});
form.AddEvent(boatDelegate);
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
}
}
private void buttonRemoveBoat_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
@ -103,16 +115,19 @@ namespace Sailboat
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos}");
pictureBoxCollection.Image = obj.ShowBoats();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (BoatNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
@ -135,13 +150,14 @@ namespace Sailboat
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
@ -154,15 +170,17 @@ namespace Sailboat
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects(); ;
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
_logger.LogWarning("Отмена удаления набора");
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
@ -172,13 +190,13 @@ namespace Sailboat
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
@ -190,20 +208,14 @@ namespace Sailboat
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}

View File

@ -1,6 +1,4 @@
using Sailboat.DrawingObjects;
using Sailboat.Entities;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -10,18 +8,19 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sailboat.DrawingObjects;
using Sailboat.Generics;
using Sailboat.MovementStrategy;
using Sailboat.Entities;
namespace Sailboat
{
public partial class FormBoatConfig : Form
{
DrawingBoat? _boat = null;
private event Action<DrawingBoat>? EventAddBoat;
public int _pictureWidth { get; private set; }
public int _pictureHeight { get; private set; }
public FormBoatConfig(int pictureWidth, int pictureHeight)
public FormBoatConfig()
{
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
@ -68,7 +67,6 @@ namespace Sailboat
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
@ -85,12 +83,14 @@ namespace Sailboat
{
case "labelSimpleObject":
_boat = new DrawingBoat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, _pictureWidth, _pictureHeight);
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_boat = new DrawingSailboat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxHull.Checked,
checkBoxSail.Checked, _pictureWidth, _pictureHeight);
checkBoxSail.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawBoat();

View File

@ -2,9 +2,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace Sailboat
{
@ -16,25 +13,31 @@ namespace Sailboat
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
pathNeed += path[i] + "\\";
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}debug.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormBoatCollection());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -1,33 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,16 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Sailboat.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception)

View File

@ -0,0 +1,20 @@
{
"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" ],
"Properties": {
"Application": "Sailboat"
}
}
}

View File

@ -1,15 +0,0 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.txt" }
}
],
"Properties": {
"Application": "Sample"
}
}
}