7 лабораторная работа

This commit is contained in:
Arslan 2024-04-29 08:29:24 +04:00
parent 227e8136f7
commit 69370b211a
10 changed files with 221 additions and 190 deletions

View File

@ -1,4 +1,5 @@
using ProjectFighterJet.CollectionGenericObjects; using ProjectFighterJet.CollectionGenericObjects;
using ProjectFighterJet.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -57,33 +58,28 @@ where T : class
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count <= _maxCount) // TODO выброс ошибки если переполнение
{ if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; return Count;
} }
return -1;
}
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count < _maxCount && position >= 0 && position < _maxCount) // TODO выброс ошибки если переполнение
{ // TODO выброс ошибки если за границу
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
return -1;
}
public T Remove(int position) public T Remove(int position)
{ {
T temp = _collection[position]; // TODO если выброс за границу
if (position >= 0 && position < _maxCount) if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
{ T obj = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return obj;
} }
return null;
}
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()
{ {
for (int i = 0; i < Count; ++i) for (int i = 0; i < Count; ++i)

View File

@ -1,4 +1,5 @@
using ProjectFighterJet.Drawnings; using ProjectFighterJet.Drawnings;
using ProjectFighterJet.Exceptions;
namespace ProjectFighterJet.CollectionGenericObjects; namespace ProjectFighterJet.CollectionGenericObjects;
@ -65,12 +66,14 @@ where T : class
} }
index++; index++;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position >= _collection.Length || position < 0) return -1; // TODO выброс ошибки если переполнение
// TODO выброс ошибки если выход за границу
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
_collection[position] = obj; _collection[position] = obj;
@ -84,7 +87,7 @@ where T : class
_collection[index] = obj; _collection[index] = obj;
return index; return index;
} }
index++; ++index;
} }
index = position - 1; index = position - 1;
while (index >= 0) while (index >= 0)
@ -94,17 +97,20 @@ where T : class
_collection[index] = obj; _collection[index] = obj;
return index; return index;
} }
index--; --index;
} }
return -1; throw new CollectionOverflowException(Count);
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= _collection.Length || position < 0) return null; // TODO выброс ошибки если выход за границу
T temp = _collection[position]; // TODO выброс ошибки если объект пустой
if (position >= _collection.Length || position < 0) 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

