Lab 7 done

This commit is contained in:
strwbrry1 2024-05-15 17:20:36 +04:00
parent 326e4cf801
commit fd88fea05f
13 changed files with 259 additions and 86 deletions

View File

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Catamaran.Drawings;
namespace Catamaran
{
public delegate void BoatDelegate(DrawingBoat boat);
}

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </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="NLog.Extensions.Logging" Version="5.3.8" />
<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.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +34,13 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,4 +1,5 @@
using System; using Catamaran.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -49,7 +50,7 @@ namespace Catamaran.CollectionGenericObjects
{ {
return _collection[position]; return _collection[position];
} }
return null; throw new PositionOutOfRangeException(position) ;
} }
public int Insert(T obj) public int Insert(T obj)
@ -62,31 +63,31 @@ namespace Catamaran.CollectionGenericObjects
return i; return i;
} }
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < Count || position >= 0) if (position > Count || position < 0)
{ {
if (_collection[position] == null) throw new PositionOutOfRangeException(position);
}
if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
else else
{
for (int i = 0; i < Count; i++)
{ {
for (int i = 0; i < Count; i++) if (_collection[i] == null)
{ {
if (_collection[i] == null) _collection[i] = obj;
{ return i;
_collection[i] = obj;
return i;
}
} }
} }
} }
return -1; return -1;
} }
@ -94,8 +95,9 @@ namespace Catamaran.CollectionGenericObjects
{ {
if (position > Count || position < 0) if (position > Count || position < 0)
{ {
return null; throw new PositionOutOfRangeException(position);
} }
if (_collection[position] == null) throw new ObjectNotFoundException();
T? obj = _collection[position]; T? obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return obj; return obj;

View File

@ -1,4 +1,5 @@
using System; using Catamaran.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -42,28 +43,27 @@ namespace Catamaran.CollectionGenericObjects
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count) if (position >= Count || position < 0) throw new PositionOutOfRangeException(position);
{ if (_collection[position] == null) throw new ObjectNotFoundException();
return null;
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count + 1 > _maxCount) if (Count + 1 > _maxCount) throw new CollectionOverflowException(Count);
{
return -1;
}
_collection.Add(obj); _collection.Add(obj);
return 1; return 1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position > Count || Count + 1 > _maxCount) if (position < 0 || position > Count)
{ {
return -1; throw new PositionOutOfRangeException(position);
}
if (Count + 1 > _maxCount)
{
throw new CollectionOverflowException(Count);
} }
_collection.Insert(position, obj); _collection.Insert(position, obj);
return 1; return 1;
@ -73,7 +73,7 @@ namespace Catamaran.CollectionGenericObjects
{ {
if (position < 0 || position > Count) if (position < 0 || position > Count)
{ {
return null; throw new PositionOutOfRangeException(position);
} }
T? obj = _collection[position]; T? obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);

View File

@ -1,4 +1,5 @@
using Catamaran.Drawings; using Catamaran.Drawings;
using Catamaran.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
@ -66,11 +67,11 @@ namespace Catamaran.CollectionGenericObjects
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -112,14 +113,13 @@ namespace Catamaran.CollectionGenericObjects
} }
return true;
} }
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 reader = new(filename)) using (StreamReader reader = new(filename))
@ -127,11 +127,11 @@ namespace Catamaran.CollectionGenericObjects
string line = reader.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new ArgumentException("В файле нет данных");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
return false; throw new InvalidDataException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
@ -147,7 +147,8 @@ namespace Catamaran.CollectionGenericObjects
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
@ -157,17 +158,25 @@ namespace Catamaran.CollectionGenericObjects
{ {
if (elem?.CreateDrawingBoat() is T boat) if (elem?.CreateDrawingBoat() is T boat)
{ {
if (collection.Insert(boat) < 0) try
{ {
return false; if (collection.Insert(boat) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
} }
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)

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 Catamaran.Exceptions
{
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("Превышено количество элементов коллекции: count" + count) { }
public CollectionOverflowException() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

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 Catamaran.Exceptions
{
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

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 Catamaran.Exceptions
{
[Serializable]
internal class PositionOutOfRangeException : ApplicationException
{
public PositionOutOfRangeException(int i) : base("Не найден объект по позиции " + i) { }
public PositionOutOfRangeException() : base() { }
public PositionOutOfRangeException(string message) : base(message) { }
public PositionOutOfRangeException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,6 +1,9 @@
using Catamaran.CollectionGenericObjects; using Catamaran.CollectionGenericObjects;
using Catamaran.Drawings; using Catamaran.Drawings;
using Catamaran.Exceptions;
using Microsoft.Extensions.Logging;
using System; using System;
using System.CodeDom;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -19,10 +22,13 @@ namespace Catamaran
private readonly StorageCollection<DrawingBoat> _storageCollection; private readonly StorageCollection<DrawingBoat> _storageCollection;
public FormBoatColletion() private readonly ILogger _logger;
public FormBoatColletion(ILogger<FormBoatColletion> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -50,14 +56,17 @@ namespace Catamaran
return; return;
} }
if (_company + boat >= 0) try
{ {
int addingObj = _company + boat;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {boat.GetDataForSave()}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект {ex.Message}");
} }
} }
@ -86,14 +95,22 @@ namespace Catamaran
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
object delObj = _company - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект по позиции {pos}");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
} }
else catch (ObjectNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект по позиции {pos}");
}
catch (PositionOutOfRangeException)
{
MessageBox.Show("Удаление вне рамкок коллекции");
_logger.LogWarning($"Не удалось удалить объект по позиции {pos} - вне коллекции");
} }
} }
@ -112,27 +129,34 @@ namespace Catamaran
{ {
return; return;
} }
try
DrawingBoat? boat = null;
int counter = 100;
while (boat == null)
{ {
boat = _company.GetRandomObject(); DrawingBoat? boat = null;
int counter = 100;
while (boat == null)
{
boat = _company.GetRandomObject();
counter--; counter--;
if (counter <= 0) break;
}
if (boat == null) if (counter <= 0) break;
{ }
return; if (boat == null)
} {
throw new ObjectNotFoundException();
}
FormCatamaran form = new() FormCatamaran form = new()
{ {
SetBoat = boat SetBoat = boat
}; };
form.ShowDialog(); form.ShowDialog();
}
catch (ObjectNotFoundException)
{
_logger.LogWarning($"Не удалось найти объект для отправки на тест");
}
} }
private void RefreshListBoxItems() private void RefreshListBoxItems()
@ -153,6 +177,7 @@ namespace Catamaran
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonArray.Checked && !radioButtonList.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неверно введены данные для создания коллекции");
return; return;
} }
@ -167,6 +192,7 @@ namespace Catamaran
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция - {textBoxCollectionName.Text}");
RefreshListBoxItems(); RefreshListBoxItems();
} }
@ -175,13 +201,16 @@ namespace Catamaran
if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0) if (listBoxCollection.SelectedItem == null || listBoxCollection.SelectedIndex < 0)
{ {
MessageBox.Show("Не выбрана коллекция"); MessageBox.Show("Не выбрана коллекция");
_logger.LogWarning("Ошибка удаления коллекции - она не выбрана");
return; return;
} }
string temp = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция - {temp}");
RefreshListBoxItems(); RefreshListBoxItems();
} }
@ -190,6 +219,7 @@ namespace Catamaran
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Ошибка создания компании - она не выбрана");
return; return;
} }
@ -197,6 +227,7 @@ namespace Catamaran
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не инициализирована"); MessageBox.Show("Коллекция не инициализирована");
_logger.LogWarning("Ошибка инициализации коллекции");
return; return;
} }
@ -215,15 +246,18 @@ namespace Catamaran
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Успешно сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Успешно сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
else
{
MessageBox.Show("Не сохранено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка сохранения: {Message}", ex.Message);
}
} }
} }
@ -231,16 +265,20 @@ namespace Catamaran
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Успешно загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Успешно загружено", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems(); RefreshListBoxItems();
} _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
else
{
MessageBox.Show("Ошибка загрузки", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка загрузки: {Message}", ex.Message);
}
} }
} }
} }

View File

@ -143,9 +143,5 @@ namespace Catamaran
} }
} }
private void panelWhite_Paint(object sender, PaintEventArgs e)
{
}
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Catamaran namespace Catamaran
{ {
internal static class Program internal static class Program
@ -11,7 +16,27 @@ namespace Catamaran
// 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 FormBoatColletion());
ServiceCollection services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBoatColletion>());
}
public static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatColletion>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

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