конец 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>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

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

View File

@ -1,4 +1,5 @@
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using ProjectAccordionBus.CollectionGenericObjects;
using System.Text;
@ -97,32 +98,33 @@ public class StorageCollection<T> where T : DrawningBus
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
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)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -130,79 +132,72 @@ public class StorageCollection<T> where T : DrawningBus
{
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>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string 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];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
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;
}
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
throw new Exception("В файле нет данных");
if (str != _collectionKey.ToString())
throw new Exception("В файле неверные данные");
_storages.Clear();
foreach (string data in strs)
while ((str = sr.ReadLine()) != null)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType =
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionType);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
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)
{
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);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
@ -219,5 +214,5 @@ public class StorageCollection<T> where T : DrawningBus
_ => 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();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
loadFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -287,9 +287,9 @@
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
// loadFileDialog
//
openFileDialog.FileName = "openFileDialog1";
loadFileDialog.FileName = "openFileDialog1";
//
// FormBusCollection
//
@ -340,6 +340,6 @@
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private OpenFileDialog loadFileDialog;
}
}

View File

@ -1,6 +1,7 @@
using AccordionBus.CollectionGenericObjects;
using AccordionBus.Drawnings;
using AccordionBus.MovementStrategy;
using Microsoft.Extensions.Logging;
using ProjectAccordionBus.CollectionGenericObjects;
using System;
using System.Collections.Generic;
@ -22,12 +23,17 @@ public partial class FormBusCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBusCollection()
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void SetBus(DrawningBus bus)
@ -209,16 +215,20 @@ public partial class FormBusCollection : Form
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);
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 (_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">
<value>247, 17</value>
</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>
</metadata>
</root>

View File

@ -1,8 +1,11 @@
using AccordionBus;
using System.Drawing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectAccordionBus;
internal static class Program
{
/// <summary>
@ -14,6 +17,23 @@ internal static class Program
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
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>