PIbd-23. Radaev A.V. Lab Work 07 #14

Closed
Arkadiy wants to merge 1 commits from Lab7 into Lab6
9 changed files with 123 additions and 56 deletions

View File

@ -8,4 +8,11 @@
<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>
</Project>

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

View File

@ -41,7 +41,6 @@ namespace Catamaran
public static T? operator -(CatamaransGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
collect._collection.Remove(pos);
return obj;
}

View File

@ -23,6 +23,14 @@ namespace Catamaran
private static readonly char _separatorForObject = ':';
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catStorages = new Dictionary<string,
CatamaransGenericCollection<DrawningCatamaran,DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
@ -30,7 +38,8 @@ namespace Catamaran
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catStorages)
foreach (KeyValuePair<string,
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>> record in _catStorages)
{
StringBuilder records = new();
foreach (DrawningCatamaran? elem in record.Value.GetCatamarans)
@ -39,12 +48,12 @@ namespace Catamaran
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
string toWrite = $"catamaransStorage{Environment.NewLine}{data}";
string toWrite = $"CatamaranStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
@ -54,7 +63,6 @@ namespace Catamaran
sw.WriteLine(str);
}
}
return true;
}
@ -62,24 +70,21 @@ namespace Catamaran
{
if (!File.Exists(filename))
{
return false;
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("catamaransStorage"))
if (!strs[0].StartsWith("CatamaranStorage"))
{
return false;
throw new IOException("Неверный формат данных");
}
_catStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
@ -89,11 +94,12 @@ namespace Catamaran
continue;
}
CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCatamaran? catamaran =
elem?.CreateDrawningCatamran(_separatorForObject, _pictureWidth, _pictureHeight);
elem?.CreateDrawningCatamaran(_separatorForObject, _pictureWidth, _pictureHeight);
if (catamaran != null)
{
if (!(collection + catamaran))
@ -110,15 +116,6 @@ namespace Catamaran
return true;
}
public CatamaransGenericStorage(int pictureWidth, int pictureHeight)
{
_catStorages = new Dictionary<string,
CatamaransGenericCollection<DrawningCatamaran,
DrawningObjectCatamaran>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_catStorages.Add(name, new CatamaransGenericCollection<DrawningCatamaran, DrawningObjectCatamaran>(_pictureWidth, _pictureHeight));

View File

@ -9,7 +9,7 @@ namespace Catamaran
public static class ExtentionDrawningCatamaran
{
public static DrawningCatamaran? CreateDrawningCatamran(this string info, char
public static DrawningCatamaran? CreateDrawningCatamaran(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -7,6 +8,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Serilog;
namespace Catamaran
{
@ -89,16 +93,18 @@ namespace Catamaran
form.Show();
Action<DrawningCatamaran>? catamaranDelegate = new((c) =>
{
bool q = (obj + c);
if (q)
try
{
bool q = obj + c;
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {SetslistBox.SelectedItem.ToString() ?? string.Empty}");
c.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowCats();
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {SetslistBox.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(catamaranDelegate);
@ -122,15 +128,23 @@ namespace Catamaran
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (obj - pos != null)
try
{
int pos = Convert.ToInt32(maskedTextBox.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {SetslistBox.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCats();
}
else
catch (CatamaranNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
Log.Warning($"Не получилось удалить объект из коллекции {SetslistBox.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@ -152,36 +166,42 @@ namespace Catamaran
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
SetslistBox.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace Catamaran
{
internal static class Program
@ -8,11 +13,11 @@ namespace Catamaran
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Log.Logger = new LoggerConfiguration().WriteTo.File("log.txt").MinimumLevel.Debug().CreateLogger();
Review

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormCatamaranCollection());
}
}
}

View File

@ -22,7 +22,7 @@ namespace Catamaran
public bool Insert(T catamaran)
{
if (_places.Count == _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
Insert(catamaran, 0);
return true;
}
@ -30,6 +30,8 @@ namespace Catamaran
public bool Insert(T catamaran, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
_places.Insert(position, catamaran);
return true;
@ -38,7 +40,7 @@ namespace Catamaran
public bool Remove(int position)
{
if (!(position >= 0 && position < Count) || _places[position] == null)
return false;
throw new CatamaranNotFoundException(position);
_places[position] = null;
return true;
}
@ -58,12 +60,12 @@ namespace Catamaran
return;
}
}
public IEnumerable<T?> GetCatamarans(int? maxMonorails = null)
public IEnumerable<T?> GetCatamarans(int? maxCatamarans = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxMonorails.HasValue && i == maxMonorails.Value)
if (maxCatamarans.HasValue && i == maxCatamarans.Value)
{
yield break;
}

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
{
[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) { }
}
}