Сделанная 7 лабораторная

This commit is contained in:
Максим Яковлев 2023-12-06 22:19:11 +04:00
parent a55d9450cf
commit 4b736d3233
9 changed files with 205 additions and 44 deletions

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
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() : base() { }
public BoatNotFoundException(string message) : base(message) { }
public BoatNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BoatNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SailBoat.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

@ -10,6 +10,9 @@ 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 SailBoat.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace SailBoat namespace SailBoat
{ {
@ -17,10 +20,13 @@ namespace SailBoat
{ {
private readonly BoatsGenericStorage _storage; private readonly BoatsGenericStorage _storage;
public FormBoatCollection() private readonly ILogger _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
} }
private void ReloadObjects() private void ReloadObjects()
@ -48,10 +54,12 @@ namespace SailBoat
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"!!Ошибка!! Не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e) private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
@ -63,12 +71,15 @@ namespace SailBoat
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
_logger.LogWarning($"Удаление не выбранного набора");
return; return;
} }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
@ -78,16 +89,27 @@ namespace SailBoat
boat._pictureHeight = pictureBoxCollection.Height; boat._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1) return; if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (obj == null) return; if (obj == null) return;
if (obj + boat) try
{ {
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats(); if (obj + boat)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"В набор {name} добавлен объект");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
} }
else catch(StorageOverflowException ex) {
{ MessageBox.Show(ex.Message);
MessageBox.Show("Не удалось добавить объект"); _logger.LogWarning($"{ex.Message}. Не удалось добавить объект");
} }
} }
@ -106,6 +128,7 @@ namespace SailBoat
{ {
if (listBoxStorages.SelectedIndex == -1) return; if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (obj == null) return; if (obj == null) return;
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
@ -114,14 +137,23 @@ namespace SailBoat
} }
if (maskedTextBoxNumber.Text == "") { return; } if (maskedTextBoxNumber.Text == "") { return; }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos) try
{ {
MessageBox.Show("Объект удален"); if (obj - pos != null)
pictureBoxCollection.Image = obj.ShowBoats(); {
} MessageBox.Show("Объект удален");
else pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Из набора {name} удален объект");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
}
} catch(BoatNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось удалить объект");
} }
} }
@ -137,13 +169,16 @@ namespace SailBoat
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение");
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка сохранения");
} }
} }
} }
@ -152,14 +187,17 @@ namespace SailBoat
{ {
if(openFileDialog.ShowDialog() == DialogResult.OK) if(openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
ReloadObjects(); ReloadObjects();
MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка");
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки");
} }
} }
} }

View File

@ -38,16 +38,13 @@ namespace SailBoat.Generics
return collect._collection.Insert(obj); return collect._collection.Insert(obj);
} }
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]; T? obj = collect._collection[pos];
if(obj == null)
{
return false;
}
collect._collection.Remove(pos); collect._collection.Remove(pos);
return true; return obj;
} }
public U? GetU(int pos) public U? GetU(int pos)
{ {

View File

@ -75,7 +75,7 @@ namespace SailBoat.Generics
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using StreamWriter fs = new StreamWriter(filename); using StreamWriter fs = new StreamWriter(filename);
@ -88,25 +88,25 @@ namespace SailBoat.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader fs = new StreamReader(filename)) using (StreamReader fs = new StreamReader(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if(str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("BoatStorage")) if (!str.StartsWith("BoatStorage"))
{ {
return false; throw new FormatException("Неверный формат данных");
} }
_boatStorages.Clear(); _boatStorages.Clear();
while ((str = fs.ReadLine()) != null) while ((str = fs.ReadLine()) != null)
{ {
if (str.Length == 0)
{
return false;
}
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2) if (record.Length != 2)
{ {
@ -122,7 +122,7 @@ namespace SailBoat.Generics
{ {
if (!(collection + boat)) if (!(collection + boat))
{ {
return false; throw new ApplicationException("Ошибка добавления в коллекцию");
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using SailBoat.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -30,11 +31,11 @@ namespace SailBoat.Generics
{ {
if (position < 0 || position >= _maxCount) if (position < 0 || position >= _maxCount)
{ {
return false; throw new BoatNotFoundException(position);
} }
if (Count >= _maxCount) if (Count >= _maxCount)
{ {
return false; throw new StorageOverflowException(_maxCount);
} }
_places.Insert(position, boat); _places.Insert(position, boat);
return true; return true;
@ -46,11 +47,12 @@ namespace SailBoat.Generics
{ {
return false; return false;
} }
if (Count >= _maxCount) if (_places[position] == null)
{ {
return false; throw new BoatNotFoundException(position);
} }
_places.RemoveAt(position);
_places[position] = null;
return true; return true;
} }
@ -58,12 +60,12 @@ namespace SailBoat.Generics
{ {
get get
{ {
if (position < 0 || position > _maxCount) { return null; } if (position < 0 || position >= Count) { return null; }
return _places[position]; return _places[position];
} }
set set
{ {
if (position < 0 || position > _maxCount) { return; } if (position < 0 || position >= Count) { return; }
_places[position] = value; _places[position] = value;
} }
} }

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.IO;
using System.Windows.Forms;
namespace SailBoat namespace SailBoat
{ {
internal static class Program internal static class Program
@ -11,7 +19,29 @@ namespace SailBoat
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormBoatCollection()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string appPath = "";
for (int i = 0; i < path.Length - 3; i++)
{
appPath += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -8,6 +8,34 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="C:\Users\shotb\.nuget\packages\nlog.config\4.7.15\contentFiles\any\any\NLog.config" />
<None Remove="C:\Users\shotb\.nuget\packages\nlog.schema\5.2.7\contentFiles\any\any\NLog.xsd" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="NLog.Schema" Version="5.2.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<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.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

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