Ну, не робит лол)

This commit is contained in:
Tonb73 2024-05-12 11:28:30 +03:00
parent bf21edec3e
commit 4479e26b20
7 changed files with 180 additions and 88 deletions

View File

@ -73,6 +73,11 @@ namespace ProjectElectricLocomotive.CollectionGenericObjects
{
return Name.GetHashCode();
}
public bool IsEmpty()
{
if (string.IsNullOrEmpty(Name) && CollectionType != CollectionType.None) return true;
return false;
}
}
}

View File

@ -42,7 +42,7 @@ where T : DrawningLocomotive
// TODO Прописать логику для добавления
if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo);
if (collectionInfo.CollectionType == CollectionType.None)
throw new CollectionNoTypeException("Пустой тип коллекции");
throw new CollectionNoTypeException("Отсутсвует тип коллекции");
if (collectionInfo.CollectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionInfo.CollectionType == CollectionType.List)
@ -53,28 +53,24 @@ where T : DrawningLocomotive
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
public void DelCollection(CollectionInfo collectionInfo)
{
if (_storages.ContainsKey(name))
{
_storages.Remove(name);
}
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -107,41 +103,46 @@ where T : DrawningLocomotive
{
if (_storages.Count == 0)
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
throw new EmptyFileExeption();
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>>
value in _storages)
using (StreamWriter writer = new StreamWriter(filename))
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
continue;
}
sb.Append(value.Key);
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))
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
sb.Append(value.Key);
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);
}
writer.Write(sb);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
}
/// <summary>
@ -151,23 +152,24 @@ where T : DrawningLocomotive
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не существует");
throw new FileNotFoundException(filename);
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
if (string.IsNullOrEmpty(str))
{
throw new Exception("В файле нет данных");
throw new EmptyFileExeption(filename);
}
if (!str.StartsWith(_collectionKey))
{
throw new Exception("В файле неверные данные");
throw new FileFormatException(filename);
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
@ -177,34 +179,33 @@ where T : DrawningLocomotive
{
continue;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
CollectionInfo? collectionInfo =
CollectionInfo.GetCollectionInfo(record[0]) ??
throw new CollectionNoInfoException("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new CollectionNoTypeException("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningLocomotive() is T locomotive)
if (elem?.CreateDrawningLocomotive() is T macine)
{
try
{
if (collection.Insert(locomotive) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
collection.Insert(macine);
}
catch (CollectionOverflowException ex)
catch (Exception ex)
{
throw new Exception("Коллекция переполнена", ex);
throw new FileFormatException(filename, ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,21 @@
using ProjectElectricLocomotive.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
[Serializable]
public class CollectionExistsException : Exception
{
public CollectionExistsException() : base() { }
public CollectionExistsException(CollectionInfo collectionInfo) : base("Коллекция " + collectionInfo + " уже создана") { }
public CollectionExistsException(string name, Exception exception) : base("Коллекция " + name + " уже создана", exception)
{ }
protected CollectionExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
public class CollectionNoInfoException : Exception
{
public CollectionNoInfoException() : base() { }
public CollectionNoInfoException(string message) : base(message) { }
public CollectionNoInfoException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionNoInfoException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,22 @@
using ProjectElectricLocomotive.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions
{
[Serializable]
public class CollectionNoTypeException : Exception
{
public CollectionNoTypeException() : base() { }
public CollectionNoTypeException(string message) : base(message) { }
public CollectionNoTypeException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionNoTypeException(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 ProjectElectricLocomotive.Exceptions
{
public class EmptyFileExeption : Exception
{
public EmptyFileExeption(string name) : base("Файл" + name + "пустой ") { }
public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { }
public EmptyFileExeption(string name, string message) : base(message) { }
public EmptyFileExeption(string name, string message, Exception exception) :
base(message, exception)
{ }
protected EmptyFileExeption(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}
}

View File

@ -195,14 +195,13 @@ public partial class FormLocomotiveCollection : Form
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
CollectionInfo? col = _storageCollection.Keys?[i];
if (!col!.IsEmpty())
{
listBoxCollection.Items.Add(colName);
listBoxCollection.Items.Add(col);
}
}
}
@ -219,18 +218,21 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningLocomotive>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
_storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Депо":
_company = new LocomotiveDepo(pictureBox.Width,
pictureBox.Height, collection);
case "Хранилище":
_company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
@ -246,25 +248,23 @@ public partial class FormLocomotiveCollection : Form
/// <param name="e"></param>
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
try
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
return;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
/// <summary>
@ -276,27 +276,29 @@ public partial class FormLocomotiveCollection : Form
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try
{
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ"));
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
}