Лёвушкина Анна, ПИбд-21, лаб7 простая #14

Closed
AnnaLioness wants to merge 4 commits from лаб7 into лаб6
9 changed files with 194 additions and 44 deletions

View File

@ -1,5 +1,6 @@
using Lab1ContainersShip.DrawingObjects; using Lab1ContainersShip.DrawingObjects;
using Lab1ContainersShip.MovementStrategy; using Lab1ContainersShip.MovementStrategy;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -9,16 +10,19 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq;
namespace Lab1ContainersShip namespace Lab1ContainersShip
{ {
public partial class FormShipCollection : Form public partial class FormShipCollection : Form
{ {
private readonly ShipGenericStorage _storage; private readonly ShipGenericStorage _storage;
public FormShipCollection() private readonly ILogger _logger;
public FormShipCollection(ILogger<FormShipCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new ShipGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new ShipGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void FormShipCollection_Load(object sender, EventArgs e) private void FormShipCollection_Load(object sender, EventArgs e)
@ -48,10 +52,13 @@ namespace Lab1ContainersShip
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: { textBoxStorageName.Text} ");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender,EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender,EventArgs e)
{ {
@ -88,17 +95,24 @@ namespace Lab1ContainersShip
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) if (obj == null)
{ {
_logger.LogWarning("Добавление пустого объекта");
return; return;
} }
try
if ((obj + drawningShip) != -1)
{ {
_ = obj + drawningShip;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString()}");
} }
else catch (ApplicationException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorages.SelectedItem.ToString()}");
} }
} }
@ -121,14 +135,23 @@ namespace Lab1ContainersShip
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null) try
{
if (obj - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"Удален объект из набора {listBoxStorages.SelectedItem.ToString()}");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (ShipNotFoundException ex)
{
MessageBox.Show(ex.Message);
} }
} }
@ -139,8 +162,7 @@ namespace Lab1ContainersShip
{ {
return; return;
} }
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string.Empty];
if (obj == null) if (obj == null)
{ {
return; return;
@ -160,6 +182,7 @@ namespace Lab1ContainersShip
_storage.DelSet(listBoxStorages.SelectedItem.ToString() _storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {listBoxStorages.SelectedItem}");
} }
} }
@ -167,15 +190,16 @@ namespace Lab1ContainersShip
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
} }
} }
} }
@ -184,18 +208,21 @@ namespace Lab1ContainersShip
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
ReloadObjects(); _storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} _logger.LogWarning($"Не удалось загрузить наборы с ошибкой: {ex.Message}");
} }
}
ReloadObjects();
} }
} }
} }

View File

@ -8,6 +8,18 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" /> <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<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="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" 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" />
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" /> <PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -1,8 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Lab1ContainersShip.Properties;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace Lab1ContainersShip namespace Lab1ContainersShip
{ {
@ -14,9 +24,36 @@ namespace Lab1ContainersShip
[STAThread] [STAThread]
static void Main() static void Main()
{ {
Application.EnableVisualStyles(); // To customize application configuration such as set high DPIsettings or default font,
Application.SetCompatibleTextRenderingDefault(false); // see https://aka.ms/applicationconfiguration.
Application.Run(new FormShipCollection()); ApplicationConfiguration.Initialize();
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}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
} }

View File

@ -39,7 +39,9 @@ namespace Lab1ContainersShip
// TODO вставка в начало набора // TODO вставка в начало набора
if(_places.Count >= _maxCount) if(_places.Count >= _maxCount)
{ {
throw new StorageOverflowException();
return -1; return -1;
} }
else else
{ {
@ -65,11 +67,11 @@ namespace Lab1ContainersShip
// TODO вставка по позиции // TODO вставка по позиции
if(_places.Count >= _maxCount) if(_places.Count >= _maxCount)
{ {
return false; throw new StorageOverflowException(position);
} }
if(position < 0 || position > _places.Count) if(position < 0 || position > _places.Count)
{ {
return false; throw new ShipNotFoundException(position);
} }
if(position == _places.Count) if(position == _places.Count)
{ {
@ -91,14 +93,14 @@ namespace Lab1ContainersShip
// TODO проверка позиции // TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива // TODO удаление объекта из массива, присвоив элементу массива
//значение null //значение null
if(position < _places.Count && _places.Count < _maxCount) if(position < _places.Count)
{ {
_places[position] = null; _places.RemoveAt(position);
return true; return true;
} }
else else
{ {
return false; throw new ShipNotFoundException(position);
} }
} }
@ -135,7 +137,14 @@ namespace Lab1ContainersShip
set set
{ {
try
{
Insert(value, position); Insert(value, position);
}
catch
{
return;
}
} }
} }

View File

@ -61,6 +61,7 @@ namespace Lab1ContainersShip
return -1; return -1;
} }
return collect?._collection.Insert(obj) ?? -1; return collect?._collection.Insert(obj) ?? -1;
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания

View File

@ -111,7 +111,7 @@ DrawningObjectShip>>();
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при /// <returns>true - сохранение прошло успешно, false - ошибка при
//сохранении данных</returns> //сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -130,13 +130,13 @@ public bool SaveData(string filename)
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using(StreamWriter sr = new StreamWriter(filename)) using(StreamWriter sr = new StreamWriter(filename))
{ {
sr.Write($"ShipStorage{Environment.NewLine}{data}"); sr.Write($"ShipStorage{Environment.NewLine}{data}");
} }
return true; return;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
@ -144,22 +144,23 @@ public bool SaveData(string filename)
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при /// <returns>true - загрузка прошла успешно, false - ошибка при
///загрузке данных</returns> ///загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = new StreamReader(filename)) using (StreamReader sr = new StreamReader(filename))
{ {
string str = sr.ReadLine(); string str = sr.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new NullReferenceException("Нет данных для загрузки");
} }
if (!str.StartsWith("ShipStorage")) if (!str.StartsWith("ShipStorage"))
{ {
return false; throw new FormatException("Неверный формат данных");
} }
_shipStorages.Clear(); _shipStorages.Clear();
str = sr.ReadLine(); str = sr.ReadLine();
@ -179,16 +180,19 @@ public bool SaveData(string filename)
elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight); elem?.CreateDrawingShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null) if (ship != null)
{ {
if (collection + ship == -1) try
{ {
return false; int t = collection + ship;
}
catch (ApplicationException ex)
{
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
} }
} }
} }
_shipStorages.Add(record[0], collection); _shipStorages.Add(record[0], collection);
} }
} }
return true;
} }
} }

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 Lab1ContainersShip
{
[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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Lab1ContainersShip
{
[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": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "ContainerShip"
}
}
}