PIbd-13_YazykovaA.I._LABA07_Simple #7

Closed
squ_squ wants to merge 6 commits from Laba07 into Laba06
22 changed files with 736 additions and 173 deletions

View File

@ -32,7 +32,7 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight /(_placeSizeWidth * _placeSizeHeight);
private int GetMaxCount => _pictureWidth / _placeSizeWidth * (_pictureHeight / _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
@ -55,7 +55,7 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /(_placeSizeWidth * _p
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection.Insert(bus);
return company._collection.Insert(bus,new DrawiningBusEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -102,4 +102,5 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /(_placeSizeWidth * _p
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
namespace TrolleybusProject.CollectionGenericObjects;
public class DrawningBusCompareByType : IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null) return 0;
if (x == null || x.EntityBus == null)
{
return -1;
}
if (y == null || y.EntityBus == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -21,20 +21,20 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
@ -51,4 +51,9 @@ int Insert(T obj, int position);
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,8 +1,11 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects;
@ -40,28 +43,51 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Get(int position)
{
if (position >= Count || position < 0)
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
return -1;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Add(obj);
return _collection.Count;
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount || position < 0 || position > Count)
if (Count == _maxCount)
{
return -1;
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
throw new PositionOutOfCollectionException(position);
}
if (comparer != null)
{
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(_collection[i], obj))
{
throw new CollectionInsertException(obj);
}
}
}
_collection.Insert(position, obj);
@ -69,13 +95,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public T? Remove(int position)
{
if (_collection == null || position < 0 || position >= _collection.Count) {
return null;
if (position < 0 || position > Count)
{
throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
_collection[position] = null;
_collection.RemoveAt(position);
return obj;
}
@ -87,6 +112,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -3,6 +3,9 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects;
@ -50,67 +53,75 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= _collection.Length || position < 0)
if (position < 0 || position >= Count)
{
return null;
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
int index = 0;
while (index < _collection.Length)
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
throw new CollectionInsertException(obj);
}
return -1;
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
return -1;
if (_collection[position] != null)
for (int i = 0; i < Count; i++)
{
int nullIndex = -1;
for (int i = position + 1; i < Count; i++)
if (_collection[i] == null)
{
if (_collection[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
{
return -1;
}
int j = nullIndex - 1;
while (j >= position)
{
_collection[j + 1] = _collection[j];
j--;
_collection[i] = obj;
return i;
}
}
_collection[position] = obj;
return position;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer))
{
throw new CollectionInsertException(obj);
}
if (position >= Count || position < 0)
throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int temp = position + 1;
while (temp < Count)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
temp++;
}
temp = position - 1;
while (temp > 0)
{
if (_collection[temp] == null)
{
_collection[temp] = obj;
return temp;
}
temp--;
}
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? temp = _collection[position];
_collection[position] = null;
return temp;
@ -123,4 +134,14 @@ internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject.CollectionGenericObjects;
@ -90,11 +91,12 @@ public class StorageCollection<T>
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -130,25 +132,25 @@ public class StorageCollection<T>
}
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует!");
}
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
return false;
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
return false;
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
@ -163,25 +165,34 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T bus)
if (elem?.CreateDrawningBus() is T bus )
{
if (collection.Insert(bus) <0)
try
{
return false;
if (collection.Insert(bus) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.CollectionGenericObjects;
namespace TrolleybusProject;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string
description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator,
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0],
(CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ?
strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings;
internal class DrawiningBusEqutables: IEqualityComparer<DrawningBus?>
{
public bool Equals(DrawningBus? x, DrawningBus? y)
{
if (x == null || x.EntityBus == null)
{
return false;
}
if (y == null || y.EntityBus == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBus.Speed != y.EntityBus.Speed)
{
return false;
}
if (x.EntityBus.Weight != y.EntityBus.Weight)
{
return false;
}
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
return false;
}
if (x is DrawningTrolleybus && y is DrawningTrolleybus)
{
if (((EntityTrolleybus)x.EntityBus).AdditionalColor !=
((EntityTrolleybus)y.EntityBus).AdditionalColor)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Roga !=
((EntityTrolleybus)y.EntityBus).Roga)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Otsek !=
((EntityTrolleybus)y.EntityBus).Otsek)
{
return false;
}
if (((EntityTrolleybus)x.EntityBus).Doors !=
((EntityTrolleybus)y.EntityBus).Doors)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.Drawnings;
public class DrawningBusCompareByColor: IComparer<DrawningBus?>
{
public int Compare(DrawningBus? x, DrawningBus? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityBus== null)
{
return -1;
}
if (y == null || y.EntityBus == null)
{
return 1;
}
var bodycolorCompare = x.EntityBus.BodyColor.Name.CompareTo(y.EntityBus.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}

View File

@ -5,52 +5,49 @@ using System.Text;
using System.Threading.Tasks;
using TrolleybusProject.Entities;
namespace TrolleybusProject.Drawnings {
namespace TrolleybusProject.Drawnings;
public static class ExtentionDrawningBus
public static class ExtentionDrawningBus
{
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info)
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningBus? CreateDrawningBus(this string info)
string[] strs = info.Split(_separatorForObject);
EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs);
if (bus != null)
{
string[] strs = info.Split(_separatorForObject);
EntityBus? bus = EntityTrolleybus.CreateEntityTrolleybus(strs);
if (bus != null)
{
return new DrawningTrolleybus(bus);
}
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
return new DrawningTrolleybus(bus);
}
bus = EntityBus.CreateEntityBus(strs);
if (bus != null)
{
return new DrawningBus(bus);
}
return null;
}
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningBus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningBus drawningBus)
{
string[]? array = drawningBus?.EntityBus?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -0,0 +1,14 @@
using System.Runtime.Serialization;
using TrolleybusProject;
namespace ProjectTrolleybus.Exceptions;
public class CollectionAlreadyExistsException : Exception
{
public CollectionAlreadyExistsException() : base() { }
public CollectionAlreadyExistsException(CollectionInfo collectioninfo) : base($"Коллекция {collectioninfo} уже существует!") { }
public CollectionAlreadyExistsException(string name, Exception exception) :
base($"Коллекция {name} уже существует!", exception)
{ }
protected CollectionAlreadyExistsException(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;
public class CollectionInsertException : Exception
{
public CollectionInsertException(object obj) : base($"Объект {obj} повторяется") { }
public CollectionInsertException() : base() { }
public CollectionInsertException(string message) : base(message) { }
public CollectionInsertException(string message, Exception exception) :
base(message, exception)
{ }
protected CollectionInsertException(SerializationInfo info, StreamingContext
contex) : base(info, contex) { }
}

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 TrolleybusProject.Exceptions;
[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) { }
}

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 TrolleybusProject.Exceptions;
[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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace TrolleybusProject.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

@ -55,6 +55,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonByType = new Button();
ByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -71,7 +73,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(904, 33);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(300, 623);
groupBoxTools.Size = new Size(300, 702);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -88,7 +90,9 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(ByColor);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddBus);
panelCompanyTools.Controls.Add(buttonDelTrolleybus);
@ -96,7 +100,7 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(0, 397);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(294, 259);
panelCompanyTools.Size = new Size(294, 305);
panelCompanyTools.TabIndex = 9;
//
// buttonRefresh
@ -127,7 +131,7 @@
buttonAddBus.Location = new Point(26, 18);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(244, 34);
buttonAddBus.TabIndex = 1;
buttonAddBus.TabIndex = 2;
buttonAddBus.Text = "Добавление автобуса";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += buttonAddBus_Click;
@ -212,7 +216,7 @@
radioButtonMassive.Location = new Point(11, 65);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(98, 29);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabIndex = 1;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
@ -250,7 +254,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(904, 623);
pictureBox.Size = new Size(904, 702);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -263,7 +267,6 @@
menuStrip.Size = new Size(1204, 33);
menuStrip.TabIndex = 2;
menuStrip.Text = "Фаил";
//
// FileToolStripMenuItem
//
@ -281,7 +284,7 @@
//
save_ToolStripMenuItem.Name = "save_ToolStripMenuItem";
save_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
save_ToolStripMenuItem.Size = new Size(270, 34);
save_ToolStripMenuItem.Size = new Size(261, 34);
save_ToolStripMenuItem.Text = "Сохранить";
save_ToolStripMenuItem.Click += save_ToolStripMenuItem_Click;
//
@ -289,7 +292,7 @@
//
load_ToolStripMenuItem.Name = "load_ToolStripMenuItem";
load_ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
load_ToolStripMenuItem.Size = new Size(270, 34);
load_ToolStripMenuItem.Size = new Size(261, 34);
load_ToolStripMenuItem.Text = "Загрузить";
load_ToolStripMenuItem.Click += load_ToolStripMenuItem_Click;
//
@ -315,11 +318,33 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonByType
//
buttonByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByType.Location = new Point(6, 259);
buttonByType.Name = "buttonByType";
buttonByType.Size = new Size(268, 34);
buttonByType.TabIndex = 8;
buttonByType.Text = "Сравнить по типу";
buttonByType.UseVisualStyleBackColor = true;
buttonByType.Click += button1_Click;
//
// ByColor
//
ByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
ByColor.Location = new Point(23, 215);
ByColor.Name = "ByColor";
ByColor.Size = new Size(247, 38);
ByColor.TabIndex = 7;
ByColor.Text = "Сравнить по цвету";
ByColor.UseVisualStyleBackColor = true;
ByColor.Click += ByColor_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1204, 656);
ClientSize = new Size(1204, 735);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -367,5 +392,7 @@
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem save_ToolStripMenuItem;
private ToolStripMenuItem load_ToolStripMenuItem;
private Button buttonByType;
private Button ByColor;
}
}

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -9,6 +10,7 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using TrolleybusProject.CollectionGenericObjects;
using TrolleybusProject.Drawnings;
using TrolleybusProject.Exceptions;
namespace TrolleybusProject;
@ -23,12 +25,18 @@ public partial class FormBusCollection : Form
/// </summary>
private AbstractCompany? _company = null;
public FormBusCollection()
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
private void buttonAddBus_Click(object sender, EventArgs e)
{
BusConfig form = new();
@ -41,14 +49,22 @@ public partial class FormBusCollection : Form
{
return;
}
if (_company + bus != -1)
try
{
int addingObject = (_company + bus);
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {bus.GetDataForSave()}");
pictureBox.Image = _company.Show();
}
else
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (CollectionInsertException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка:обьект повторяется {0}", bus);
}
}
@ -67,20 +83,30 @@ public partial class FormBusCollection : Form
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
else
{
MessageBox.Show($"Не удалось удалить объект");
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -90,13 +116,23 @@ public partial class FormBusCollection : Form
{
return;
}
DrawningBus? bus = null;
int counter = 100;
while (bus == null)
{
bus = _company.GetRandomObject();
counter--;
try
{
bus = _company.GetRandomObject();
}
catch (ObjectNotFoundException)
{
counter--;
if (counter <= 0)
{
break;
}
}
}
if (bus == null)
{
@ -122,10 +158,11 @@ public partial class FormBusCollection : Form
private void buttonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) ||
(!radioButtonList.Checked && !radioButtonMassive.Checked))
(!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не заполненная коллекция");
return;
}
CollectionType collectionType = CollectionType.None;
@ -137,10 +174,9 @@ public partial class FormBusCollection : Form
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text,
collectionType);
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation($"Добавлена коллекция: {textBoxCollectionName.Text}");
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
@ -150,7 +186,7 @@ public partial class FormBusCollection : Form
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -159,19 +195,19 @@ public partial class FormBusCollection : Form
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null) return;
if (listBoxCollection.SelectedIndex < 0)
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Удаление невыбранной коллекции");
return;
}
string name = listBoxCollection.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation($"Удалена коллекция: {name}");
RerfreshListBoxItems();
}
@ -181,6 +217,7 @@ public partial class FormBusCollection : Form
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
_logger.LogWarning("Создание компании невыбранной коллекции");
return;
}
ICollectionGenericObjects<DrawningBus>? collection =
@ -188,6 +225,7 @@ public partial class FormBusCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
_logger.LogWarning("Не удалось инициализировать коллекцию");
return;
}
switch (comboBoxSelectionCompany.Text)
@ -205,37 +243,72 @@ public partial class FormBusCollection : Form
{
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("Не сохранилось", "Результат",
MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void load_ToolStripMenuItem_Click(object sender, EventArgs e)
{
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);
_logger.LogInformation("Загрузка из файла: {filename}", saveFileDialog.FileName);
RerfreshListBoxItems();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось загрузить", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByType());
}
private void ByColor_Click(object sender, EventArgs e)
{
CompareBus(new DrawningBusCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareBus(IComparer<DrawningBus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -63,6 +63,5 @@ namespace TrolleybusProject.MovementStrategy
_height = height;
}
}
}

View File

@ -1,17 +1,40 @@
namespace TrolleybusProject
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace TrolleybusProject;
internal static class Program
{
internal static class Program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormBusCollection());
}
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ServiceCollection services = new();
ConfigureServices(services);
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);
var config = new ConfigurationBuilder()
.AddJsonFile("serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
option.AddSerilog(Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger());
});
}
}

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +37,13 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
<?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>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Trolleybus"
}
}
}