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

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(); 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 Прописать логику для добавления // TODO Прописать логику для добавления
if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo); if (_storages.ContainsKey(collectionInfo)) throw new CollectionExistsException(collectionInfo);
if (collectionInfo.CollectionType == CollectionType.None) if (collectionInfo.CollectionType == CollectionType.None)
throw new CollectionNoTypeException("Пустой тип коллекции"); throw new CollectionNoTypeException("Отсутсвует тип коллекции");
if (collectionInfo.CollectionType == CollectionType.Massive) if (collectionInfo.CollectionType == CollectionType.Massive)
_storages[collectionInfo] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionInfo.CollectionType == CollectionType.List) else if (collectionInfo.CollectionType == CollectionType.List)
@ -53,28 +53,24 @@ where T : DrawningLocomotive
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(CollectionInfo collectionInfo)
{ {
if (_storages.ContainsKey(name))
{
_storages.Remove(name);
}
// TODO Прописать логику для удаления коллекции // TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
/// <returns></returns> /// <returns></returns>
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[CollectionInfo collectionInfo]
{ {
get get
{ {
if (_storages.ContainsKey(name))
{
return _storages[name];
}
// TODO Продумать логику получения объекта // TODO Продумать логику получения объекта
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null; return null;
} }
} }
@ -107,41 +103,46 @@ where T : DrawningLocomotive
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
throw new Exception("В хранилище отсутствуют коллекции для сохранения"); throw new EmptyFileExeption();
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder sb = new();
sb.Append(_collectionKey); using (StreamWriter writer = new StreamWriter(filename))
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>>
value in _storages)
{ {
sb.Append(Environment.NewLine); writer.Write(_collectionKey);
// не сохраняем пустые коллекции foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
if (value.Value.Count == 0)
{ {
continue; StringBuilder sb = new();
} sb.Append(Environment.NewLine);
sb.Append(value.Key); // не сохраняем пустые коллекции
sb.Append(_separatorForKeyValue); if (value.Value.Count == 0)
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; 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> /// <summary>
@ -151,23 +152,24 @@ where T : DrawningLocomotive
// /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns> // /// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
throw new Exception("Файл не существует"); throw new FileNotFoundException(filename);
} }
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 (string.IsNullOrEmpty(str))
{ {
throw new Exception("В файле нет данных"); throw new EmptyFileExeption(filename);
} }
if (!str.StartsWith(_collectionKey)) if (!str.StartsWith(_collectionKey))
{ {
throw new Exception("В файле неверные данные"); throw new FileFormatException(filename);
} }
_storages.Clear(); _storages.Clear();
string strs = ""; string strs = "";
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
@ -177,34 +179,33 @@ where T : DrawningLocomotive
{ {
continue; 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]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningLocomotive() is T locomotive) if (elem?.CreateDrawningLocomotive() is T macine)
{ {
try try
{ {
if (collection.Insert(locomotive) == -1) collection.Insert(macine);
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
} }
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> /// </summary>
private void RerfreshListBoxItems() private void RerfreshListBoxItems()
{ {
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; CollectionInfo? col = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName)) if (!col!.IsEmpty())
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(col);
} }
} }
} }
@ -219,18 +218,21 @@ public partial class FormLocomotiveCollection : Form
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
ICollectionGenericObjects<DrawningLocomotive>? collection = ICollectionGenericObjects<DrawningLocomotive>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; _storageCollection[
CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!) ??
new CollectionInfo("", CollectionType.None, "")];
if (collection == null) if (collection == null)
{ {
MessageBox.Show("Коллекция не проинициализирована"); MessageBox.Show("Коллекция не проинициализирована");
return; return;
} }
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Депо": case "Хранилище":
_company = new LocomotiveDepo(pictureBox.Width, _company = new LocomotiveDepo(pictureBox.Width, pictureBox.Height, collection);
pictureBox.Height, collection);
break; break;
} }
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
@ -246,25 +248,23 @@ public partial class FormLocomotiveCollection : Form
/// <param name="e"></param> /// <param name="e"></param>
private void buttonCollectionDel_Click(object sender, EventArgs e) private void buttonCollectionDel_Click(object sender, EventArgs e)
{ {
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{ {
MessageBox.Show("Коллекция не выбрана"); MessageBox.Show("Коллекция не выбрана");
return; return;
} }
try if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(listBoxCollection.SelectedItem.ToString()!);
_storageCollection.DelCollection(collectionInfo!);
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
} }
/// <summary> /// <summary>
@ -276,27 +276,29 @@ public partial class FormLocomotiveCollection : Form
{ {
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
try try
{ {
CollectionType collectionType = CollectionType.None; _storageCollection.AddCollection(new CollectionInfo(textBoxCollectionName.Text, collectionType, "ХЗ"));
if (radioButtonMassive.Checked) _logger.LogInformation("Добавление коллекции");
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems(); RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("Ошибка: {Message}", ex.Message); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
} }
} }