Лаб_7_фикс1
This commit is contained in:
parent
f8ce47bbd3
commit
dc45fbd65d
@ -1,11 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DoubleDeckerBus.DrawningObjects;
|
||||
|
||||
namespace DoubleDeckerBus
|
||||
{
|
||||
public delegate void BusDelegate(DrawningBus bus);
|
||||
}
|
@ -8,4 +8,9 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -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 DoubleDeckerBus.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class BusNotFoundException : ApplicationException
|
||||
{
|
||||
public BusNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
|
||||
public BusNotFoundException() : base() { }
|
||||
public BusNotFoundException(string message) : base(message) { }
|
||||
public BusNotFoundException(string message, Exception exception) : base(message, exception){ }
|
||||
protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
||||
|
@ -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 DoubleDeckerBus.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 contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -12,33 +12,36 @@ using DoubleDeckerBus.Generics;
|
||||
using DoubleDeckerBus.MovementStrategy;
|
||||
using static System.Windows.Forms.DataFormats;
|
||||
using System.Windows.Forms;
|
||||
using DoubleDeckerBus.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DoubleDeckerBus
|
||||
{
|
||||
public partial class FormBusCollection : Form
|
||||
{
|
||||
private readonly BusesGenericStorage _storage;
|
||||
public FormBusCollection()
|
||||
private readonly ILogger _logger;
|
||||
public FormBusCollection(ILogger<FormBusCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
private void ReloadObjects()
|
||||
{
|
||||
int index = listBoxStorages.SelectedIndex;
|
||||
|
||||
listBoxStorages.Items.Clear();
|
||||
for (int i = 0; i < _storage.Keys.Count; i++)
|
||||
{
|
||||
listBoxStorages.Items.Add(_storage.Keys[i]);
|
||||
}
|
||||
|
||||
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
|
||||
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
|
||||
>= listBoxStorages.Items.Count))
|
||||
{
|
||||
listBoxStorages.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
|
||||
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
|
||||
index < listBoxStorages.Items.Count)
|
||||
{
|
||||
listBoxStorages.SelectedIndex = index;
|
||||
}
|
||||
@ -52,11 +55,12 @@ namespace DoubleDeckerBus
|
||||
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}");
|
||||
}
|
||||
private void ButtonDelObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
@ -64,12 +68,14 @@ namespace DoubleDeckerBus
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
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}");
|
||||
}
|
||||
}
|
||||
private void buttonAddBus_Click(object sender, EventArgs e)
|
||||
@ -120,15 +126,23 @@ namespace DoubleDeckerBus
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
if (obj - pos != null)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowBuses();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (BusNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
||||
{
|
||||
@ -136,8 +150,7 @@ namespace DoubleDeckerBus
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
@ -148,13 +161,14 @@ namespace DoubleDeckerBus
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -162,17 +176,18 @@ namespace DoubleDeckerBus
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
foreach (var collection in _storage.Keys)
|
||||
{
|
||||
listBoxStorages.Items.Add(collection);
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show($"Не открылось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -23,87 +23,6 @@ namespace DoubleDeckerBus.Generics
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
public bool SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder data = new();
|
||||
foreach (KeyValuePair<string, BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
|
||||
{
|
||||
StringBuilder records = new();
|
||||
foreach (DrawningBus? elem in record.Value.GetTheBuses)
|
||||
{
|
||||
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
||||
}
|
||||
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
string toWrite = $"BusStorage{Environment.NewLine}{data}";
|
||||
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
using (StreamWriter sw = new(filename))
|
||||
{
|
||||
foreach (var str in strs)
|
||||
{
|
||||
sw.WriteLine(str);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public bool LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (!strs[0].StartsWith("BusStorage"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_busStorages.Clear();
|
||||
do
|
||||
{
|
||||
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 2)
|
||||
{
|
||||
str = sr.ReadLine();
|
||||
continue;
|
||||
}
|
||||
BusesGenericCollection<DrawningBus, DrawningObjectBus> collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
DrawningBus? bus =
|
||||
elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (bus != null)
|
||||
{
|
||||
if (!(collection + bus))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
_busStorages.Add(record[0], collection);
|
||||
|
||||
str = sr.ReadLine();
|
||||
} while (str != null);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public void AddSet(string name)
|
||||
{
|
||||
_busStorages.Add(name, new BusesGenericCollection<DrawningBus, DrawningObjectBus>(_pictureWidth, _pictureHeight));
|
||||
@ -130,5 +49,90 @@ namespace DoubleDeckerBus.Generics
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder data = new();
|
||||
foreach (KeyValuePair<string,
|
||||
BusesGenericCollection<DrawningBus, DrawningObjectBus>> record in _busStorages)
|
||||
{
|
||||
StringBuilder records = new();
|
||||
foreach (DrawningBus? elem in record.Value.GetTheBuses)
|
||||
{
|
||||
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
||||
}
|
||||
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
throw new Exception("Невалидная операция, нет данных для сохранения");
|
||||
}
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new
|
||||
UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}");
|
||||
fs.Write(info, 0, info.Length);
|
||||
return;
|
||||
}
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new Exception("Файл не найден");
|
||||
}
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
}
|
||||
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
throw new Exception("Нет данных для загрузки");
|
||||
}
|
||||
if (!strs[0].StartsWith("BusStorage"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
throw new Exception("Неверный формат данных");
|
||||
}
|
||||
_busStorages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
BusesGenericCollection<DrawningBus, DrawningObjectBus>
|
||||
collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
DrawningBus? car =
|
||||
elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (car != null)
|
||||
{
|
||||
if (!(collection + car))
|
||||
{
|
||||
throw new Exception("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
}
|
||||
_busStorages.Add(record[0], collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@ -1,4 +1,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Drawing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
|
||||
namespace DoubleDeckerBus
|
||||
{
|
||||
@ -8,7 +11,22 @@ namespace DoubleDeckerBus
|
||||
static void Main()
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBusCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider =
|
||||
services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormBusCollection>()
|
||||
.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddNLog("nlog.config");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
14
DoubleDeckerBus/DoubleDeckerBus/nlog.config
Normal file
14
DoubleDeckerBus/DoubleDeckerBus/nlog.config
Normal 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="carlog-
|
||||
${shortdate}.log" />
|
||||
</targets>
|
||||
<rules>
|
||||
<logger name="*" minlevel="Debug" writeTo="tofile" />
|
||||
</rules>
|
||||
</nlog>
|
||||
</configuration>
|
Loading…
Reference in New Issue
Block a user