конец 7 лабы

This commit is contained in:
repka228 2024-05-07 23:01:58 +04:00
parent 5561fe3211
commit 8099071590
12 changed files with 260 additions and 146 deletions

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,4 +1,5 @@
using ProjectAccordionBus.CollectionGenericObjects; using AccordionBus.Exceptions;
using ProjectAccordionBus.CollectionGenericObjects;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -35,40 +36,33 @@ public class ListGenericObjects<T>:ICollectionGenericObjects<T> where T : class
public T? Get(int position) public T? Get(int position)
{ {
if (position >= 0 && position < Count) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{
return _collection[position]; return _collection[position];
} }
else
{
return null;
}
}
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) { return -1; } if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count || Count == _maxCount) if (position < 0 || position >= Count)
{ throw new PositionOutOfCollectionException(position);
return -1;
} if (Count == _maxCount)
throw new CollectionOverflowException(Count);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= Count || position < 0) return null; if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
T? obj = _collection[position]; T? obj = _collection[position];
_collection?.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }

View File

@ -1,4 +1,5 @@
using ProjectAccordionBus.CollectionGenericObjects; using AccordionBus.Exceptions;
using ProjectAccordionBus.CollectionGenericObjects;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -48,13 +49,13 @@ where T : class
} }
public T? Get(int position) // получение с позиции public T? Get(int position) // получение с позиции
{ {
if (position < 0 || position >= _collection.Length) // если позиция передано неправильно if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
return null; if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) // вставка объекта на свободное место public int Insert(T obj) // вставка объекта на свободное место
{ {
for(int i=0; i < _collection.Length; ++i) for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -62,20 +63,21 @@ where T : class
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 < 0 || position >= _collection.Length) // если позиция переданна неправильно if (position < 0 || position >= Count)
return -1; {
if (_collection[position] == null)//если позиция пуста throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
return position; return position;
} }
else
{ for (int i = position + 1; i < Count; i++)
for(int i=position; i< _collection.Length; ++i) //ищем свободное место справа
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -83,7 +85,7 @@ where T : class
return i; return i;
} }
} }
for (int i = 0; i < position; ++i) // иначе слева for (int i = position - 1; i >= 0; i--)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -91,16 +93,19 @@ where T : class
return i; return i;
} }
} }
}
return -1; throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) // удаление объекта, зануляя его public T? Remove(int position) // удаление объекта, зануляя его
{ {
if (position < 0 || position >= _collection.Length || _collection[position] == null) if (position < 0 || position >= Count)
return null; {
T ?temp = _collection[position]; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using AccordionBus.Drawnings; using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.CollectionGenericObjects;
using System.Text; using System.Text;
@ -97,32 +98,33 @@ public class StorageCollection<T> where T : DrawningBus
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns> /// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
return false;
if (File.Exists(filename))
File.Delete(filename);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
sw.Write(Environment.NewLine); throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
_storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key);
sw.Write(value.Key); sb.Append(_separatorForKeyValue);
sw.Write(_separatorForKeyValue); sb.Append(value.Value.GetCollectionType);
sw.Write(value.Value.GetCollectionType); sb.Append(_separatorForKeyValue);
sw.Write(_separatorForKeyValue); sb.Append(value.Value.MaxCount);
sw.Write(value.Value.MaxCount); sb.Append(_separatorForKeyValue);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
@ -130,79 +132,72 @@ public class StorageCollection<T> where T : DrawningBus
{ {
continue; continue;
} }
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
return true;
}
/// <summary> /// <summary>
/// Загрузка информации по самолетам в хранилище из файла /// Загрузка информации по самолетам в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new StreamReader(filename))
{ {
byte[] b = new byte[fs.Length]; string? str;
UTF8Encoding temp = new(true); str = sr.ReadLine();
while (fs.Read(b, 0, b.Length) > 0) if (str == null || str.Length == 0)
{ throw new Exception("В файле нет данных");
bufferTextFromFile += temp.GetString(b); if (str != _collectionKey.ToString())
} throw new Exception("В файле неверные данные");
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear(); _storages.Clear();
foreach (string data in strs) while ((str = sr.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, string[] record = str.Split(_separatorForKeyValue);
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
continue; continue;
} }
CollectionType collectionType = CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new Exception("Не удалось создать коллекцию");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningBus() is T bus) if (elem?.CreateDrawningBus() is T bus)
{ {
if (collection.Insert(bus)!=-1) try
{ {
return false; if (collection.Insert(bus) == -1)
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true; }
} }
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типу
@ -219,5 +214,5 @@ public class StorageCollection<T> where T : DrawningBus
_ => null, _ => null,
}; };
} }
} }

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions;
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionOverflowException(SerializationInfo info,
StreamingContext contex) : base(info, contex)
{
}
}

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 AccordionBus.Exceptions;
public 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 contex) : base(info, contex) { }
}

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 AccordionBus.Exceptions;
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции.Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,7 +52,7 @@
saveToolStripMenuItem = new ToolStripMenuItem(); saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); loadFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -287,9 +287,9 @@
// //
saveFileDialog.Filter = "txt file|*.txt"; saveFileDialog.Filter = "txt file|*.txt";
// //
// openFileDialog // loadFileDialog
// //
openFileDialog.FileName = "openFileDialog1"; loadFileDialog.FileName = "openFileDialog1";
// //
// FormBusCollection // FormBusCollection
// //
@ -340,6 +340,6 @@
private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog loadFileDialog;
} }
} }

View File

@ -1,6 +1,7 @@
using AccordionBus.CollectionGenericObjects; using AccordionBus.CollectionGenericObjects;
using AccordionBus.Drawnings; using AccordionBus.Drawnings;
using AccordionBus.MovementStrategy; using AccordionBus.MovementStrategy;
using Microsoft.Extensions.Logging;
using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.CollectionGenericObjects;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -22,12 +23,17 @@ public partial class FormBusCollection : Form
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
/// <summary> /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormBusCollection() public FormBusCollection(ILogger<FormBusCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
} }
private void SetBus(DrawningBus bus) private void SetBus(DrawningBus bus)
@ -209,16 +215,20 @@ public partial class FormBusCollection : Form
private void LoadToolStripMenuItem_Click(object sender, EventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (loadFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
_storageCollection.SaveData(loadFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems(); _logger.LogInformation("Загрузка из файла: {filename}",
loadFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -227,13 +237,19 @@ public partial class FormBusCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
} }
} }

View File

@ -126,7 +126,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>247, 17</value> <value>247, 17</value>
</metadata> </metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="loadFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>376, 17</value> <value>376, 17</value>
</metadata> </metadata>
</root> </root>

View File

@ -1,8 +1,11 @@
using AccordionBus; using AccordionBus;
using System.Drawing; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectAccordionBus; namespace ProjectAccordionBus;
internal static class Program internal static class Program
{ {
/// <summary> /// <summary>
@ -14,6 +17,23 @@ internal static class Program
// 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 FormBusCollection()); ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormBusCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBusCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }

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="carlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>