@ -6,6 +6,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text; using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Runtime.InteropServices.JavaScript.JSType;
using ProjectFighterJet.Exceptions;
namespace ProjectFighterJet.CollectionGenericObjects; namespace ProjectFighterJet.CollectionGenericObjects;
@ -90,12 +91,12 @@ where T : DrawningJet
/// Сохранение информации по автомобилям в хранилище в файл /// Сохранение информации по автомобилям в хранилище в файл
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -106,19 +107,18 @@ where T : DrawningJet
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); writer.Write(Environment.NewLine);
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); writer.Write(value.Key);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); writer.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); writer.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;
@ -126,85 +126,40 @@ where T : DrawningJet
{ {
continue; continue;
} }
sb.Append(data); writer.Write(data);
sb.Append(_separatorItems); writer.Write(_separatorItems);
} }
writer.Write(sb);
} }
} }
//if (_storages.Count == 0)
//{
// return false;
//}
//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;
// }
// 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;
// if (string.IsNullOrEmpty(data))
// {
// 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);
return true;
} }
/// <summary> /// <summary>
/// Загрузка информации по автомобилям в хранилище из файла /// Загрузка информации по автомобилям в хранилище из файла
/// </summary> /// </summary>
/// <param name="filename">Путь и имя файла</param> /// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> public void LoadData(string filename)
public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не существует");
} }
using (StreamReader fs = File.OpenText(filename)) using (StreamReader fs = File.OpenText(filename))
{ {
string str = fs.ReadLine(); string str = fs.ReadLine();
if (str == null || str.Length == 0) if (str == null || str.Length == 0)
{ {
return false; throw new Exception("В файле нет данных");
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
return false; throw new Exception("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
//по идее этого произойти не должно
//if (strs == null)
//{
// return false;
//}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
@ -214,73 +169,29 @@ where T : DrawningJet
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?.CreateDrawningJet() is T jet) if (elem?.CreateDrawningJet() is T jet)
{
try
{ {
if (collection.Insert(jet) == -1) if (collection.Insert(jet) == -1)
{ {
return false; throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
return true;
//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);
// }
//}
//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();
//foreach (string data in strs)
//{
// string[] record = data.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);
// if (collection == null)
// {
// return false;
// }
// collection.MaxCount = Convert.ToInt32(record[2]);
// string[] set = record[3].Split(_separatorItems,
// StringSplitOptions.RemoveEmptyEntries);
// foreach (string elem in set)
// {
// if (elem?.CreateDrawningShip() is T ship)
// {
// if (collection.Insert(ship) == -1)
// {
// return false;
// }
// }
// }
// _storages.Add(record[0], collection);
//}
//return true;
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectFighterJet.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal 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,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectFighterJet.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) { }
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectFighterJet.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) { }
}

View File

@ -1,5 +1,7 @@
using ProjectFighterJet.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using ProjectFighterJet.CollectionGenericObjects;
using ProjectFighterJet.Drawnings; using ProjectFighterJet.Drawnings;
using ProjectFighterJet.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -26,10 +28,15 @@ public partial class FormJetCollection : Form
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormJetCollection()
private readonly ILogger _logger;
public FormJetCollection(ILogger<FormJetCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
} }
/// <summary> /// <summary>
/// Выбор компании /// Выбор компании
@ -48,14 +55,24 @@ public partial class FormJetCollection : Form
private void SetJet(DrawningJet jet) private void SetJet(DrawningJet jet)
{ {
try
{
if (_company == null || jet == null)
{
return;
}
if (_company + jet != -1) if (_company + jet != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + jet.GetDataForSave());
} }
else }
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
@ -99,15 +116,19 @@ public partial class FormJetCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
int tempSize = FighterJetSharingService.getAmountOfObjects(); try
{
if (_company - pos != null) if (_company - pos != null)
{ {
MessageBox.Show("Объект удалён"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
} }
else }
catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
/// <summary> /// <summary>
@ -123,6 +144,8 @@ public partial class FormJetCollection : Form
} }
DrawningJet? jet = null; DrawningJet? jet = null;
int counter = 100; int counter = 100;
try
{
while (jet == null) while (jet == null)
{ {
jet = _company.GetRandomObject(); jet = _company.GetRandomObject();
@ -132,16 +155,18 @@ public partial class FormJetCollection : Form
break; break;
} }
} }
if (jet == null)
{
return;
}
FormFighterJet form = new() FormFighterJet form = new()
{ {
Setjet = jet Setjet = jet
}; };
form.ShowDialog(); form.ShowDialog();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary> /// <summary>
/// Перерисовка коллекции /// Перерисовка коллекции
/// </summary> /// </summary>
@ -164,6 +189,8 @@ public partial class FormJetCollection : Form
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
try
{
CollectionType collectionType = CollectionType.None; CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked) if (radioButtonMassive.Checked)
{ {
@ -175,6 +202,12 @@ public partial class FormJetCollection : Form
} }
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
} }
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -239,15 +272,16 @@ public partial class FormJetCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storageCollection.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -262,16 +296,17 @@ public partial class FormJetCollection : Form
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", _storageCollection.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Загрузка не удалась", "Результат", MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using NLog.Extensions.Logging;
namespace ProjectFighterJet namespace ProjectFighterJet
{ {
internal static class Program internal static class Program
@ -11,7 +16,21 @@ namespace ProjectFighterJet
// 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 FormJetCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormJetCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormJetCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -11,6 +11,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="EntityFramework" Version="5.0.0" /> <PackageReference Include="EntityFramework" Version="5.0.0" />
<PackageReference Include="EntityFramework.ru" Version="5.0.0" /> <PackageReference Include="EntityFramework.ru" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.9" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>