PIbd22_NikiforovaMV_lab7 #7

Closed
Michelty wants to merge 1 commits from lab7 into lab6
11 changed files with 235 additions and 49 deletions

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -8,19 +8,25 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ContainerShip.MovementStrategy;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using ContainerShip.DrawningObjects;
using ContainerShip.Generic;
using ContainerShip.Exceptions;
namespace ContainerShip
{
public partial class FormShipCollection : Form
{
private readonly ShipsGenericStorage _storage;
private readonly ILogger _logger;
public FormShipCollection()
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
@ -43,12 +49,12 @@ namespace ContainerShip
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@ -60,10 +66,12 @@ namespace ContainerShip
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удалён набор: {name}");
}
}
@ -75,7 +83,7 @@ namespace ContainerShip
}
private void AddShip(DrawningShip selectedShip)
private void AddShip(DrawningShip _ship)
{
if (listBoxStorages.SelectedIndex == -1)
{
@ -87,15 +95,24 @@ namespace ContainerShip
{
return;
}
selectedShip.ChangeBordersPicture(pictureBoxCollection.Width, pictureBoxCollection.Height);
if (obj + selectedShip != -1)
_ship.ChangeBordersPicture(Width, Height);
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips();
if (obj + _ship != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Добавлен объект: {_ship.EntityShip.BodyColor}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
@ -105,29 +122,42 @@ namespace ContainerShip
{
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)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Удалён объект по позиции : {pos}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (FormatException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Неверный формат ввода");
_logger.LogWarning("Неверный формат ввода");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning(ex.Message);
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
@ -142,36 +172,43 @@ namespace ContainerShip
}
pictureBoxCollection.Image = obj.ShowShips();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл сохранён по пути: {saveFileDialog.FileName}");
}
else
catch (InvalidOperationException ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
ReloadObjects();
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
pictureBoxCollection.Image = obj.ShowShips();
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Файл загружен по пути: {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
}
ReloadObjects();
}
}
}

View File

@ -6,7 +6,15 @@ namespace ContainerShip
public partial class FormShips : Form
{
private DrawningShip? _drawningShip;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// </summary>
/// Âûáðàííûé êîðàáëü
/// </summary>
public DrawningShip? SelectedShip { get; private set; }
public FormShips()
@ -27,10 +35,17 @@ namespace ContainerShip
_drawningShip.DrawTransport(gr);
pictureBoxShips.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êîíòåéíåðîâîç"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateContainerShip_Click(object sender, EventArgs e)
{
Random random = new Random();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
@ -38,6 +53,7 @@ namespace ContainerShip
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð äîïîëíèòåëüíîãî öâåòà
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
@ -50,10 +66,17 @@ namespace ContainerShip
_drawningShip.SetPosition(random.Next(10, 200), random.Next(10, 200));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü êîðàáëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateShip_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
@ -90,6 +113,12 @@ namespace ContainerShip
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
@ -132,6 +161,7 @@ namespace ContainerShip
SelectedShip = _drawningShip;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
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 FormShipCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().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}serilog.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContainerShip.Exceptions;
namespace ContainerShip.Generic
{
@ -19,26 +20,28 @@ namespace ContainerShip.Generic
}
public int Insert(T ship)
{
_places.Insert(0, ship);
return 0;
return Insert(ship, 0);
}
public bool Insert(T ship, int position)
public int Insert(T ship, int position)
{
if (position < 0 || position >= Count || Count >= _maxCount)
if (Count >= _maxCount)
{
return false;
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new IndexOutOfRangeException("Индекс вне границ коллекции");
}
_places.Insert(position, ship);
return true;
return 0;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
throw new ShipNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}
public T? this[int position]

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
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 context) : base(info, context) { }
}
}

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using ContainerShip.Generic;
using ContainerShip.MovementStrategy;
using ContainerShip.DrawningObjects;
using ContainerShip.Exceptions;
namespace ContainerShip.Generic
{
@ -13,6 +14,7 @@ namespace ContainerShip.Generic
where T : DrawningShip
where U : IMoveableObject
{
public int count => _collection.Count;
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 210;
@ -38,7 +40,7 @@ namespace ContainerShip.Generic
{
if (collect._collection[pos] == null)
{
return false;
throw new ShipNotFoundException(pos);
}
return collect?._collection.Remove(pos) ?? false;
}
@ -78,7 +80,6 @@ namespace ContainerShip.Generic
for (int i = 0; i < _collection.Count; i++)
{
// TODO получение объекта
DrawningShip _ship = _collection[i];
if (_ship != null) {
if (x < 0)

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using ContainerShip.MovementStrategy;
using ContainerShip.DrawningObjects;
using ContainerShip.Entities;
namespace ContainerShip.Generic
{
@ -48,6 +49,11 @@ namespace ContainerShip.Generic
}
public bool SaveData(string filename)
{
if (_shipStorages.Count == 0)
{
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
@ -56,9 +62,15 @@ namespace ContainerShip.Generic
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine($"ShipStorage");
foreach (var record in _shipStorages)
{
StringBuilder records = new();
if (record.Value.count <= 0)
{
throw new InvalidOperationException("Невалидная операция, нет данных для сохранения");
}
foreach (DrawningShip? elem in record.Value.GetShip)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
@ -66,31 +78,40 @@ namespace ContainerShip.Generic
sw.WriteLine($"{record.Key}{_separatorForKeyValue}{records}");
}
}
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException($"Файл {filename} не найден");
}
using (StreamReader sr = File.OpenText(filename))
{
string? curLine = sr.ReadLine();
if (curLine == null || !curLine.Contains("ShipStorage"))
if (curLine == null || curLine.Length == 0 || !curLine.StartsWith("ShipStorage"))
{
return false;
throw new ArgumentException("Неверный формат данных");
}
_shipStorages.Clear();
curLine = sr.ReadLine();
if (curLine == null || curLine.Length == 0)
{
throw new ArgumentException("Нет данных");
}
while (curLine != null)
{
if (!curLine.Contains(_separatorRecords))
{
throw new ArgumentException("Коллекция пуста");
}
string[] record = curLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
ShipsGenericCollection<DrawningShip, DrawingObjectShip> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
@ -100,7 +121,7 @@ namespace ContainerShip.Generic
{
if (collection + ship == -1)
{
return false;
throw new InvalidOperationException("Невалидная операция, ошибка добавления в коллекцию");
}
}
}

View File

@ -6,9 +6,6 @@ using System.Threading.Tasks;
namespace ContainerShip.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ContainerShip.Exceptions
{
[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 context) : base(info, context) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/carlog.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ContainerShip"
}
}
}