зафиксировать

This commit is contained in:
Kristina 2023-12-02 19:40:05 +04:00
parent 6c6d67d02d
commit a17a520267
7 changed files with 199 additions and 25 deletions

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.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)
{ }
public BoatNotFoundException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.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)
{ }
public StorageOverflowException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@ -7,10 +7,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Generics;
using ProjectBoat_bae.MovementStrategy;
using ProjectBoat_bae.Exceptions;
namespace ProjectBoat_bae
{
@ -19,10 +21,14 @@ namespace ProjectBoat_bae
// Набор объектов
private readonly BoatsGenericStorage _storage;
// Логер
private readonly ILogger _logger;
public FormBoatCollection()
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
// Заполнение listBoxObjects
@ -49,6 +55,15 @@ namespace ProjectBoat_bae
// Добавление набора в коллекцию
private void ButtonAddObject_Click_1(object sender, EventArgs e)
{
//if (string.IsNullOrEmpty(textBoxStorageName.Text))
//{
// MessageBox.Show("Не все данные заполнены", "Ошибка",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// return;
//}
//_storage.AddSet(textBoxStorageName.Text);
//ReloadObjects();
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
@ -57,6 +72,7 @@ namespace ProjectBoat_bae
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// Удаление набора
@ -66,12 +82,20 @@ namespace ProjectBoat_bae
{
return;
}
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);
// ReloadObjects();
// }
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {name}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
@ -167,15 +191,16 @@ namespace ProjectBoat_bae
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -183,15 +208,52 @@ namespace ProjectBoat_bae
//загрузка
private void LoadToolStripMenu_Click(object sender, EventArgs args)
{
//if (openFileDialog.ShowDialog() == DialogResult.OK)
//{
// if (_storage.LoadData(openFileDialog.FileName))
// {
// MessageBox.Show("Load Complete", "Result",
// MessageBoxButtons.OK, MessageBoxIcon.Information);
// ReloadObjects();
// }
// else
// {
// MessageBox.Show("Load Not Complete", "Result",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
//}
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
ReloadObjects();
//if (openFileDialog.ShowDialog() == DialogResult.OK)
//{
// try
// {
// _storage.LoadData(openFileDialog.FileName);
// MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
// _logger.LogInformation("Загрузка прошла успешно");
// }
// catch (Exception ex)
// {
// MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
// _logger.LogWarning($"Не загрузилось: {ex.Message}");
// }
//}
//ReloadObjects();
}
}
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -49,14 +50,15 @@ namespace ProjectBoat_bae.Generics
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
foreach (KeyValuePair<string,
BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (Drawningboat? elem in record.Value.GetBoats)
@ -67,13 +69,14 @@ namespace ProjectBoat_bae.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"PlaneStorage{Environment.NewLine}{data}");
}
return true;
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public bool LoadData(string filename)
@ -82,7 +85,6 @@ namespace ProjectBoat_bae.Generics
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
@ -90,7 +92,7 @@ namespace ProjectBoat_bae.Generics
{
return false;
}
if (!str.StartsWith("BoatStorage"))
if (!str.StartsWith("ShipStorage"))
{
return false;
}

View File

@ -1,3 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectBoat_bae
{
internal static class Program
@ -11,7 +15,22 @@ namespace ProjectBoat_bae
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,6 +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" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,14 @@
<?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="boatlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>