Лабораторная работа №7
This commit is contained in:
parent
a0b08d45ce
commit
438b1653bc
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -52,7 +53,7 @@ internal class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
public T? Get(int position)
|
||||
{
|
||||
// TODO проверка позиции
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
@ -61,12 +62,9 @@ internal class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// TODO проверка, что не превышено максимальное количество элементов
|
||||
// TODO вставка в конец набора
|
||||
|
||||
if (_collection.Count > _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
_collection.Add(obj);
|
||||
return _collection.Count;
|
||||
return Count;
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -75,11 +73,8 @@ internal class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// TODO проверка позиции
|
||||
// TODO вставка по позиции
|
||||
|
||||
if (_collection.Count > _maxCount)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (position >= Count || position < 0) return -1;
|
||||
if (Count == _maxCount) throw new CollectionOverflowException(Count);
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
_collection.Insert(position, obj);
|
||||
return position;
|
||||
}
|
||||
@ -89,7 +84,7 @@ internal class ListGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из списка
|
||||
|
||||
if (position >= Count || position < 0) return null;
|
||||
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
|
||||
T obj = _collection[position];
|
||||
_collection.RemoveAt(position);
|
||||
return obj;
|
||||
|
@ -1,4 +1,6 @@
|
||||
|
||||
using ProjectAirbus.Exceptions;
|
||||
|
||||
namespace ProjectAirbus.CollectionGenericObjects;
|
||||
|
||||
|
||||
@ -50,7 +52,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
|
||||
public T? Get(int position)
|
||||
{
|
||||
if (position >= _collection.Length || position < 0) return null;
|
||||
if (position < 0 || position >= MaxCount)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
return _collection[position];
|
||||
}
|
||||
|
||||
@ -58,17 +63,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
{
|
||||
// TODO вставка в свободное место набора
|
||||
|
||||
int index = 0;
|
||||
while (index < _collection.Length)
|
||||
for (int i = 0; i < MaxCount; ++i)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
_collection[i] = obj;
|
||||
return i;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
return -1;
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public int Insert(T obj, int position)
|
||||
@ -79,35 +82,32 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// если нет после, ищем до
|
||||
// TODO вставка
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return -1;
|
||||
if (position < 0 || position >= MaxCount)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(Count);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
_collection[position] = obj;
|
||||
return position;
|
||||
}
|
||||
int index = position + 1;
|
||||
while (index < _collection.Length)
|
||||
for (int i = position + 1; i < _collection.Length; ++i)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
}
|
||||
++index;
|
||||
}
|
||||
index = position - 1;
|
||||
while (index >= 0)
|
||||
for (int i = 0; i < position; ++i)
|
||||
{
|
||||
if (_collection[index] == null)
|
||||
if (_collection[i] == null)
|
||||
{
|
||||
_collection[index] = obj;
|
||||
return index;
|
||||
_collection[i] = obj;
|
||||
return position;
|
||||
}
|
||||
--index;
|
||||
}
|
||||
return -1;
|
||||
|
||||
throw new CollectionOverflowException(Count);
|
||||
}
|
||||
|
||||
public T Remove(int position)
|
||||
@ -115,11 +115,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
|
||||
// TODO проверка позиции
|
||||
// TODO удаление объекта из массива, присвоив элементу массива значение null
|
||||
|
||||
if (position >= _collection.Length || position < 0)
|
||||
return null;
|
||||
T obj = _collection[position];
|
||||
if (position < 0 || position >= MaxCount)
|
||||
{
|
||||
throw new PositionOutOfCollectionException(position);
|
||||
}
|
||||
if (_collection[position] == null)
|
||||
{
|
||||
throw new ObjectNotFoundException(position);
|
||||
}
|
||||
T remove = _collection[position];
|
||||
_collection[position] = null;
|
||||
return obj;
|
||||
return remove;
|
||||
}
|
||||
|
||||
public IEnumerable<T?> GetItems()
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirbus.Drawning;
|
||||
using ProjectAirbus.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -96,36 +97,35 @@ public class StorageCollection<T>
|
||||
/// </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;
|
||||
}
|
||||
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
|
||||
|
||||
}
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
|
||||
StringBuilder sb = new();
|
||||
sb.Append(_collectionKey);
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
|
||||
_storages)
|
||||
using StreamWriter wr = new StreamWriter(filename);
|
||||
|
||||
wr.Write(_collectionKey);
|
||||
|
||||
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
|
||||
{
|
||||
sb.Append(Environment.NewLine);
|
||||
// не сохраняем пустые коллекции
|
||||
wr.Write(Environment.NewLine);
|
||||
if (value.Value.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(value.Key);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.GetCollectionType);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
sb.Append(value.Value.MaxCount);
|
||||
sb.Append(_separatorForKeyValue);
|
||||
|
||||
wr.Write(value.Key);
|
||||
wr.Write(_separatorForKeyValue);
|
||||
wr.Write(value.Value.GetCollectionType);
|
||||
wr.Write(_separatorForKeyValue);
|
||||
wr.Write(value.Value.MaxCount);
|
||||
wr.Write(_separatorForKeyValue);
|
||||
foreach (T? item in value.Value.GetItems())
|
||||
{
|
||||
string data = item?.GetDataForSave() ?? string.Empty;
|
||||
@ -133,14 +133,10 @@ public class StorageCollection<T>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sb.Append(data);
|
||||
sb.Append(_separatorItems);
|
||||
wr.Write(data);
|
||||
wr.Write(_separatorItems);
|
||||
}
|
||||
}
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
|
||||
fs.Write(info, 0, info.Length);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -148,66 +144,60 @@ public class StorageCollection<T>
|
||||
/// </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 fs = File.OpenText(filename))
|
||||
{
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
string str = fs.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
{
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
throw new Exception("В файле нет данных");
|
||||
}
|
||||
}
|
||||
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
if (!str.StartsWith(_collectionKey))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!strs[0].Equals(_collectionKey))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
throw new Exception("В файле неверные данные");
|
||||
}
|
||||
_storages.Clear();
|
||||
foreach (string data in strs)
|
||||
string strs = "";
|
||||
while ((strs = fs.ReadLine()) != null)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
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("Не удалось определить тип коллекции:" + record[1]);
|
||||
}
|
||||
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)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection.Insert(bus) == -1)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
|
||||
}
|
||||
}
|
||||
catch (CollectionOverflowException ex)
|
||||
{
|
||||
throw new Exception("Коллекция переполнена", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
_storages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirbus.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку переполнения коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
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) { }
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirbus.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
internal 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) { }
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAirbus.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Класс, описывающий ошибку выхода за границы коллекции
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
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) { }
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ProjectAirbus.CollectionGenericObjects;
|
||||
using ProjectAirbus.Drawning;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -24,13 +25,19 @@ namespace ProjectAirbus
|
||||
/// </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 ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
|
||||
@ -234,13 +241,16 @@ namespace ProjectAirbus
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -249,16 +259,16 @@ namespace ProjectAirbus
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storageCollection.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_storageCollection.LoadData(openFileDialog.FileName);
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
RerfreshListBoxItems();
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogError("Ошибка: {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NLog.Extensions.Logging;
|
||||
|
||||
namespace ProjectAirbus
|
||||
{
|
||||
internal static class Program
|
||||
@ -10,8 +15,22 @@ namespace ProjectAirbus
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ServiceCollection services = new();
|
||||
ConfigureServices(services);
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormBusCollection());
|
||||
|
||||
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");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,11 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.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>
|
14
ProjectAirbus/ProjectAirbus/nlog.config
Normal file
14
ProjectAirbus/ProjectAirbus/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