ПИбд-23 Салин Олег Алексеевич Лабораторная работа №7 #17

Closed
Oleja123 wants to merge 5 commits from Lab7 into Lab6
10 changed files with 125 additions and 34 deletions

View File

@ -15,6 +15,8 @@ namespace Monorail.DrawningObjects
public int GetPosX => _startPosX;
char separator = '|';
public int GetPosY => _startPosY;
public int GetWidth => _monoRailWidth;

View File

@ -1,6 +1,8 @@
using Monorail.Entities;
using Microsoft.VisualBasic.Logging;
using Monorail.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;

View File

@ -1,4 +1,6 @@
using Monorail.DrawningObjects;
using Microsoft.Extensions.Logging;
using Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics;
using Monorail.MovementStrategy;
using System;
@ -11,6 +13,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Serilog;
namespace Monorail
{
@ -63,16 +67,18 @@ namespace Monorail
form.Show();
Action<DrawningMonorail>? monorailDelegate = new((m) =>
{
bool q = (obj + m);
if (q)
try
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
m.ChangePictureBoxSize(pictureBoxCollection.Width, pictureBoxCollection.Height);
pictureBoxCollection.Image = obj.ShowMonorails();
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(monorailDelegate);
@ -95,15 +101,24 @@ namespace Monorail
{
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($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowMonorails();
}
else
catch (MonorailNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch(FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
@ -135,12 +150,14 @@ _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowMonorail
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
@ -155,21 +172,26 @@ MessageBoxIcon.Question) == DialogResult.Yes)
}
_storage.AddSet(storageAddNameBox.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {storageAddNameBox.Text}");
}
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);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -179,19 +201,23 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
try {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach(var collection in _storage.Keys)
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.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

@ -6,6 +6,13 @@
<UseWindowsForms>true</UseWindowsForms>
</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>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -45,8 +45,7 @@ namespace Monorail.Generics
pos)
{
T? obj = collect._collection[pos];
if (obj != null)
collect._collection.Remove(pos);
collect._collection.Remove(pos);
return obj;
}

View File

@ -50,7 +50,7 @@ MonorailGenericCollection<DrawningMonorail, DrawningObjectMonorail>> record in _
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
string toWrite = $"MonorailStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' },
@ -70,7 +70,7 @@ StringSplitOptions.RemoveEmptyEntries);
{
if (!File.Exists(filename))
{
return false;
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
@ -79,11 +79,11 @@ StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("MonorailStorage"))
{
return false;
throw new IOException("Неверный формат данных");
}
_monorailStorages.Clear();
do

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Monorail.Exceptions
{
[Serializable]
internal class MonorailNotFoundException : ApplicationException
{
public MonorailNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public MonorailNotFoundException() : base () { }
public MonorailNotFoundException(string message) : base(message) { }
public MonorailNotFoundException(string message, Exception exception) : base(message, exception) { }
protected MonorailNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,12 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
namespace Monorail
{
static class Program
internal static class Program
{
/// <summary>
/// The main entry point for the application.
@ -14,6 +22,10 @@ namespace Monorail
[STAThread]
static void Main()
{
Log.Logger = new LoggerConfiguration()
Review

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

Настройку логера следует выносить в отдельный конфигурационный файл, чтобы ее можно было менять без пересборки проекта
.WriteTo.File("log.txt")
.MinimumLevel.Debug()
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

View File

@ -1,8 +1,10 @@
using System;
using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Monorail.Generics
{
@ -23,7 +25,7 @@ namespace Monorail.Generics
public bool Insert(T monorail)
{
if (_places.Count == _maxCount)
return false;
throw new StorageOverflowException(_maxCount);
Insert(monorail, 0);
return true;
@ -31,7 +33,9 @@ namespace Monorail.Generics
public bool Insert(T monorail, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count))
return false;
_places.Insert(position, monorail);
return true;
@ -39,7 +43,7 @@ namespace Monorail.Generics
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
return false;
throw new MonorailNotFoundException(position);
_places.RemoveAt(position);
return true;
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Monorail.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) { }
}
}